Merge branch 'restframework2' of https://github.com/tomchristie/django-rest-framework into patch

This commit is contained in:
Marko Tibold 2012-10-29 22:00:25 +01:00
commit 19bffc6b51
36 changed files with 926 additions and 339 deletions

View File

@ -50,7 +50,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
Or, if you're using the `@api_view` decorator with function based views.
@api_view(('GET',)),
@api_view(['GET'])
@authentication_classes((SessionAuthentication, UserBasicAuthentication))
@permissions_classes((IsAuthenticated,))
def example_view(request, format=None):

View File

@ -12,6 +12,51 @@ Serializer fields handle converting between primative values and internal dataty
**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
---
## Core arguments
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
### `source`
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`.
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the `PaginationSerializer` class for an example.)
Defaults to the name of the field.
### `read_only`
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
Defaults to `False`
### `required`
Normally an error will be raised if a field is not supplied during deserialization.
Set to false if this field is not required to be present during deserialization.
Defaults to `True`.
### `default`
If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all.
### `validators`
A list of Django validators that should be used to validate deserialized values.
### `error_messages`
A dictionary of error codes to error messages.
### `widget`
Used only if rendering the field to HTML.
This argument sets the widget that should be used to render the field.
---
# Generic Fields
@ -192,24 +237,42 @@ Then an example output format for a Bookmark instance would be:
## PrimaryKeyRelatedField
As with `RelatedField` field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## ManyPrimaryKeyRelatedField
As with `RelatedField` field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
`PrimaryKeyRelatedField` will represent the target of the field using their primary key.
`PrimaryKeyRelatedField` will represent the targets of the field using their primary key.
Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## HyperlinkedRelatedField
This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## ManyHyperlinkedRelatedField
This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## HyperLinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the model.
This field is always read-only.
[cite]: http://www.python.org/dev/peps/pep-0020/

View File

@ -37,7 +37,7 @@ You can also set the renderers used for an individual view, using the `APIView`
Or, if you're using the `@api_view` decorator with function based views.
@api_view(('POST',)),
@api_view(['POST'])
@parser_classes((YAMLParser,))
def example_view(request, format=None):
"""

View File

@ -33,6 +33,12 @@ The default permission policy may be set globally, using the `DEFAULT_PERMISSION
)
}
If not specified, this setting defaults to allowing unrestricted access:
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
)
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
class ExampleView(APIView):
@ -58,6 +64,12 @@ Or, if you're using the `@api_view` decorator with function based views.
# API Reference
## AllowAny
The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.
## IsAuthenticated
The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
@ -66,7 +78,7 @@ This permission is suitable if you want your API to only be accessible to regist
## IsAdminUser
The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff`is `True` in which case permission will be allowed.
The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.

View File

@ -42,7 +42,7 @@ You can also set the renderers used for an individual view, using the `APIView`
Or, if you're using the `@api_view` decorator with function based views.
@api_view(('GET',)),
@api_view(['GET'])
@renderer_classes((JSONRenderer, JSONPRenderer))
def user_count_view(request, format=None):
"""
@ -106,12 +106,12 @@ If you are considering using `XML` for your API, you may want to consider implem
**.format**: `'.xml'`
## HTMLRenderer
## TemplateHTMLRenderer
Renders data to HTML, using Django's standard template rendering.
Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`.
The HTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
The template name is determined by (in order of preference):
@ -119,27 +119,49 @@ The template name is determined by (in order of preference):
2. An explicit `.template_name` attribute set on this class.
3. The return result of calling `view.get_template_names()`.
An example of a view that uses `HTMLRenderer`:
An example of a view that uses `TemplateHTMLRenderer`:
class UserInstance(generics.RetrieveUserAPIView):
"""
A view that returns a templated HTML representations of a given user.
"""
model = Users
renderer_classes = (HTMLRenderer,)
renderer_classes = (TemplateHTMLRenderer,)
def get(self, request, *args, **kwargs)
self.object = self.get_object()
return Response({'user': self.object}, template_name='user_detail.html')
You can use `HTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
If you're building websites that use `HTMLRenderer` along with other renderer classes, you should consider listing `HTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
**.media_type**: `text/html`
**.format**: `'.html'`
See also: `StaticHTMLRenderer`
## StaticHTMLRenderer
A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
An example of a view that uses `TemplateHTMLRenderer`:
@api_view(('GET',))
@renderer_classes((StaticHTMLRenderer,))
def simple_html_view(request):
data = '<html><body><h1>Hello, world</h1></body></html>'
return Response(data)
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
**.media_type**: `text/html`
**.format**: `'.html'`
See also: `TemplateHTMLRenderer`
## BrowsableAPIRenderer
Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
@ -207,7 +229,7 @@ In some cases you might want your view to use different serialization styles dep
For example:
@api_view(('GET',))
@renderer_classes((HTMLRenderer, JSONRenderer))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def list_users(request):
"""
A view that can return JSON or HTML representations
@ -215,9 +237,9 @@ For example:
"""
queryset = Users.objects.filter(active=True)
if request.accepted_media_type == 'text/html':
if request.accepted_renderer.format == 'html':
# TemplateHTMLRenderer takes a context dict,
# and additionally requiresa 'template_name'.
# and additionally requires a 'template_name'.
# It does not require serialization.
data = {'users': queryset}
return Response(data, template_name='list_users.html')

View File

@ -107,21 +107,21 @@ where some of the attributes of an object might not be simple datatypes such as
The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another.
class UserSerializer(serializers.Serializer):
email = serializers.EmailField()
username = serializers.CharField()
def restore_object(self, attrs, instance=None):
return User(**attrs)
email = serializers.Field()
username = serializers.Field()
class CommentSerializer(serializers.Serializer):
user = UserSerializer()
title = serializers.CharField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
return Comment(**attrs)
title = serializers.Field()
content = serializers.Field()
created = serializers.Field()
---
**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses.
---
## Creating custom fields
@ -135,7 +135,6 @@ Let's look at an example of serializing a class that represents an RGB color val
"""
A color represented in the RGB colorspace.
"""
def __init__(self, red, green, blue):
assert(red >= 0 and green >= 0 and blue >= 0)
assert(red < 256 and green < 256 and blue < 256)
@ -145,7 +144,6 @@ Let's look at an example of serializing a class that represents an RGB color val
"""
Color objects are serialized into "rgb(#, #, #)" notation.
"""
def to_native(self, obj):
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
@ -190,7 +188,7 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit
You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class.
class AccountSerializer(serializers.ModelSerializer):
url = CharField(source='get_absolute_url', readonly=True)
url = CharField(source='get_absolute_url', read_only=True)
group = NaturalKeyField()
class Meta:
@ -225,40 +223,54 @@ For example:
## Specifiying nested serialization
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `nested` option:
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
exclude = ('id',)
nested = True
depth = 1
The `nested` option may be set to either `True`, `False`, or an integer value. If given an integer value it indicates the depth of relationships that should be traversed before reverting to a flat representation.
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation.
## Customising the default fields
## Customising the default fields used by a ModelSerializer
You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get_<field_type>_field` methods.
Each of these methods may either return a field or serializer instance, or `None`.
### get_pk_field
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
**Signature**: `.get_pk_field(self, model_field)`
Returns the field instance that should be used to represent the pk field.
### get_nested_field
**Signature**: `.get_nested_field(self, model_field)`
Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
### get_related_field
**Signature**: `.get_related_field(self, model_field, to_many=False)`
Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero.
### get_field
**Signature**: `.get_field(self, model_field)`
Returns the field instance that should be used for non-relational, non-pk fields.
### Example:
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
class NoPKModelSerializer(serializers.ModelSerializer):
def get_pk_field(self, model_field):
return serializers.Field(readonly=True)
return None
def get_nested_field(self, model_field):
return serializers.ModelSerializer()
def get_related_field(self, model_field, to_many=False):
queryset = model_field.rel.to._default_manager
if to_many:
return serializers.ManyRelatedField(queryset=queryset)
return serializers.RelatedField(queryset=queryset)
def get_field(self, model_field):
return serializers.ModelField(model_field=model_field)
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion

View File

@ -42,7 +42,7 @@ Default:
(
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework.renderers.TemplateHTMLRenderer'
)
@ -72,7 +72,11 @@ Default:
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
Default: `()`
Default:
(
'rest_framework.permissions.AllowAny',
)
## DEFAULT_THROTTLE_CLASSES

View File

@ -32,8 +32,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttles.AnonThrottle',
'rest_framework.throttles.UserThrottle',
)
'rest_framework.throttles.UserThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
@ -102,8 +102,8 @@ For example, multiple user throttle rates could be implemented by using the foll
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'example.throttles.BurstRateThrottle',
'example.throttles.SustainedRateThrottle',
)
'example.throttles.SustainedRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'burst': '60/min',
'sustained': '1000/day'
@ -136,8 +136,8 @@ For example, given the following views...
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttles.ScopedRateThrottle',
)
'rest_framework.throttles.ScopedRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'

View File

@ -122,7 +122,7 @@ REST framework also allows you to work with regular function based views. It pro
## @api_view()
**Signature:** `@api_view(http_method_names)
**Signature:** `@api_view(http_method_names)`
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:

View File

@ -67,9 +67,8 @@ The tutorial will walk you through the building blocks that make up REST framewo
* [1 - Serialization][tut-1]
* [2 - Requests & Responses][tut-2]
* [3 - Class based views][tut-3]
* [4 - Authentication, permissions & throttling][tut-4]
* [4 - Authentication & permissions][tut-4]
* [5 - Relationships & hyperlinked APIs][tut-5]
<!-- * [6 - Resource orientated projects][tut-6]-->
## API Guide
@ -98,11 +97,9 @@ The API guide is your complete reference manual to all the functionality provide
General guides to using REST framework.
* [CSRF][csrf]
* [Browser enhancements][browser-enhancements]
* [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [Contributing to REST framework][contributing]
* [2.0 Announcement][rest-framework-2-announcement]
* [Release Notes][release-notes]
* [Credits][credits]
@ -119,7 +116,6 @@ Run the tests:
./rest_framework/runtests/runtests.py
For more information see the [Contributing to REST framework][contributing] section.
## Support
For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`.
@ -161,9 +157,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[tut-1]: tutorial/1-serialization.md
[tut-2]: tutorial/2-requests-and-responses.md
[tut-3]: tutorial/3-class-based-views.md
[tut-4]: tutorial/4-authentication-permissions-and-throttling.md
[tut-4]: tutorial/4-authentication-and-permissions.md
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
[tut-6]: tutorial/6-resource-orientated-projects.md
[request]: api-guide/requests.md
[response]: api-guide/responses.md

View File

@ -57,9 +57,8 @@
<li><a href="{{ base_url }}/tutorial/1-serialization{{ suffix }}">1 - Serialization</a></li>
<li><a href="{{ base_url }}/tutorial/2-requests-and-responses{{ suffix }}">2 - Requests and responses</a></li>
<li><a href="{{ base_url }}/tutorial/3-class-based-views{{ suffix }}">3 - Class based views</a></li>
<li><a href="{{ base_url }}/tutorial/4-authentication-permissions-and-throttling{{ suffix }}">4 - Authentication, permissions and throttling</a></li>
<li><a href="{{ base_url }}/tutorial/4-authentication-and-permissions{{ suffix }}">4 - Authentication and permissions</a></li>
<li><a href="{{ base_url }}/tutorial/5-relationships-and-hyperlinked-apis{{ suffix }}">5 - Relationships and hyperlinked APIs</a></li>
<!-- <li><a href="{{ base_url }}/tutorial/6-resource-orientated-projects{{ suffix }}">6 - Resource orientated projects</a></li> -->
</ul>
</li>
<li class="dropdown">
@ -88,11 +87,9 @@
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="{{ base_url }}/topics/csrf{{ suffix }}">Working with AJAX and CSRF</a></li>
<li><a href="{{ base_url }}/topics/browser-enhancements{{ suffix }}">Browser enhancements</a></li>
<li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li>
<li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
<li><a href="{{ base_url }}/topics/contributing{{ suffix }}">Contributing to REST framework</a></li>
<li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
<li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li>
<li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>

View File

@ -50,6 +50,7 @@ The following people have helped make REST framework great.
* Rob Dobson - [rdobson]
* Daniel Vaca Araujo - [diviei]
* Madis Väin - [madisvain]
* Stephan Groß - [minddust]
Many thanks to everyone who's contributed to the project.
@ -131,3 +132,4 @@ To contact the author directly:
[rdobson]: https://github.com/rdobson
[diviei]: https://github.com/diviei
[madisvain]: https://github.com/madisvain
[minddust]: https://github.com/minddust

View File

@ -56,16 +56,6 @@ REST framework 2 also allows you to work with both function-based and class-base
Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
## Documentation
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
In the author's opinion, using `markdown` for documentation is a much better option that `rst`. It is intuitive and readable, and there is great tooling available, such as the [Mou][mou] editor for Mac OS X, which makes it easy and plesant to work.
We're really pleased with how the docs style looks - it's simple and clean, and the docs build much more quickly than with the previous sphinx setup. We'll miss being able to use the wonderful [Read the Docs][readthedocs] service, but we think it's a trade-off worth making.
Developing REST framework's documentation builder into a fully-fledged reusable project is something that we have planned for a future date.
## The Browseable API
Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
@ -76,6 +66,16 @@ With REST framework 2, the browseable API gets a snazzy new bootstrap-based them
There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
![Browseable API][image]
**Image above**: An example of the browseable API in REST framework 2
## Documentation
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.
## Summary
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
@ -84,5 +84,5 @@ In short, we've engineered the hell outta this thing, and we're incredibly proud
[quote1]: https://twitter.com/kobutsu/status/261689665952833536
[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
[mou]: http://mouapp.com/
[image]: ../img/quickstart.png
[readthedocs]: https://readthedocs.org/

View File

@ -2,7 +2,9 @@
## Introduction
This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together.
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
## Setting up a new environment
@ -17,6 +19,7 @@ Now that we're inside a virtualenv environment, we can install our package requi
pip install django
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
**Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].
@ -30,8 +33,9 @@ To get started, let's create a new project to work with.
cd tutorial
Once that's done we can create an app that we'll use to create a simple Web API.
We're going to create a project that
python manage.py startapp blog
python manage.py startapp snippets
The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`.
@ -46,32 +50,48 @@ The simplest way to get up and running will probably be to use an `sqlite3` data
}
}
We'll also need to add our new `blog` app and the `rest_framework` app to `INSTALLED_APPS`.
We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`.
INSTALLED_APPS = (
...
'rest_framework',
'blog'
'snippets'
)
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our blog views.
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet views.
urlpatterns = patterns('',
url(r'^', include('blog.urls')),
url(r'^', include('snippets.urls')),
)
Okay, we're ready to roll.
## Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple `Comment` model that is used to store comments against a blog post. Go ahead and edit the `blog` app's `models.py` file.
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file.
from django.db import models
class Comment(models.Model):
email = models.EmailField()
content = models.CharField(max_length=200)
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()])
STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles()))
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
class Meta:
ordering = ('created',)
Don't forget to sync the database for the first time.
@ -79,28 +99,40 @@ Don't forget to sync the database for the first time.
## Creating a Serializer class
We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the `blog` directory named `serializers.py` and add the following.
The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similarly to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
from blog import models
from django.forms import widgets
from rest_framework import serializers
from snippets import models
class CommentSerializer(serializers.Serializer):
id = serializers.IntegerField(readonly=True)
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField(readonly=True)
class SnippetSerializer(serializers.Serializer):
pk = serializers.Field() # Note: `Field` is an untyped read-only field.
title = serializers.CharField(required=False,
max_length=100)
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES,
default='python')
style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
default='friendly')
def restore_object(self, attrs, instance=None):
"""
Create or update a new comment instance.
Create or update a new snippet instance.
"""
if instance:
instance.email = attrs['email']
instance.content = attrs['content']
instance.created = attrs['created']
# Update existing instance
instance.title = attrs['title']
instance.code = attrs['code']
instance.linenos = attrs['linenos']
instance.language = attrs['language']
instance.style = attrs['style']
return instance
return models.Comment(**attrs)
# Create new instance
return models.Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@ -112,31 +144,27 @@ Before we go any further we'll familiarise ourselves with using our new Serializ
python manage.py shell
Okay, once we've got a few imports out of the way, we'd better create a few comments to work with.
Okay, once we've got a few imports out of the way, let's create a code snippet to work with.
from blog.models import Comment
from blog.serializers import CommentSerializer
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
c1 = Comment(email='leila@example.com', content='nothing to say')
c2 = Comment(email='tom@example.com', content='foo bar')
c3 = Comment(email='anna@example.com', content='LOLZ!')
c1.save()
c2.save()
c3.save()
snippet = Snippet(code='print "hello, world"\n')
snippet.save()
We've now got a few comment instances to play with. Let's take a look at serializing one of those instances.
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
serializer = CommentSerializer(instance=c1)
serializer = SnippetSerializer(instance=snippet)
serializer.data
# {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=<UTC>)}
# {'pk': 1, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data)
content
# '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
# '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into python native datatypes...
@ -147,101 +175,115 @@ Deserialization is similar. First we parse a stream into python native datatype
...then we restore those native datatypes into to a fully populated object instance.
serializer = CommentSerializer(data)
serializer = SnippetSerializer(data)
serializer.is_valid()
# True
serializer.object
# <Comment: Comment object>
# <Snippet: Snippet object>
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
## Writing regular Django views using our Serializers
## Using ModelSerializers
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep out code a bit more concise.
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
Let's look at refactoring our serializer using the `ModelSerializer` class.
Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` class.
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = models.Snippet
fields = ('pk', 'title', 'code', 'linenos', 'language', 'style')
## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class.
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`.
Edit the `blog/views.py` file, and add the following.
Edit the `snippet/views.py` file, and add the following.
from blog.models import Comment
from blog.serializers import CommentSerializer
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders it's content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment.
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt
def comment_root(request):
def snippet_list(request):
"""
List all comments, or create a new comment.
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
comments = Comment.objects.all()
serializer = CommentSerializer(instance=comments)
snippets = Snippet.objects.all()
serializer = SnippetSerializer(instance=snippets)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CommentSerializer(data)
serializer = SnippetSerializer(data)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return JSONResponse(serializer.data, status=201)
else:
return JSONResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
@csrf_exempt
def comment_instance(request, pk):
def snippet_detail(request, pk):
"""
Retrieve, update or delete a comment instance.
Retrieve, update or delete a code snippet.
"""
try:
comment = Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = CommentSerializer(instance=comment)
serializer = SnippetSerializer(instance=snippet)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CommentSerializer(data, instance=comment)
serializer = SnippetSerializer(data, instance=snippet)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return JSONResponse(serializer.data)
else:
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
comment.delete()
snippet.delete()
return HttpResponse(status=204)
Finally we need to wire these views up. Create the `blog/urls.py` file:
Finally we need to wire these views up. Create the `snippets/urls.py` file:
from django.conf.urls import patterns, url
urlpatterns = patterns('blog.views',
url(r'^$', 'comment_root'),
url(r'^(?P<pk>[0-9]+)$', 'comment_instance')
urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail')
)
It's worth noting that there's a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
@ -260,5 +302,6 @@ Our API views don't do anything particularly special at the moment, beyond serve
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
[quickstart]: quickstart.md
[virtualenv]: http://www.virtualenv.org/en/latest/index.html
[tut-2]: 2-requests-and-responses.md

View File

@ -38,27 +38,27 @@ Okay, let's go ahead and start using these new components to write a few views.
We don't need our `JSONResponse` class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.
from blog.models import Comment
from blog.serializers import CommentSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippet.models import Snippet
from snippet.serializers import SnippetSerializer
@api_view(['GET', 'POST'])
def comment_root(request):
def snippet_list(request):
"""
List all comments, or create a new comment.
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
comments = Comment.objects.all()
serializer = CommentSerializer(instance=comments)
snippets = Snippet.objects.all()
serializer = SnippetSerializer(instance=snippets)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CommentSerializer(request.DATA)
serializer = SnippetSerializer(request.DATA)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@ -67,30 +67,29 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
@api_view(['GET', 'PUT', 'DELETE'])
def comment_instance(request, pk):
def snippet_detail(request, pk):
"""
Retrieve, update or delete a comment instance.
Retrieve, update or delete a snippet instance.
"""
try:
comment = Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = CommentSerializer(instance=comment)
serializer = SnippetSerializer(instance=snippet)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = CommentSerializer(request.DATA, instance=comment)
serializer = SnippetSerializer(request.DATA, instance=snippet)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
comment.delete()
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
This should all feel very familiar - there's not a lot different to working with regular Django views.
@ -103,20 +102,20 @@ To take advantage of the fact that our responses are no longer hardwired to a si
Start by adding a `format` keyword argument to both of the views, like so.
def comment_root(request, format=None):
def snippet_list(request, format=None):
and
def comment_instance(request, pk, format=None):
def snippet_detail(request, pk, format=None):
Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = patterns('blog.views',
url(r'^$', 'comment_root'),
url(r'^(?P<pk>[0-9]+)$', 'comment_instance')
urlpatterns = patterns('snippet.views',
url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail')
)
urlpatterns = format_suffix_patterns(urlpatterns)
@ -129,7 +128,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][
**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][devserver]."
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]."
**Note: Right now the Browseable API only works with the CBV's. Need to fix that.**
@ -145,7 +144,7 @@ See the [browsable api][browseable-api] topic for more information about the bro
In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write.
[json-url]: http://example.com/api/items/4.json
[devserver]: http://127.0.0.1:8000/
[devserver]: http://127.0.0.1:8000/snippets/
[browseable-api]: ../topics/browsable-api.md
[tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md

View File

@ -6,61 +6,59 @@ We can also write our API views using class based views, rather than function ba
We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
from blog.models import Comment
from blog.serializers import CommentSerializer
from snippet.models import Snippet
from snippet.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class CommentRoot(APIView):
class SnippetList(APIView):
"""
List all comments, or create a new comment.
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
comments = Comment.objects.all()
serializer = CommentSerializer(instance=comments)
snippets = Snippet.objects.all()
serializer = SnippetSerializer(instance=snippets)
return Response(serializer.data)
def post(self, request, format=None):
serializer = CommentSerializer(request.DATA)
serializer = SnippetSerializer(request.DATA)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view.
class CommentInstance(APIView):
class SnippetDetail(APIView):
"""
Retrieve, update or delete a comment instance.
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(instance=comment)
snippet = self.get_object(pk)
serializer = SnippetSerializer(instance=snippet)
return Response(serializer.data)
def put(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(request.DATA, instance=comment)
snippet = self.get_object(pk)
serializer = SnippetSerializer(request.DATA, instance=snippet)
if serializer.is_valid():
comment = serializer.object
comment.save()
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
comment = self.get_object(pk)
comment.delete()
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
That's looking good. Again, it's still pretty similar to the function based view right now.
@ -69,11 +67,11 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from blogpost import views
from snippetpost import views
urlpatterns = patterns('',
url(r'^$', views.CommentRoot.as_view()),
url(r'^(?P<pk>[0-9]+)$', views.CommentInstance.as_view())
url(r'^$', views.SnippetList.as_view()),
url(r'^(?P<pk>[0-9]+)$', views.SnippetDetail.as_view())
)
urlpatterns = format_suffix_patterns(urlpatterns)
@ -88,16 +86,16 @@ The create/retrieve/update/delete operations that we've been using so far are go
Let's take a look at how we can compose our views by using the mixin classes.
from blog.models import Comment
from blog.serializers import CommentSerializer
from snippet.models import Snippet
from snippet.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics
class CommentRoot(mixins.ListModelMixin,
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.MultipleObjectBaseView):
model = Comment
serializer_class = CommentSerializer
model = Snippet
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
@ -109,12 +107,12 @@ We'll take a moment to examine exactly what's happening here - We're building ou
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
class CommentInstance(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.SingleObjectBaseView):
model = Comment
serializer_class = CommentSerializer
class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.SingleObjectBaseView):
model = Snippet
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
@ -131,23 +129,23 @@ Pretty similar. This time we're using the `SingleObjectBaseView` class to provi
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use.
from blog.models import Comment
from blog.serializers import CommentSerializer
from snippet.models import Snippet
from snippet.serializers import SnippetSerializer
from rest_framework import generics
class CommentRoot(generics.ListCreateAPIView):
model = Comment
serializer_class = CommentSerializer
class SnippetList(generics.ListCreateAPIView):
model = Snippet
serializer_class = SnippetSerializer
class CommentInstance(generics.RetrieveUpdateDestroyAPIView):
model = Comment
serializer_class = CommentSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
model = Snippet
serializer_class = SnippetSerializer
Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django.
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API.
[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
[tut-4]: 4-authentication-permissions-and-throttling.md
[tut-4]: 4-authentication-and-permissions.md

View File

@ -0,0 +1,189 @@
# Tutorial 4: Authentication & Permissions
Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
* Code snippets are always associated with a creator.
* Only authenticated users may create snippets.
* Only the creator of a snippet may update or delete it.
* Unauthenticated requests should have full read-only access.
## Adding information to our model
We're going to make a couple of changes to our `Snippet` model class.
First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
Add the following two fields to the model.
owner = models.ForeignKey('auth.User', related_name='snippets')
highlighted = models.TextField()
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code higlighting library.
We'll ned some extra imports:
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments import highlight
And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create an highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm tmp.db
python ./manage.py syncdb
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
python ./manage.py createsuperuser
## Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy:
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.ManyPrimaryKeyRelatedField()
class Meta:
model = User
fields = ('pk', 'username', 'snippets')
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we've needed to add an explicit field for it.
We'll also add a couple of views. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views.
class UserList(generics.ListAPIView):
model = User
serializer_class = UserSerializer
class UserInstance(generics.RetrieveAPIView):
model = User
serializer_class = UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf.
url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view())
## Associating Snippets with Users
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.
On **both** the `SnippetList` and `SnippetInstance` view classes, add the following method:
def pre_save(self, obj):
obj.owner = self.request.user
## Updating our serializer
Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that.
Add the following field to the serializer definition:
owner = serializers.Field(source='owner.username')
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
This field is doing something quite interesting. The `source` argument controls which attribtue is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language.
The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
**TODO: Explain the SessionAuthentication and BasicAuthentication classes, and demonstrate using HTTP basic authentication with curl requests**
## Adding required permissions to views
Now that code snippets are associated with users we want to make sure that only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
Add the following property to **both** the `SnippetList` and `SnippetInstance` view classes.
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
**TODO: Now that the permissions are restricted, demonstrate using HTTP basic authentication with curl requests**
## Adding login to the Browseable API
If you open a browser and navigate to the browseable API at the moment, you'll find you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
We can add a login view for use with the browseable API, by editing our URLconf once more.
Add the following import at the top of the file:
from django.conf.urls import include
And, at the end of the file, add a pattern to include the login and logout views for the browseable API.
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework'))
)
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.
## Object level permissions
Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able update or delete it.
To do that we're going to need to create a custom permission.
In the snippets app, create a new file, `permissions.py`
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view, obj=None):
# Skip the check unless this is an object-level test
if obj is None:
return True
# Read permissions are allowed to any request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet
return obj.owner == request.user
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetInstance` class:
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
Make sure to also import the `IsOwnerOrReadOnly` class.
from snippets.permissions import IsOwnerOrReadOnly
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
## Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
[tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -1,5 +0,0 @@
# Tutorial 4: Authentication & Permissions
Nothing to see here. Onwards to [part 5][tut-5].
[tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -1,11 +1,157 @@
# Tutorial 5 - Relationships & Hyperlinked APIs
**TODO**
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
* Create BlogPost model
* Demonstrate nested relationships
* Demonstrate and describe hyperlinked relationships
## Creating an endpoint for the root of our API
<!-- Onwards to [part 6][tut-6].
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier.
[tut-6]: 6-resource-orientated-projects.md -->
from rest_framework import renderers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(('GET',))
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request),
'snippets': reverse('snippet-list', request=request)
})
Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
## Creating an endpoint for the highlighted snippets
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two style of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concreate generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method.
class SnippetHighlight(generics.SingleObjectAPIView):
model = Snippet
renderer_classes = (renderers.StaticHTMLRenderer,)
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
As usual we need to add the new views that we've created in to our URLconf.
We'll add a url pattern for our new API root:
url(r'^$', 'api_root'),
And then add a url pattern for the snippet highlights:
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
## Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
* Using primary keys.
* Using hyperlinking between entities.
* Using a unique identifying slug field on the related entity.
* Using the default string representation of the related entity.
* Nesting the related entity inside the parent representation.
* Some other custom representation.
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`.
The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
* It does not include the `pk` field by default.
* It includes a `url` field, using `HyperlinkedIdentityField`.
* Relationships use `HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField`,
instead of `PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField`.
We can easily re-write our existing serializers to use hyperlinking.
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight')
class Meta:
model = models.Snippet
fields = ('url', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style')
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail')
class Meta:
model = User
fields = ('url', 'username', 'snippets')
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
## Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
* The root of our API refers to `'user-list'` and `'snippet-list'`.
* Our snippet serializer includes a field that refers to `'snippet-highlight'`.
* Our user serializer includes a field that refers to `'snippet-detail'`.
* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`.
After adding all those names into our URLconf, our final `'urls.py'` file should look something like this:
# API endpoints
urlpatterns = format_suffix_patterns(patterns('snippets.views',
url(r'^$', 'api_root'),
url(r'^snippets/$',
views.SnippetList.as_view(),
name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetInstance.as_view(),
name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$'
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
url(r'^users/$',
views.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$',
views.UserInstance.as_view(),
name='user-detail')
))
# Login and logout views for the browsable API
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework'))
)
## Reviewing our work
If we open a browser and navigate to the browseable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the hightlighted code HTML representations.
We've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
* Contribute on [GitHub][github] by reviewing and subitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.
* Follow the author [on Twitter][twitter] and say hi.
**Now go build some awesome things.**
[repo]: https://github.com/tomchristie/rest-framework-tutorial
[sandbox]: http://sultry-coast-6726.herokuapp.com/
[github]: https://github.com/tomchristie/django-rest-framework
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[twitter]: https://twitter.com/_tomchristie

View File

@ -10,8 +10,18 @@ def api_view(http_method_names):
def decorator(func):
class WrappedAPIView(APIView):
pass
WrappedAPIView = type(
'WrappedAPIView',
(APIView,),
{'__doc__': func.__doc__}
)
# Note, the above allows us to set the docstring.
# It is the equivelent of:
#
# class WrappedAPIView(APIView):
# pass
# WrappedAPIView.__doc__ = func.doc <--- Not possible to do this
allowed_methods = set(http_method_names) | set(('options',))
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]

View File

@ -31,14 +31,6 @@ class PermissionDenied(APIException):
self.detail = detail or self.default_detail
class InvalidFormat(APIException):
status_code = status.HTTP_404_NOT_FOUND
default_detail = "Format suffix '.%s' not found."
def __init__(self, format, detail=None):
self.detail = (detail or self.default_detail) % format
class MethodNotAllowed(APIException):
status_code = status.HTTP_405_METHOD_NOT_ALLOWED
default_detail = "Method '%s' not allowed."

View File

@ -111,17 +111,17 @@ class WritableField(Field):
widget = widgets.TextInput
default = None
def __init__(self, source=None, readonly=False, required=None,
def __init__(self, source=None, read_only=False, required=None,
validators=[], error_messages=None, widget=None,
default=None):
super(WritableField, self).__init__(source=source)
self.readonly = readonly
self.read_only = read_only
if required is None:
self.required = not(readonly)
self.required = not(read_only)
else:
assert not readonly, "Cannot set required=True and readonly=True"
assert not read_only, "Cannot set required=True and read_only=True"
self.required = required
messages = {}
@ -166,7 +166,7 @@ class WritableField(Field):
Given a dictionary and a field name, updates the dictionary `into`,
with the field and it's deserialized value.
"""
if self.readonly:
if self.read_only:
return
try:
@ -240,7 +240,7 @@ class RelatedField(WritableField):
return self.to_native(value)
def field_from_native(self, data, field_name, into):
if self.readonly:
if self.read_only:
return
value = data.get(field_name)
@ -256,7 +256,7 @@ class ManyRelatedMixin(object):
return [self.to_native(item) for item in value.all()]
def field_from_native(self, data, field_name, into):
if self.readonly:
if self.read_only:
return
try:
@ -331,14 +331,16 @@ class HyperlinkedRelatedField(RelatedField):
self.view_name = kwargs.pop('view_name')
except:
raise ValueError("Hyperlinked field requires 'view_name' kwarg")
self.format = kwargs.pop('format', None)
super(HyperlinkedRelatedField, self).__init__(*args, **kwargs)
def to_native(self, obj):
view_name = self.view_name
request = self.context.get('request', None)
format = self.format or self.context.get('format', None)
kwargs = {self.pk_url_kwarg: obj.pk}
try:
return reverse(view_name, kwargs=kwargs, request=request)
return reverse(view_name, kwargs=kwargs, request=request, format=format)
except:
pass
@ -349,13 +351,13 @@ class HyperlinkedRelatedField(RelatedField):
kwargs = {self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request)
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try:
return reverse(self.view_name, kwargs=kwargs, request=request)
return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
except:
pass
@ -405,13 +407,15 @@ class HyperlinkedIdentityField(Field):
# TODO: Make this mandatory, and have the HyperlinkedModelSerializer
# set it on-the-fly
self.view_name = kwargs.pop('view_name', None)
self.format = kwargs.pop('format', None)
super(HyperlinkedIdentityField, self).__init__(*args, **kwargs)
def field_to_native(self, obj, field_name):
request = self.context.get('request', None)
format = self.format or self.context.get('format', None)
view_name = self.view_name or self.parent.opts.view_name
view_kwargs = {'pk': obj.pk}
return reverse(view_name, kwargs=view_kwargs, request=request)
return reverse(view_name, kwargs=view_kwargs, request=request, format=format)
##### Typed Fields #####
@ -509,7 +513,10 @@ class EmailField(CharField):
default_validators = [validators.validate_email]
def from_native(self, value):
return super(EmailField, self).from_native(value).strip()
ret = super(EmailField, self).from_native(value)
if ret is None:
return None
return ret.strip()
def __deepcopy__(self, memo):
result = copy.copy(self)
@ -531,8 +538,9 @@ class DateField(WritableField):
empty = None
def from_native(self, value):
if value is None:
return value
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
if timezone and settings.USE_TZ and timezone.is_aware(value):
# Convert aware datetimes to the default time zone
@ -570,8 +578,9 @@ class DateTimeField(WritableField):
empty = None
def from_native(self, value):
if value is None:
return value
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
@ -629,6 +638,7 @@ class IntegerField(WritableField):
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeError):
@ -644,8 +654,9 @@ class FloatField(WritableField):
}
def from_native(self, value):
if value is None:
return value
if value in validators.EMPTY_VALUES:
return None
try:
return float(value)
except (TypeError, ValueError):

View File

@ -1,3 +1,4 @@
from django.http import Http404
from rest_framework import exceptions
from rest_framework.settings import api_settings
from rest_framework.utils.mediatypes import order_by_precedence, media_type_matches
@ -66,7 +67,7 @@ class DefaultContentNegotiation(BaseContentNegotiation):
renderers = [renderer for renderer in renderers
if renderer.format == format]
if not renderers:
raise exceptions.InvalidFormat(format)
raise Http404
return renderers
def get_accept_list(self, request):

View File

@ -18,6 +18,17 @@ class BasePermission(object):
raise NotImplementedError(".has_permission() must be overridden.")
class AllowAny(BasePermission):
"""
Allow any access.
This isn't strictly required, since you could use an empty
permission_classes list, but it's useful because it makes the intention
more explicit.
"""
def has_permission(self, request, view, obj=None):
return True
class IsAuthenticated(BasePermission):
"""
Allows access only to authenticated users.

View File

@ -139,13 +139,24 @@ class YAMLRenderer(BaseRenderer):
return yaml.dump(data, stream=None, Dumper=self.encoder)
class HTMLRenderer(BaseRenderer):
class TemplateHTMLRenderer(BaseRenderer):
"""
A Base class provided for convenience.
An HTML renderer for use with templates.
Render the object simply by using the given template.
To create a template renderer, subclass this class, and set
the :attr:`media_type` and :attr:`template` attributes.
The data supplied to the Response object should be a dictionary that will
be used as context for the template.
The template name is determined by (in order of preference):
1. An explicit `.template_name` attribute set on the response.
2. An explicit `.template_name` attribute set on this class.
3. The return result of calling `view.get_template_names()`.
For example:
data = {'users': User.objects.all()}
return Response(data, template_name='users.html')
For pre-rendered HTML, see StaticHTMLRenderer.
"""
media_type = 'text/html'
@ -188,6 +199,26 @@ class HTMLRenderer(BaseRenderer):
raise ConfigurationError('Returned a template response with no template_name')
class StaticHTMLRenderer(BaseRenderer):
"""
An HTML renderer class that simply returns pre-rendered HTML.
The data supplied to the Response object should be a string representing
the pre-rendered HTML content.
For example:
data = '<html><body>example</body></html>'
return Response(data)
For template rendered HTML, see TemplateHTMLRenderer.
"""
media_type = 'text/html'
format = 'html'
def render(self, data, accepted_media_type=None, renderer_context=None):
return data
class BrowsableAPIRenderer(BaseRenderer):
"""
HTML renderer used to self-document the API.
@ -257,7 +288,7 @@ class BrowsableAPIRenderer(BaseRenderer):
fields = {}
for k, v in serializer.get_fields(True).items():
if getattr(v, 'readonly', True):
if getattr(v, 'read_only', True):
continue
kwargs = {}

View File

@ -5,13 +5,15 @@ from django.core.urlresolvers import reverse as django_reverse
from django.utils.functional import lazy
def reverse(viewname, *args, **kwargs):
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
"""
Same as `django.core.urlresolvers.reverse`, but optionally takes a request
and returns a fully qualified URL, using the request to get the base URL.
"""
request = kwargs.pop('request', None)
url = django_reverse(viewname, *args, **kwargs)
if format is not None:
kwargs = kwargs or {}
kwargs['format'] = format
url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
if request:
return request.build_absolute_uri(url)
return url

View File

@ -23,10 +23,6 @@ class SortedDictWithMetadata(SortedDict, DictWithMetadata):
pass
class RecursionOccured(BaseException):
pass
def _is_protected_type(obj):
"""
True if the object is a native datatype that does not need to
@ -74,7 +70,7 @@ class SerializerOptions(object):
Meta class options for Serializer
"""
def __init__(self, meta):
self.nested = getattr(meta, 'nested', False)
self.depth = getattr(meta, 'depth', 0)
self.fields = getattr(meta, 'fields', ())
self.exclude = getattr(meta, 'exclude', ())
@ -93,7 +89,6 @@ class BaseSerializer(Field):
self.parent = None
self.root = None
self.stack = []
self.context = context or {}
self.init_data = data
@ -152,14 +147,11 @@ class BaseSerializer(Field):
def initialize(self, parent):
"""
Same behaviour as usual Field, except that we need to keep track
of state so that we can deal with handling maximum depth and recursion.
of state so that we can deal with handling maximum depth.
"""
super(BaseSerializer, self).initialize(parent)
self.stack = parent.stack[:]
if parent.opts.nested and not isinstance(parent.opts.nested, bool):
self.opts.nested = parent.opts.nested - 1
else:
self.opts.nested = parent.opts.nested
if parent.opts.depth:
self.opts.depth = parent.opts.depth - 1
#####
# Methods to convert or revert from objects <--> primative representations.
@ -175,21 +167,13 @@ class BaseSerializer(Field):
Core of serialization.
Convert an object into a dictionary of serialized field values.
"""
if obj in self.stack and not self.source == '*':
raise RecursionOccured()
self.stack.append(obj)
ret = self._dict_class()
ret.fields = {}
fields = self.get_fields(serialize=True, obj=obj, nested=self.opts.nested)
fields = self.get_fields(serialize=True, obj=obj, nested=bool(self.opts.depth))
for field_name, field in fields.items():
key = self.get_field_key(field_name)
try:
value = field.field_to_native(obj, field_name)
except RecursionOccured:
field = self.get_fields(serialize=True, obj=obj, nested=False)[field_name]
value = field.field_to_native(obj, field_name)
value = field.field_to_native(obj, field_name)
ret[key] = value
ret.fields[key] = field
return ret
@ -199,7 +183,7 @@ class BaseSerializer(Field):
Core of deserialization, together with `restore_object`.
Converts a dictionary of data into a dictionary of deserialized fields.
"""
fields = self.get_fields(serialize=False, data=data, nested=self.opts.nested)
fields = self.get_fields(serialize=False, data=data, nested=bool(self.opts.depth))
reverted_data = {}
for field_name, field in fields.items():
try:
@ -213,7 +197,8 @@ class BaseSerializer(Field):
"""
Run `validate_<fieldname>()` and `validate()` methods on the serializer
"""
fields = self.get_fields(serialize=False, data=attrs, nested=self.opts.nested)
# TODO: refactor this so we're not determining the fields again
fields = self.get_fields(serialize=False, data=attrs, nested=bool(self.opts.depth))
for field_name, field in fields.items():
try:

View File

@ -37,11 +37,14 @@ DEFAULTS = {
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
),
'DEFAULT_PERMISSION_CLASSES': (),
'DEFAULT_THROTTLE_CLASSES': (),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_THROTTLE_CLASSES': (
),
'DEFAULT_CONTENT_NEGOTIATION_CLASS':
'rest_framework.negotiation.DefaultContentNegotiation',
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.ModelSerializer',
'DEFAULT_PAGINATION_SERIALIZER_CLASS':

View File

@ -32,6 +32,10 @@ h2, h3 {
margin-right: 1em;
}
ul.breadcrumb {
margin: 58px 0 0 0;
}
/* To allow tooltips to work on disabled elements */
.disabled-tooltip-shield {
position: absolute;
@ -55,6 +59,7 @@ pre {
.page-header {
border-bottom: none;
padding-bottom: 0px;
margin-bottom: 20px;
}
@ -65,7 +70,7 @@ html{
background: none;
}
body, .navbar .navbar-inner .container-fluid{
body, .navbar .navbar-inner .container-fluid {
max-width: 1150px;
margin: 0 auto;
}
@ -76,13 +81,14 @@ body{
}
#content{
margin: 40px 0 0 0;
margin: 0;
}
/* custom navigation styles */
.wrapper .navbar{
width:100%;
width: 100%;
position: absolute;
left:0;
left: 0;
top: 0;
}
.navbar .navbar-inner{

View File

@ -109,7 +109,7 @@
<div class="content-main">
<div class="page-header"><h1>{{ name }}</h1></div>
<p class="resource-description">{{ description }}</p>
{{ description }}
<div class="request-info">
<pre class="prettyprint"><b>{{ request.method }}</b> {{ request.get_full_path }}</pre>

View File

@ -3,42 +3,50 @@
<html>
<head>
<link rel="stylesheet" type="text/css" href='{% get_static_prefix %}rest_framework/css/style.css'/>
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}rest_framework/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}rest_framework/css/bootstrap-tweaks.css"/>
<link rel="stylesheet" type="text/css" href='{% get_static_prefix %}rest_framework/css/default.css'/>
</head>
<body class="login">
<body class="container">
<div id="container">
<div id="header">
<div id="branding">
<h1 id="site-name">Django REST framework</h1>
<div class="container-fluid" style="margin-top: 30px">
<div class="row-fluid">
<div class="well" style="width: 320px; margin-left: auto; margin-right: auto">
<div class="row-fluid">
<div>
<h3 style="margin: 0 0 20px;">Django REST framework</h3>
</div>
</div>
</div><!-- /row fluid -->
<div id="content" class="colM">
<div id="content-main">
<form method="post" action="{% url 'rest_framework:login' %}" id="login-form">
<div class="row-fluid">
<div>
<form action="{% url 'rest_framework:login' %}" class=" form-inline" method="post">
{% csrf_token %}
<div class="form-row">
<label for="id_username">Username:</label> {{ form.username }}
<div id="div_id_username" class="clearfix control-group">
<div class="controls" style="height: 30px">
<Label class="span4" style="margin-top: 3px">Username:</label>
<input style="height: 25px" type="text" name="username" maxlength="100" autocapitalize="off" autocorrect="off" class="textinput textInput" id="id_username">
</div>
</div>
<div class="form-row">
<label for="id_password">Password:</label> {{ form.password }}
<input type="hidden" name="next" value="{{ next }}" />
<div id="div_id_password" class="clearfix control-group">
<div class="controls" style="height: 30px">
<Label class="span4" style="margin-top: 3px">Password:</label>
<input style="height: 25px" type="password" name="password" maxlength="100" autocapitalize="off" autocorrect="off" class="textinput textInput" id="id_password">
</div>
</div>
<div class="form-row">
<label>&nbsp;</label><input type="submit" value="Log in">
<input type="hidden" name="next" value="{{ next }}" />
<div class="form-actions-no-box">
<input type="submit" name="submit" value="Log in" class="btn btn-primary" id="submit-id-submit">
</div>
</form>
<script type="text/javascript">
document.getElementById('id_username').focus()
</script>
</div>
<br class="clear">
</div>
</div><!-- /row fluid -->
</div><!--/span-->
<div id="footer"></div>
</div><!-- /.row-fluid -->
</div>
</div>
</body>

View File

@ -2,7 +2,7 @@ from django.test import TestCase
from django.test.client import RequestFactory
from django.utils import simplejson as json
from rest_framework import generics, serializers, status
from rest_framework.tests.models import BasicModel, Comment
from rest_framework.tests.models import BasicModel, Comment, SlugBasedModel
factory = RequestFactory()
@ -22,6 +22,22 @@ class InstanceView(generics.RetrieveUpdateDestroyAPIView):
model = BasicModel
class SlugSerializer(serializers.ModelSerializer):
slug = serializers.Field() # read only
class Meta:
model = SlugBasedModel
exclude = ('id',)
class SlugBasedInstanceView(InstanceView):
"""
A model with a slug-field.
"""
model = SlugBasedModel
serializer_class = SlugSerializer
class TestRootView(TestCase):
def setUp(self):
"""
@ -129,6 +145,7 @@ class TestInstanceView(TestCase):
for obj in self.objects.all()
]
self.view = InstanceView.as_view()
self.slug_based_view = SlugBasedInstanceView.as_view()
def test_get_instance_view(self):
"""
@ -198,7 +215,7 @@ class TestInstanceView(TestCase):
def test_put_cannot_set_id(self):
"""
POST requests to create a new object should not be able to set the id.
PUT requests to create a new object should not be able to set the id.
"""
content = {'id': 999, 'text': 'foobar'}
request = factory.put('/1', json.dumps(content),
@ -224,6 +241,34 @@ class TestInstanceView(TestCase):
updated = self.objects.get(id=1)
self.assertEquals(updated.text, 'foobar')
def test_put_as_create_on_id_based_url(self):
"""
PUT requests to RetrieveUpdateDestroyAPIView should create an object
at the requested url if it doesn't exist.
"""
content = {'text': 'foobar'}
# pk fields can not be created on demand, only the database can set th pk for a new object
request = factory.put('/5', json.dumps(content),
content_type='application/json')
response = self.view(request, pk=5).render()
self.assertEquals(response.status_code, status.HTTP_200_OK)
new_obj = self.objects.get(pk=5)
self.assertEquals(new_obj.text, 'foobar')
def test_put_as_create_on_slug_based_url(self):
"""
PUT requests to RetrieveUpdateDestroyAPIView should create an object
at the requested url if possible, else return HTTP_403_FORBIDDEN error-response.
"""
content = {'text': 'foobar'}
request = factory.put('/test_slug', json.dumps(content),
content_type='application/json')
response = self.slug_based_view(request, slug='test_slug').render()
self.assertEquals(response.status_code, status.HTTP_200_OK)
self.assertEquals(response.data, {'slug': 'test_slug', 'text': 'foobar'})
new_obj = SlugBasedModel.objects.get(slug='test_slug')
self.assertEquals(new_obj.text, 'foobar')
# Regression test for #285

View File

@ -3,12 +3,12 @@ from django.test import TestCase
from django.template import TemplateDoesNotExist, Template
import django.template.loader
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import HTMLRenderer
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
@api_view(('GET',))
@renderer_classes((HTMLRenderer,))
@renderer_classes((TemplateHTMLRenderer,))
def example(request):
"""
A view that can returns an HTML representation.
@ -22,7 +22,7 @@ urlpatterns = patterns('',
)
class HTMLRendererTests(TestCase):
class TemplateHTMLRendererTests(TestCase):
urls = 'rest_framework.tests.htmlrenderer'
def setUp(self):

View File

@ -52,6 +52,11 @@ class BasicModel(RESTFrameworkModel):
text = models.CharField(max_length=100)
class SlugBasedModel(RESTFrameworkModel):
text = models.CharField(max_length=100)
slug = models.SlugField(max_length=32)
class DefaultValueModel(RESTFrameworkModel):
text = models.CharField(default='foobar', max_length=100)

View File

@ -301,7 +301,7 @@ class ManyToManyTests(TestCase):
class ReadOnlyManyToManyTests(TestCase):
def setUp(self):
class ReadOnlyManyToManySerializer(serializers.ModelSerializer):
rel = serializers.ManyRelatedField(readonly=True)
rel = serializers.ManyRelatedField(read_only=True)
class Meta:
model = ReadOnlyManyToManyModel
@ -323,7 +323,7 @@ class ReadOnlyManyToManyTests(TestCase):
def test_update(self):
"""
Attempt to update an instance of a model with a ManyToMany
relationship. Not updated due to readonly=True
relationship. Not updated due to read_only=True
"""
new_anchor = Anchor()
new_anchor.save()
@ -339,7 +339,7 @@ class ReadOnlyManyToManyTests(TestCase):
def test_update_without_relationship(self):
"""
Attempt to update an instance of a model where many to ManyToMany
relationship is not supplied. Not updated due to readonly=True
relationship is not supplied. Not updated due to read_only=True
"""
new_anchor = Anchor()
new_anchor.save()

View File

@ -285,7 +285,7 @@
# uiop = models.CharField(max_length=256, blank=True)
# @property
# def readonly(self):
# def read_only(self):
# return 'read only'
# class MockResource(ModelResource):
@ -298,7 +298,7 @@
# def test_property_fields_are_allowed_on_model_forms(self):
# """Validation on ModelForms may include property fields that exist on the Model to be included in the input."""
# content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only'}
# content = {'qwerty': 'example', 'uiop': 'example', 'read_only': 'read only'}
# self.assertEqual(self.validator.validate_request(content, None), content)
# def test_property_fields_are_not_required_on_model_forms(self):
@ -310,19 +310,19 @@
# """If some (otherwise valid) content includes fields that are not in the form then validation should fail.
# It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up
# broken clients more easily (eg submitting content with a misnamed field)"""
# content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only', 'extra': 'extra'}
# content = {'qwerty': 'example', 'uiop': 'example', 'read_only': 'read only', 'extra': 'extra'}
# self.assertRaises(ImmediateResponse, self.validator.validate_request, content, None)
# def test_validate_requires_fields_on_model_forms(self):
# """If some (otherwise valid) content includes fields that are not in the form then validation should fail.
# It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up
# broken clients more easily (eg submitting content with a misnamed field)"""
# content = {'readonly': 'read only'}
# content = {'read_only': 'read only'}
# self.assertRaises(ImmediateResponse, self.validator.validate_request, content, None)
# def test_validate_does_not_require_blankable_fields_on_model_forms(self):
# """Test standard ModelForm validation behaviour - fields with blank=True are not required."""
# content = {'qwerty': 'example', 'readonly': 'read only'}
# content = {'qwerty': 'example', 'read_only': 'read only'}
# self.validator.validate_request(content, None)
# def test_model_form_validator_uses_model_forms(self):