aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-rwxr-xr-x[-rw-r--r--]docs/api-guide/authentication.md259
-rw-r--r--docs/api-guide/exceptions.md19
-rw-r--r--docs/api-guide/fields.md264
-rw-r--r--docs/api-guide/filtering.md170
-rw-r--r--docs/api-guide/format-suffixes.md21
-rwxr-xr-x[-rw-r--r--]docs/api-guide/generic-views.md289
-rw-r--r--docs/api-guide/pagination.md11
-rw-r--r--docs/api-guide/parsers.md78
-rw-r--r--docs/api-guide/permissions.md95
-rw-r--r--docs/api-guide/relations.md440
-rw-r--r--docs/api-guide/renderers.md40
-rw-r--r--docs/api-guide/requests.md4
-rw-r--r--docs/api-guide/routers.md111
-rw-r--r--docs/api-guide/serializers.md339
-rw-r--r--docs/api-guide/settings.md142
-rw-r--r--docs/api-guide/throttling.md22
-rw-r--r--docs/api-guide/views.md8
-rw-r--r--docs/api-guide/viewsets.md219
-rw-r--r--docs/css/default.css38
-rw-r--r--docs/index.md153
-rw-r--r--docs/template.html44
-rw-r--r--docs/topics/2.2-announcement.md159
-rw-r--r--docs/topics/2.3-announcement.md264
-rw-r--r--docs/topics/ajax-csrf-cors.md41
-rw-r--r--docs/topics/browsable-api.md18
-rw-r--r--docs/topics/browser-enhancements.md16
-rw-r--r--docs/topics/contributing.md136
-rw-r--r--docs/topics/credits.md105
-rw-r--r--docs/topics/csrf.md12
-rw-r--r--docs/topics/migration.md89
-rw-r--r--docs/topics/release-notes.md270
-rw-r--r--docs/topics/rest-framework-2-announcement.md10
-rw-r--r--docs/topics/rest-hypermedia-hateoas.md2
-rw-r--r--docs/tutorial/1-serialization.md98
-rw-r--r--docs/tutorial/2-requests-and-responses.md47
-rw-r--r--docs/tutorial/3-class-based-views.md20
-rw-r--r--docs/tutorial/4-authentication-and-permissions.md66
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md50
-rw-r--r--docs/tutorial/6-viewsets-and-routers.md151
-rw-r--r--docs/tutorial/quickstart.md95
40 files changed, 3590 insertions, 825 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 43fc15d2..c2f73901 100644..100755
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -8,25 +8,33 @@
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
-REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
+REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
-Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
+Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
+---
+
+**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
+
+For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
+
+---
+
## How authentication is determined
-The authentication policy is always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
+The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
-## Setting the authentication policy
+## Setting the authentication scheme
-The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
+The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
@@ -35,7 +43,8 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
)
}
-You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
+You can also set the authentication scheme on a per-view or per-viewset basis,
+using the `APIView` class based views.
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
@@ -52,7 +61,7 @@ Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
- @permissions_classes((IsAuthenticated,))
+ @permission_classes((IsAuthenticated,))
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
@@ -60,24 +69,59 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
+## Unauthorized and Forbidden responses
+
+When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
+
+* [HTTP 401 Unauthorized][http401]
+* [HTTP 403 Permission Denied][http403]
+
+HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header.
+
+The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**.
+
+Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
+
+## Apache mod_wsgi specific configuration
+
+Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
+
+If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`.
+
+ # this can go in either server config, virtual host, directory or .htaccess
+ WSGIPassAuthorization On
+
+---
+
# API Reference
## BasicAuthentication
-This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
+This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
If successfully authenticated, `BasicAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
-**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
+Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
+
+ WWW-Authenticate: Basic realm="api"
+
+**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
## TokenAuthentication
-This policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
+This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
-To use the `TokenAuthentication` policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
+To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
+
+ INSTALLED_APPS = (
+ ...
+ 'rest_framework.authtoken'
+ )
+
+Make sure to run `manage.py syncdb` after changing your settings.
You'll also need to create tokens for your users.
@@ -93,9 +137,23 @@ For clients to authenticate, the token key should be included in the `Authorizat
If successfully authenticated, `TokenAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
-* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
+* `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
+
+Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
+
+ WWW-Authenticate: Token
+
+The `curl` command line tool may be useful for testing token authenticated APIs. For example:
+
+ curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
-**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
+---
+
+**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
+
+---
+
+#### Generating Tokens
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@@ -112,8 +170,7 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)
-When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password.
-REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
+When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
@@ -125,32 +182,186 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
-<!--
-## OAuthAuthentication
+Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
-This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
+#### Custom user models
-If successfully authenticated, `OAuthAuthentication` provides the following credentials.
+The `rest_framework.authtoken` app includes a south migration that will create the authtoken table. If you're using a [custom user model][custom-user-model] you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.
-* `request.user` will be a Django `User` instance.
-* `request.auth` will be a `rest_framework.models.OAuthToken` instance.
--->
+You can do so by inserting a `needed_by` attribute in your user migration:
+
+ class Migration:
+
+ needed_by = (
+ ('authtoken', '0001_initial'),
+ )
+
+ def forwards(self):
+ ...
+
+For more details, see the [south documentation on dependencies][south-dependencies].
## SessionAuthentication
-This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
+This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
If successfully authenticated, `SessionAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
+Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
+
+If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
+
+## OAuthAuthentication
+
+This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.
+
+This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`:
+
+ INSTALLED_APPS = (
+ ...
+ `oauth_provider`,
+ )
+
+Don't forget to run `syncdb` once you've added the package.
+
+ python manage.py syncdb
+
+#### Getting started with django-oauth-plus
+
+The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.
+
+The `django-oauth-plus` package provides simple foundation for classic 'three-legged' oauth flow. Please refer to [the documentation][django-oauth-plus] for more details.
+
+## OAuth2Authentication
+
+This authentication uses [OAuth 2.0][rfc6749] authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection.
+
+This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`:
+
+ INSTALLED_APPS = (
+ ...
+ 'provider',
+ 'provider.oauth2',
+ )
+
+You must also include the following in your root `urls.py` module:
+
+ url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
+
+Note that the `namespace='oauth2'` argument is required.
+
+Finally, sync your database.
+
+ python manage.py syncdb
+ python manage.py migrate
+
+---
+
+**Note:** If you use `OAuth2Authentication` in production you must ensure that your API is only available over `https`.
+
+---
+
+#### Getting started with django-oauth2-provider
+
+The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients.
+
+The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs].
+
+To get started:
+
+##### 1. Create a client
+
+You can create a client, either through the shell, or by using the Django admin.
+
+Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you.
+
+##### 2. Request an access token
+
+To request an access token, submit a `POST` request to the url `/oauth2/access_token` with the following fields:
+
+* `client_id` the client id you've just configured at the previous step.
+* `client_secret` again configured at the previous step.
+* `username` the username with which you want to log in.
+* `password` well, that speaks for itself.
+
+You can use the command line to test that your local configuration is working:
+
+ curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
+
+You should get a response that looks something like this:
+
+ {"access_token": "<your-access-token>", "scope": "read", "expires_in": 86399, "refresh_token": "<your-refresh-token>"}
+
+##### 3. Access the API
+
+The only thing needed to make the `OAuth2Authentication` class work is to insert the `access_token` you've received in the `Authorization` request header.
+
+The command line to test the authentication looks like:
+
+ curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/
+
+---
+
# Custom authentication
-To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
+To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
+
+In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
+
+Typically the approach you should take is:
+
+* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
+* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
+
+You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
+
+If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
+
+## Example
+
+The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
+
+ class ExampleAuthentication(authentication.BaseAuthentication):
+ def authenticate(self, request):
+ username = request.META.get('X_USERNAME')
+ if not username:
+ return None
+
+ try:
+ user = User.objects.get(username=username)
+ except User.DoesNotExist:
+ raise authenticate.AuthenticationFailed('No such user')
+
+ return (user, None)
+
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## Digest Authentication
+
+HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
[cite]: http://jacobian.org/writing/rest-worst-practices/
+[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
+[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
[basicauth]: http://tools.ietf.org/html/rfc2617
[oauth]: http://oauth.net/2/
[permission]: permissions.md
[throttling]: throttling.md
+[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
+[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
+[custom-user-model]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model
+[south-dependencies]: http://south.readthedocs.org/en/latest/dependencies.html
+[juanriaza]: https://github.com/juanriaza
+[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
+[oauth-1.0a]: http://oauth.net/core/1.0a
+[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus
+[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
+[django-oauth2-provider-docs]: https://django-oauth2-provider.readthedocs.org/en/latest/
+[rfc6749]: http://tools.ietf.org/html/rfc6749
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index ba57fde8..8b3e50f1 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -53,11 +53,27 @@ Raised if the request contains malformed data when accessing `request.DATA` or `
By default this exception results in a response with the HTTP status code "400 Bad Request".
+## AuthenticationFailed
+
+**Signature:** `AuthenticationFailed(detail=None)`
+
+Raised when an incoming request includes incorrect authentication.
+
+By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
+
+## NotAuthenticated
+
+**Signature:** `NotAuthenticated(detail=None)`
+
+Raised when an unauthenticated request fails the permission checks.
+
+By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
+
## PermissionDenied
**Signature:** `PermissionDenied(detail=None)`
-Raised when an incoming request fails the permission checks.
+Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
@@ -86,3 +102,4 @@ Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
+[authentication]: authentication.md
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 50a09701..e117c370 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,11 +2,11 @@
# Serializer fields
-> Flat is better than nested.
+> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it &mdash; normalizing it to a consistent format.
>
-> &mdash; [The Zen of Python][cite]
+> &mdash; [Django documentation][cite]
-Serializer fields handle converting between primative values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
+Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
---
@@ -28,7 +28,7 @@ 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.
+Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.
Defaults to `False`
@@ -41,7 +41,7 @@ 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.
+If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all.
### `validators`
@@ -96,13 +96,13 @@ Would produce output similar to:
'expired': True
}
-By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary.
+By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
-You can customize this behaviour by overriding the `.to_native(self, value)` method.
+You can customize this behavior by overriding the `.to_native(self, value)` method.
## WritableField
-A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
+A field that supports both read and write operations. By itself `WritableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
## ModelField
@@ -110,6 +110,24 @@ A generic field that can be tied to any arbitrary model field. The `ModelField`
**Signature:** `ModelField(model_field=<Django ModelField class>)`
+## SerializerMethodField
+
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
+ from rest_framework import serializers
+ from django.contrib.auth.models import User
+ from django.utils.timezone import now
+
+ class UserSerializer(serializers.ModelSerializer):
+
+ days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
+
---
# Typed Fields
@@ -163,17 +181,60 @@ Corresponds to `django.forms.fields.RegexField`
**Signature:** `RegexField(regex, max_length=None, min_length=None)`
+## DateTimeField
+
+A date and time representation.
+
+Corresponds to `django.db.models.fields.DateTimeField`
+
+When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default.
+
+If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
+
+ class CommentSerializer(serializers.ModelSerializer):
+ created = serializers.DateTimeField()
+
+ class Meta:
+ model = Comment
+
+Note that by default, datetime representations are deteremined by the renderer in use, although this can be explicitly overridden as detailed below.
+
+In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`.
+
+**Signature:** `DateTimeField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `datetime` objects should be returned by `to_native`. In this case the datetime encoding will be determined by the renderer.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
+
+DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
+
## DateField
A date representation.
Corresponds to `django.db.models.fields.DateField`
-## DateTimeField
+**Signature:** `DateField(format=None, input_formats=None)`
-A date and time representation.
+* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
-Corresponds to `django.db.models.fields.DateTimeField`
+Date format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
+
+## TimeField
+
+A time representation.
+
+Optionally takes `format` as parameter to replace the matching pattern.
+
+Corresponds to `django.db.models.fields.TimeField`
+
+**Signature:** `TimeField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
+
+Time format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
## IntegerField
@@ -187,6 +248,12 @@ A floating point representation.
Corresponds to `django.db.models.fields.FloatField`.
+## DecimalField
+
+A decimal representation.
+
+Corresponds to `django.db.models.fields.DecimalField`.
+
## FileField
A file representation. Performs Django's standard FileField validation.
@@ -211,151 +278,56 @@ Signature and validation is the same as with `FileField`.
---
-**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since eg json doesn't support file uploads.
-Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
+**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
+Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
---
-# Relational Fields
-
-Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
-
-## RelatedField
-
-This field can be applied to any of the following:
-
-* A `ForeignKey` field.
-* A `OneToOneField` field.
-* A reverse OneToOne relationship
-* Any other "to-one" relationship.
-
-By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+# Custom fields
-You can customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
+If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects.
-## ManyRelatedField
+The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation.
-This field can be applied to any of the following:
-
-* A `ManyToManyField` field.
-* A reverse ManyToMany relationship.
-* A reverse ForeignKey relationship
-* Any other "to-many" relationship.
+## Examples
-By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+Let's look at an example of serializing a class that represents an RGB color value:
-For example, given the following models:
-
- class TaggedItem(models.Model):
+ class Color(object):
"""
- Tags arbitrary model instances using a generic relation.
-
- See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
+ A color represented in the RGB colorspace.
"""
- tag = models.SlugField()
- content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
- content_object = GenericForeignKey('content_type', 'object_id')
-
- def __unicode__(self):
- return self.tag
-
-
- class Bookmark(models.Model):
+ def __init__(self, red, green, blue):
+ assert(red >= 0 and green >= 0 and blue >= 0)
+ assert(red < 256 and green < 256 and blue < 256)
+ self.red, self.green, self.blue = red, green, blue
+
+ class ColourField(serializers.WritableField):
"""
- A bookmark consists of a URL, and 0 or more descriptive tags.
+ Color objects are serialized into "rgb(#, #, #)" notation.
"""
- url = models.URLField()
- tags = GenericRelation(TaggedItem)
-
-And a model serializer defined like this:
-
- class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
-
- class Meta:
- model = Bookmark
- exclude = ('id',)
-
-Then an example output format for a Bookmark instance would be:
-
- {
- 'tags': [u'django', u'python'],
- 'url': u'https://www.djangoproject.com/'
- }
-
-## PrimaryKeyRelatedField / ManyPrimaryKeyRelatedField
-
-`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
-
-By default these fields are read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## SlugRelatedField / ManySlugRelatedField
-
-`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
-
-By default these fields read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
-
-`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
-
-By default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
-* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
-* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## HyperLinkedIdentityField
-
-This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
-
-This field is always read-only.
-
-**Arguments**:
-
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
-* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
-* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
-
-# Other Fields
-
-## SerializerMethodField
-
-This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
-
- from rest_framework import serializers
- from django.contrib.auth.models import User
- from django.utils.timezone import now
-
- class UserSerializer(serializers.ModelSerializer):
-
- days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
-
- class Meta:
- model = User
-
- def get_days_since_joined(self, obj):
- return (now() - obj.date_joined).days
-
-[cite]: http://www.python.org/dev/peps/pep-0020/
+ def to_native(self, obj):
+ return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
+
+ def from_native(self, data):
+ data = data.strip('rgb(').rstrip(')')
+ red, green, blue = [int(col) for col in data.split(',')]
+ return Color(red, green, blue)
+
+
+By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`.
+
+As an example, let's create a field that can be used represent the class name of the object being serialized:
+
+ class ClassNameField(serializers.Field):
+ def field_to_native(self, obj, field_name):
+ """
+ Serialize the object's class name.
+ """
+ return obj.__class__
+
+[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
+[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
+[strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
+[iso8601]: http://www.w3.org/TR/NOTE-datetime
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 53ea7cbc..a710ad7d 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -8,7 +8,7 @@
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
-The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method.
+The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method.
Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
@@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`.
For example:
class PurchaseList(generics.ListAPIView)
- model = Purchase
serializer_class = PurchaseSerializer
def get_queryset(self):
@@ -44,7 +43,6 @@ For example if your URL config contained an entry like this:
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
class PurchaseList(generics.ListAPIView)
- model = Purchase
serializer_class = PurchaseSerializer
def get_queryset(self):
@@ -62,7 +60,6 @@ A final example of filtering the initial queryset would be to determine the init
We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
class PurchaseList(generics.ListAPIView)
- model = Purchase
serializer_class = PurchaseSerializer
def get_queryset(self):
@@ -80,35 +77,76 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
# Generic Filtering
-As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
+As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
-REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package.
+## Setting filter backends
-To use REST framework's filtering backend, first install `django-filter`.
-
- pip install django-filter
-
-You must also set the filter backend to `DjangoFilterBackend` in your settings:
+The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
REST_FRAMEWORK = {
- 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend'
+ 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}
+You can also set the authentication policy on a per-view, or per-viewset basis,
+using the `GenericAPIView` class based views.
-## Specifying filter fields
+ class UserListView(generics.ListAPIView):
+ queryset = User.objects.all()
+ serializer = UserSerializer
+ filter_backends = (filters.DjangoFilterBackend,)
-If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against.
+## Filtering and object lookups
- class ProductList(generics.ListAPIView):
+Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
+
+For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
+
+ http://example.com/api/products/4675/?category=clothing&max_price=10.00
+
+## Overriding the initial queryset
+
+Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
+
+ class PurchasedProductsList(generics.ListAPIView):
+ """
+ Return a list of all the products that the authenticated
+ user has ever purchased, with optional filtering.
+ """
model = Product
serializer_class = ProductSerializer
+ filter_class = ProductFilter
+
+ def get_queryset(self):
+ user = self.request.user
+ return user.purchase_set.all()
+
+---
+
+# API Guide
+
+## DjangoFilterBackend
+
+The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter].
+
+To use REST framework's `DjangoFilterBackend`, first install `django-filter`.
+
+ pip install django-filter
+
+
+#### Specifying filter fields
+
+If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
+
+ class ProductList(generics.ListAPIView):
+ queryset = Product.objects.all()
+ serializer_class = ProductSerializer
filter_fields = ('category', 'in_stock')
This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
http://example.com/api/products?category=clothing&in_stock=True
-## Specifying a FilterSet
+#### Specifying a FilterSet
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example:
@@ -120,7 +158,7 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha
fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView):
- model = Product
+ queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_class = ProductFilter
@@ -134,28 +172,74 @@ For more details on using filter sets see the [django-filter documentation][djan
**Hints & Tips**
-* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting.
+* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting.
* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
* `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
---
-## Overriding the initial queryset
-
-Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
+## SearchFilter
+
+The `SearchFilterBackend` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
+
+The `SearchFilterBackend` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`.
+
+ class UserListView(generics.ListAPIView):
+ queryset = User.objects.all()
+ serializer = UserSerializer
+ filter_backends = (filters.SearchFilter,)
+ search_fields = ('username', 'email')
+
+This will allow the client to filter the items in the list by making queries such as:
+
+ http://example.com/api/users?search=russell
+
+You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
+
+ search_fields = ('username', 'email', 'profile__profession')
+
+By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
+
+The search behavior may be restricted by prepending various characters to the `search_fields`.
+
+* '^' Starts-with search.
+* '=' Exact matches.
+* '@' Full-text search. (Currently only supported Django's MySQL backend.)
+
+For example:
+
+ search_fields = ('=username', '=email')
+
+For more details, see the [Django documentation][search-django-admin].
+
+---
+
+## OrderingFilter
+
+The `OrderingFilter` class supports simple query parameter controlled ordering of results. To specify the result order, set a query parameter named `'order'` to the required field name. For example:
+
+ http://example.com/api/users?ordering=username
+
+The client may also specify reverse orderings by prefixing the field name with '-', like so:
+
+ http://example.com/api/users?ordering=-username
+
+Multiple orderings may also be specified:
+
+ http://example.com/api/users?ordering=account,username
+
+If an `ordering` attribute is set on the view, this will be used as the default ordering.
+
+Typicaly you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.
+
+ class UserListView(generics.ListAPIView):
+ queryset = User.objects.all()
+ serializer = UserSerializer
+ filter_backends = (filters.OrderingFilter,)
+ ordering = ('username',)
+
+The `ordering` attribute may be either a string or a list/tuple of strings.
- class PurchasedProductsList(generics.ListAPIView):
- """
- Return a list of all the products that the authenticated
- user has ever purchased, with optional filtering.
- """
- model = Product
- serializer_class = ProductSerializer
- filter_class = ProductFilter
-
- def get_queryset(self):
- user = self.request.user
- return user.purchase_set.all()
---
# Custom generic filtering
@@ -164,15 +248,23 @@ You can also provide your own generic filtering backend, or write an installable
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
-To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
+As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.
-For example:
+## Example
- REST_FRAMEWORK = {
- 'FILTER_BACKEND': 'custom_filters.CustomFilterBackend'
- }
+For example, you might need to restrict users to only being able to see objects they created.
+
+ class IsOwnerFilterBackend(filters.BaseFilterBackend):
+ """
+ Filter that only allows users to see their own objects.
+ """
+ def filter_queryset(self, request, queryset, view):
+ return queryset.filter(owner=request.user)
+
+We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
[django-filter]: https://github.com/alex/django-filter
[django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html
-[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py \ No newline at end of file
+[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
+[search-django-admin]: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields
diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md
index 6d5feba4..dae3dea3 100644
--- a/docs/api-guide/format-suffixes.md
+++ b/docs/api-guide/format-suffixes.md
@@ -29,18 +29,27 @@ Example:
urlpatterns = patterns('blog.views',
url(r'^/$', 'api_root'),
- url(r'^comment/$', 'comment_root'),
- url(r'^comment/(?P<pk>[0-9]+)/$', 'comment_instance')
+ url(r'^comments/$', 'comment_list'),
+ url(r'^comments/(?P<pk>[0-9]+)/$', 'comment_detail')
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
-When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example.
+When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example:
- @api_view(('GET',))
- def api_root(request, format=None):
+ @api_view(('GET', 'POST'))
+ def comment_list(request, format=None):
# do stuff...
+Or with class based views:
+
+ class CommentList(APIView):
+ def get(self, request, format=None):
+ # do stuff...
+
+ def post(self, request, format=None):
+ # do stuff...
+
The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting.
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
@@ -58,4 +67,4 @@ It is actually a misconception. For example, take the following quote from Roy
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
-[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844 \ No newline at end of file
+[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 27c7d3f6..1a060a32 100644..100755
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -18,7 +18,7 @@ If the generic views don't suit the needs of your API, you can drop down to usin
Typically when using the generic views, you'll override the view, and set several class attributes.
class UserList(generics.ListCreateAPIView):
- model = User
+ queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
paginate_by = 100
@@ -26,17 +26,16 @@ Typically when using the generic views, you'll override the view, and set severa
For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):
- model = User
+ queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
- def get_paginate_by(self, queryset):
+ def get_paginate_by(self):
"""
Use smaller pagination for HTML representations.
"""
- page_size_param = self.request.QUERY_PARAMS.get('page_size')
- if page_size_param:
- return int(page_size_param)
+ if self.request.accepted_renderer.format == 'html':
+ return 20
return 100
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
@@ -47,117 +46,127 @@ For very simple cases you might want to pass through any class attributes using
# API Reference
-The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
+## GenericAPIView
-## CreateAPIView
+This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
-Used for **create-only** endpoints.
+Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
-Provides `post` method handlers.
+### Attributes
-Extends: [GenericAPIView], [CreateModelMixin]
+**Basic settings**:
-## ListAPIView
+The following attributes control the basic view behavior.
-Used for **read-only** endpoints to represent a **collection of model instances**.
+* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method.
+* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
+* `lookup_field` - The field that should be used to lookup individual model instances. Defaults to `'pk'`. The URL conf should include a keyword argument corresponding to this value. More complex lookup styles can be supported by overriding the `get_object()` method.
-Provides a `get` method handler.
+**Shortcuts**:
-Extends: [MultipleObjectAPIView], [ListModelMixin]
+* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class.
-## RetrieveAPIView
+**Pagination**:
-Used for **read-only** endpoints to represent a **single model instance**.
+The following attibutes are used to control pagination when used with list views.
-Provides a `get` method handler.
+* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`.
+* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`.
+* `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting.
+* `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`.
-Extends: [SingleObjectAPIView], [RetrieveModelMixin]
+**Filtering**:
-## DestroyAPIView
+* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting.
-Used for **delete-only** endpoints for a **single model instance**.
+### Methods
-Provides a `delete` method handler.
+**Base methods**:
-Extends: [SingleObjectAPIView], [DestroyModelMixin]
+#### `get_queryset(self)`
-## UpdateAPIView
+Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute, or the default queryset for the model if the `model` shortcut is being used.
-Used for **update-only** endpoints for a **single model instance**.
+May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request.
-Provides a `put` method handler.
+For example:
-Extends: [SingleObjectAPIView], [UpdateModelMixin]
+ def get_queryset(self):
+ return self.user.accounts.all()
-## ListCreateAPIView
+#### `get_object(self)`
-Used for **read-write** endpoints to represent a **collection of model instances**.
+Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
-Provides `get` and `post` method handlers.
+May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg.
-Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin]
+For example:
-## RetrieveDestroyAPIView
+ def get_object(self):
+ queryset = self.get_queryset()
+ filter = {}
+ for field in self.multiple_lookup_fields:
+ filter[field] = self.kwargs[field]
+ return get_object_or_404(queryset, **filter)
-Used for **read or delete** endpoints to represent a **single model instance**.
+#### `get_serializer_class(self)`
-Provides `get` and `delete` method handlers.
+Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute, or dynamically generating a serializer class if the `model` shortcut is being used.
-Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin]
+May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of uesr.
-## RetrieveUpdateDestroyAPIView
+For example:
-Used for **read-write-delete** endpoints to represent a **single model instance**.
+ def get_serializer_class(self):
+ if self.request.user.is_staff:
+ return FullAccountSerializer
+ return BasicAccountSerializer
-Provides `get`, `put` and `delete` method handlers.
+#### `get_paginate_by(self)`
-Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
+Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set.
----
+You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response.
-# Base views
+For example:
-Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes.
+ def get_paginate_by(self):
+ self.request.accepted_renderer.format == 'html':
+ return 20
+ return 100
-## GenericAPIView
+**Save hooks**:
-Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
+The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes.
-**Attributes**:
+* `pre_save(self, obj)` - A hook that is called before saving an object.
+* `post_save(self, obj, created=False)` - A hook that is called after saving an object.
-* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required.
-* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class.
+The `pre_save` method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
-## MultipleObjectAPIView
+ def pre_save(self, obj):
+ """
+ Set the object's owner, based on the incoming request.
+ """
+ obj.owner = self.request.user
-Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin].
+Remember that the `pre_save()` method is not called by `GenericAPIView` itself, but it is called by `create()` and `update()` methods on the `CreateModelMixin` and `UpdateModelMixin` classes.
-**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy].
+**Other methods**:
-**Attributes**:
+You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
-* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`.
-* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`.
-* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`.
-
-## SingleObjectAPIView
-
-Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin].
-
-**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy].
-
-**Attributes**:
-
-* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`.
-* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+]
-* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+]
-* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`.
+* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
+* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance.
+* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data.
+* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
+* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
---
# Mixins
-The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour.
+The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior.
## ListModelMixin
@@ -165,9 +174,7 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
-If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`.
-
-Should be mixed in with [MultipleObjectAPIView].
+If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`.
## CreateModelMixin
@@ -177,45 +184,157 @@ If an object is created this returns a `201 Created` response, with a serialized
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
-Should be mixed in with any [GenericAPIView].
-
## RetrieveModelMixin
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
-If an object can be retrieve this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
-
-Should be mixed in with [SingleObjectAPIView].
+If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
## UpdateModelMixin
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
+Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
+
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
-Should be mixed in with [SingleObjectAPIView].
-
## DestroyModelMixin
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
-Should be mixed in with [SingleObjectAPIView].
+---
+
+# Concrete View Classes
+
+The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
+
+## CreateAPIView
+
+Used for **create-only** endpoints.
+
+Provides a `post` method handler.
+
+Extends: [GenericAPIView], [CreateModelMixin]
+
+## ListAPIView
+
+Used for **read-only** endpoints to represent a **collection of model instances**.
+
+Provides a `get` method handler.
+
+Extends: [GenericAPIView], [ListModelMixin]
+
+## RetrieveAPIView
+
+Used for **read-only** endpoints to represent a **single model instance**.
+
+Provides a `get` method handler.
+
+Extends: [GenericAPIView], [RetrieveModelMixin]
+
+## DestroyAPIView
+
+Used for **delete-only** endpoints for a **single model instance**.
+
+Provides a `delete` method handler.
+
+Extends: [GenericAPIView], [DestroyModelMixin]
+
+## UpdateAPIView
+
+Used for **update-only** endpoints for a **single model instance**.
+
+Provides `put` and `patch` method handlers.
+
+Extends: [GenericAPIView], [UpdateModelMixin]
+
+## ListCreateAPIView
+
+Used for **read-write** endpoints to represent a **collection of model instances**.
+
+Provides `get` and `post` method handlers.
+
+Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
+
+## RetrieveUpdateAPIView
+
+Used for **read or update** endpoints to represent a **single model instance**.
+
+Provides `get`, `put` and `patch` method handlers.
+
+Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
+
+## RetrieveDestroyAPIView
+
+Used for **read or delete** endpoints to represent a **single model instance**.
+
+Provides `get` and `delete` method handlers.
+
+Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
+
+## RetrieveUpdateDestroyAPIView
+
+Used for **read-write-delete** endpoints to represent a **single model instance**.
+
+Provides `get`, `put`, `patch` and `delete` method handlers.
+
+Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
+
+---
+
+# Customizing the generic views
+
+Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.
+
+## Creating custom mixins
+
+For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
+
+ class MultipleFieldLookupMixin(object):
+ """
+ Apply this mixin to any view or viewset to get multiple field filtering
+ based on a `lookup_fields` attribute, instead of the default single field filtering.
+ """
+ def get_object(self):
+ queryset = self.get_queryset() # Get the base queryset
+ queryset = self.filter_queryset(queryset) # Apply any filter backends
+ filter = {}
+ for field in self.lookup_fields:
+ filter[field] = self.kwargs[field]
+ return get_object_or_404(queryset, **filter) # Lookup the object
+
+You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
+
+ class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
+ queryset = User.objects.all()
+ serializer_class = UserSerializer
+ lookup_fields = ('account', 'username')
+
+Using custom mixins is a good option if you have custom behavior that needs to be used
+
+## Creating custom base classes
+
+If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
+
+ class BaseRetrieveView(MultipleFieldLookupMixin,
+ generics.RetrieveAPIView):
+ pass
+
+ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
+ generics.RetrieveUpdateDestroyAPIView):
+ pass
+
+Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
-[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/
-[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
-[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/
-[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/
[GenericAPIView]: #genericapiview
-[SingleObjectAPIView]: #singleobjectapiview
-[MultipleObjectAPIView]: #multipleobjectapiview
[ListModelMixin]: #listmodelmixin
[CreateModelMixin]: #createmodelmixin
[RetrieveModelMixin]: #retrievemodelmixin
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index ab335e6e..912ce41b 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -37,7 +37,7 @@ We could now return that data in a `Response` object, and it would be rendered i
## Paginating QuerySets
-Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with.
+Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.
We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example.
@@ -93,10 +93,13 @@ The default pagination style may be set globally, using the `DEFAULT_PAGINATION_
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
class PaginatedListView(ListAPIView):
- model = ExampleModel
+ queryset = ExampleModel.objects.all()
+ serializer_class = ExampleModelSerializer
paginate_by = 10
paginate_by_param = 'page_size'
+Note that using a `paginate_by` value of `None` will turn off pagination for the view.
+
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
---
@@ -112,8 +115,8 @@ You can also override the name used for the object list field, by setting the `r
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
class LinksSerializer(serializers.Serializer):
- next = pagination.NextURLField(source='*')
- prev = pagination.PreviousURLField(source='*')
+ next = pagination.NextPageField(source='*')
+ prev = pagination.PreviousPageField(source='*')
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
links = LinksSerializer(source='*') # Takes the page object as the source
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 185b616c..5bd79a31 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -14,6 +14,16 @@ REST framework includes a number of built in Parser classes, that allow you to a
The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
+---
+
+**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
+
+If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted.
+
+As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
+
+---
+
## Setting the parsers
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content.
@@ -24,7 +34,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE
)
}
-You can also set the renderers used for an individual view, using the `APIView` class based views.
+You can also set the renderers used for an individual view, or viewset,
+using the `APIView` class based views.
class ExampleView(APIView):
"""
@@ -59,6 +70,8 @@ Parses `JSON` request content.
Parses `YAML` request content.
+Requires the `pyyaml` package to be installed.
+
**.media_type**: `application/yaml`
## XMLParser
@@ -69,6 +82,8 @@ Note that the `XML` markup language is typically used as the base language for m
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
+Requires the `defusedxml` package to be installed.
+
**.media_type**: `application/xml`
## FormParser
@@ -87,6 +102,33 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
**.media_type**: `multipart/form-data`
+## FileUploadParser
+
+Parses raw file upload content. The `request.DATA` property will be an empty `QueryDict`, and `request.FILES` will be a dictionary with a single key `'file'` containing the uploaded file.
+
+If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
+
+**.media_type**: `*/*`
+
+##### Notes:
+
+* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead.
+* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view.
+* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details.
+
+##### Basic usage example:
+
+ class FileUploadView(views.APIView):
+ parser_classes = (FileUploadParser,)
+
+ def put(self, request, filename, format=None):
+ file_obj = request.FILES['file']
+ # ...
+ # do some staff with uploaded file
+ # ...
+ return Response(status=204)
+
+
---
# Custom parsers
@@ -130,33 +172,19 @@ The following is an example plaintext parser that will populate the `request.DAT
"""
return stream.read()
-## Uploading file content
-
-If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property.
-
-For example:
+---
- class SimpleFileUploadParser(BaseParser):
- """
- A naive raw file upload parser.
- """
- media_type = '*/*' # Accept anything
+# Third party packages
- def parse(self, stream, media_type=None, parser_context=None):
- content = stream.read()
- name = 'example.dat'
- content_type = 'application/octet-stream'
- size = len(content)
- charset = 'utf-8'
+The following third party packages are also available.
- # Write a temporary file based on the request content
- temp = tempfile.NamedTemporaryFile(delete=False)
- temp.write(content)
- uploaded = UploadedFile(temp, name, content_type, size, charset)
+## MessagePack
- # Return the uploaded file
- data = {}
- files = {name: uploaded}
- return DataAndFiles(data, files)
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
+[jquery-ajax]: http://api.jquery.com/jQuery.ajax/
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
+[upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers
+[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[juanriaza]: https://github.com/juanriaza
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index fce68f6d..db0d4b26 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -21,7 +21,12 @@ If any permission check fails an `exceptions.PermissionDenied` exception will be
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
-Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
+Object level permissions are run by REST framework's generic views when `.get_object()` is called.
+As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
+
+If you're writing your own views and want to enforce object level permissions,
+you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object.
+This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions.
## Setting the permission policy
@@ -39,7 +44,8 @@ If not specified, this setting defaults to allowing unrestricted access:
'rest_framework.permissions.AllowAny',
)
-You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
+You can also set the authentication policy on a per-view, or per-viewset basis,
+using the `APIView` class based views.
class ExampleView(APIView):
permission_classes = (IsAuthenticated,)
@@ -90,29 +96,104 @@ This permission is suitable if you want to your API to allow read permissions to
## DjangoModelPermissions
-This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user has the relevant model permissions assigned.
+This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
* `POST` requests require the user to have the `add` permission on the model.
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
* `DELETE` requests require the user to have the `delete` permission on the model.
-
+
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
-The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] that provide object-level permissions should work just fine with `DjangoModelPermissions` without any custom configuration required.
+## DjangoModelPermissionsOrAnonReadOnly
+
+Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
+
+## TokenHasReadWriteScope
+
+This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide.
+
+Requests with a safe methods of `GET`, `OPTIONS` or `HEAD` will be allowed if the authenticated token has read permission.
+
+Requests for `POST`, `PUT`, `PATCH` and `DELETE` will be allowed if the authenticated token has write permission.
+
+This permission class relies on the implementations of the [django-oauth-plus][django-oauth-plus] and [django-oauth2-provider][django-oauth2-provider] libraries, which both provide limited support for controlling the scope of access tokens:
+
+* `django-oauth-plus`: Tokens are associated with a `Resource` class which has a `name`, `url` and `is_readonly` properties.
+* `django-oauth2-provider`: Tokens are associated with a bitwise `scope` attribute, that defaults to providing bitwise values for `read` and/or `write`.
+
+If you require more advanced scoping for your API, such as restricting tokens to accessing a subset of functionality of your API then you will need to provide a custom permission class. See the source of the `django-oauth-plus` or `django-oauth2-provider` package for more details on scoping token access.
---
# Custom permissions
-To implement a custom permission, override `BasePermission` and implement the `.has_permission(self, request, view, obj=None)` method.
+To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
+
+* `.has_permission(self, request, view)`
+* `.has_object_permission(self, request, view, obj)`
+
+The methods should return `True` if the request should be granted access, and `False` otherwise.
+
+If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example:
+
+ if request.method in permissions.SAFE_METHODS:
+ # Check permissions for read-only request
+ else:
+ # Check permissions for write request
+
+---
+
+**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
+
+As of version 2.2 this signature has now been replaced with two seperate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
+
+For more details see the [2.2 release announcement][2.2-announcement].
+
+---
+
+## Examples
+
+The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
+
+ class BlacklistPermission(permissions.BasePermission):
+ """
+ Global permission check for blacklisted IPs.
+ """
+
+ def has_permission(self, request, view):
+ ip_addr = request.META['REMOTE_ADDR']
+ blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
+ return not blacklisted
+
+As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
+
+ class IsOwnerOrReadOnly(permissions.BasePermission):
+ """
+ Object-level permission to only allow owners of an object to edit it.
+ Assumes the model instance has an `owner` attribute.
+ """
+
+ def has_object_permission(self, request, view, obj):
+ # Read permissions are allowed to any request,
+ # so we'll always allow GET, HEAD or OPTIONS requests.
+ if request.method in permissions.SAFE_METHODS:
+ return True
+
+ # Instance must have an attribute named `owner`.
+ return obj.owner == request.user
-The method should return `True` if the request should be granted access, and `False` otherwise.
+Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return.
+Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
[throttling]: throttling.md
[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
[guardian]: https://github.com/lukaszb/django-guardian
+[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus
+[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
+[2.2-announcement]: ../topics/2.2-announcement.md
+[filtering]: filtering.md
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
new file mode 100644
index 00000000..155c89de
--- /dev/null
+++ b/docs/api-guide/relations.md
@@ -0,0 +1,440 @@
+<a class="github" href="relations.py"></a>
+
+# Serializer relations
+
+> Bad programmers worry about the code.
+> Good programmers worry about data structures and their relationships.
+>
+> &mdash; [Linus Torvalds][cite]
+
+
+Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
+
+---
+
+**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
+
+---
+
+# API Reference
+
+In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.
+
+ class Album(models.Model):
+ album_name = models.CharField(max_length=100)
+ artist = models.CharField(max_length=100)
+
+ class Track(models.Model):
+ album = models.ForeignKey(Album, related_name='tracks')
+ order = models.IntegerField()
+ title = models.CharField(max_length=100)
+ duration = models.IntegerField()
+
+ class Meta:
+ unique_together = ('album', 'order')
+ order_by = 'order'
+
+ def __unicode__(self):
+ return '%d: %s' % (self.order, self.title)
+
+## RelatedField
+
+`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method.
+
+For example, the following serializer.
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = RelatedField(many=True)
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Would serialize to the following representation.
+
+ {
+ 'album_name': 'Things We Lost In The Fire',
+ 'artist': 'Low'
+ 'tracks': [
+ '1: Sunflower',
+ '2: Whitetail',
+ '3: Dinosaur Act',
+ ...
+ ]
+ }
+
+This field is read only.
+
+**Arguments**:
+
+* `many` - If applied to a to-many relationship, you should set this argument to `True`.
+
+## PrimaryKeyRelatedField
+
+`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key.
+
+For example, the following serializer:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = PrimaryKeyRelatedField(many=True, read_only=True)
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Would serialize to a representation like this:
+
+ {
+ 'album_name': 'The Roots',
+ 'artist': 'Undun'
+ 'tracks': [
+ 89,
+ 90,
+ 91,
+ ...
+ ]
+ }
+
+By default this field is read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `many` - If applied to a to-many relationship, you should set this argument to `True`.
+* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+
+## HyperlinkedRelatedField
+
+`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
+
+For example, the following serializer:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = HyperlinkedRelatedField(many=True, read_only=True,
+ view_name='track-detail')
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Would serialize to a representation like this:
+
+ {
+ 'album_name': 'Graceland',
+ 'artist': 'Paul Simon'
+ 'tracks': [
+ 'http://www.example.com/api/tracks/45/',
+ 'http://www.example.com/api/tracks/46/',
+ 'http://www.example.com/api/tracks/47/',
+ ...
+ ]
+ }
+
+By default this field is read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `many` - If applied to a to-many relationship, you should set this argument to `True`.
+* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+
+## SlugRelatedField
+
+`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
+
+For example, the following serializer:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = SlugRelatedField(many=True, read_only=True, slug_field='title')
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Would serialize to a representation like this:
+
+ {
+ 'album_name': 'Dear John',
+ 'artist': 'Loney Dear'
+ 'tracks': [
+ 'Airport Surroundings',
+ 'Everything Turns to You',
+ 'I Was Only Going Out',
+ ...
+ ]
+ }
+
+By default this field is read-write, although you can change this behavior using the `read_only` flag.
+
+When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`.
+
+**Arguments**:
+
+* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required**
+* `many` - If applied to a to-many relationship, you should set this argument to `True`.
+* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+
+## HyperlinkedIdentityField
+
+This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
+
+ class AlbumSerializer(serializers.HyperlinkedModelSerializer):
+ track_listing = HyperlinkedIdentityField(view_name='track-list')
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'track_listing')
+
+Would serialize to a representation like this:
+
+ {
+ 'album_name': 'The Eraser',
+ 'artist': 'Thom Yorke'
+ 'track_listing': 'http://www.example.com/api/track_list/12/',
+ }
+
+This field is always read-only.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+
+---
+
+# Nested relationships
+
+Nested relationships can be expressed by using serializers as fields.
+
+If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
+
+Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style.
+
+## Example
+
+For example, the following serializer:
+
+ class TrackSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Track
+ fields = ('order', 'title')
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = TrackSerializer(many=True)
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Would serialize to a nested representation like this:
+
+ {
+ 'album_name': 'The Grey Album',
+ 'artist': 'Danger Mouse'
+ 'tracks': [
+ {'order': 1, 'title': 'Public Service Annoucement'},
+ {'order': 2, 'title': 'What More Can I Say'},
+ {'order': 3, 'title': 'Encore'},
+ ...
+ ],
+ }
+
+# Custom relational fields
+
+To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target.
+
+If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition.
+
+## Example
+
+For, example, we could define a relational field, to serialize a track to a custom string representation, using it's ordering, title, and duration.
+
+ import time
+
+ class TrackListingField(serializers.RelatedField):
+ def to_native(self, value):
+ duration = time.strftime('%M:%S', time.gmtime(value.duration))
+ return 'Track %d: %s (%s)' % (value.order, value.name, duration)
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = TrackListingField(many=True)
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+This custom field would then serialize to the following representation.
+
+ {
+ 'album_name': 'Sometimes I Wish We Were an Eagle',
+ 'artist': 'Bill Callahan'
+ 'tracks': [
+ 'Track 1: Jim Cain (04:39)',
+ 'Track 2: Eid Ma Clack Shaw (04:19)',
+ 'Track 3: The Wind and the Dove (04:34)',
+ ...
+ ]
+ }
+
+---
+
+# Further notes
+
+## Reverse relations
+
+Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ class Meta:
+ fields = ('tracks', ...)
+
+You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
+
+ class Track(models.Model):
+ album = models.ForeignKey(Album, related_name='tracks')
+ ...
+
+If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ class Meta:
+ fields = ('track_set', ...)
+
+See the Django documentation on [reverse relationships][reverse-relationships] for more details.
+
+## Generic relationships
+
+If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.
+
+For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
+
+ class TaggedItem(models.Model):
+ """
+ Tags arbitrary model instances using a generic relation.
+
+ See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
+ """
+ tag_name = models.SlugField()
+ content_type = models.ForeignKey(ContentType)
+ object_id = models.PositiveIntegerField()
+ tagged_object = GenericForeignKey('content_type', 'object_id')
+
+ def __unicode__(self):
+ return self.tag
+
+And the following two models, which may be have associated tags:
+
+ class Bookmark(models.Model):
+ """
+ A bookmark consists of a URL, and 0 or more descriptive tags.
+ """
+ url = models.URLField()
+ tags = GenericRelation(TaggedItem)
+
+
+ class Note(models.Model):
+ """
+ A note consists of some text, and 0 or more descriptive tags.
+ """
+ text = models.CharField(max_length=1000)
+ tags = GenericRelation(TaggedItem)
+
+We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.
+
+ class TaggedObjectRelatedField(serializers.RelatedField):
+ """
+ A custom field to use for the `tagged_object` generic relationship.
+ """
+
+ def to_native(self, value):
+ """
+ Serialize tagged objects to a simple textual representation.
+ """
+ if isinstance(value, Bookmark):
+ return 'Bookmark: ' + value.url
+ elif isinstance(value, Note):
+ return 'Note: ' + value.text
+ raise Exception('Unexpected type of tagged object')
+
+If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method:
+
+ def to_native(self, value):
+ """
+ Serialize bookmark instances using a bookmark serializer,
+ and note instances using a note serializer.
+ """
+ if isinstance(value, Bookmark):
+ serializer = BookmarkSerializer(value)
+ elif isinstance(value, Note):
+ serializer = NoteSerializer(value)
+ else:
+ raise Exception('Unexpected type of tagged object')
+
+ return serializer.data
+
+Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.
+
+For more information see [the Django documentation on generic relations][generic-relations].
+
+## Advanced Hyperlinked fields
+
+If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
+
+There are two methods you'll need to override.
+
+#### get_url(self, obj, view_name, request, format)
+
+This method should return the URL that corresponds to the given object.
+
+May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
+attributes are not configured to correctly match the URL conf.
+
+#### get_object(self, queryset, view_name, view_args, view_kwargs)
+
+
+This method should the object that corresponds to the matched URL conf arguments.
+
+May raise an `ObjectDoesNotExist` exception.
+
+### Example
+
+For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
+
+ class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
+ def get_url(self, obj, view_name, request, format):
+ kwargs = {'account': obj.account, 'slug': obj.slug}
+ return reverse(view_name, kwargs=kwargs, request=request, format=format)
+
+ def get_object(self, queryset, view_name, view_args, view_kwargs):
+ account = view_kwargs['account']
+ slug = view_kwargs['slug']
+ return queryset.get(account=account, slug=sug)
+
+---
+
+## Deprecated APIs
+
+The following classes have been deprecated, in favor of the `many=<bool>` syntax.
+They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default.
+
+* `ManyRelatedField`
+* `ManyPrimaryKeyRelatedField`
+* `ManyHyperlinkedRelatedField`
+* `ManySlugRelatedField`
+
+The `null=<bool>` flag has been deprecated in favor of the `required=<bool>` flag. It will continue to function, but will raise a `PendingDeprecationWarning`.
+
+In the 2.3 release, these warnings will be escalated to a `DeprecationWarning`, which is loud by default.
+In the 2.4 release, these parts of the API will be removed entirely.
+
+For more details see the [2.2 release announcement][2.2-announcement].
+
+[cite]: http://lwn.net/Articles/193245/
+[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
+[generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
+[2.2-announcement]: ../topics/2.2-announcement.md
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 374ff0ab..ed733c65 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -27,7 +27,8 @@ The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CL
)
}
-You can also set the renderers used for an individual view, using the `APIView` class based views.
+You can also set the renderers used for an individual view, or viewset,
+using the `APIView` class based views.
class UserCountView(APIView):
"""
@@ -56,7 +57,7 @@ Or, if you're using the `@api_view` decorator with function based views.
It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response.
-For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
+For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers].
@@ -80,7 +81,7 @@ Renders the request data into `JSONP`. The `JSONP` media type provides a mechan
The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
-**Note**: If you require cross-domain AJAX requests, you may also want to consider using [CORS] as an alternative to `JSONP`.
+**Note**: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
**.media_type**: `application/javascript`
@@ -90,6 +91,8 @@ The javascript callback function must be set by the client including a `callback
Renders the request data into `YAML`.
+Requires the `pyyaml` package to be installed.
+
**.media_type**: `application/yaml`
**.format**: `'.yaml'`
@@ -115,17 +118,17 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
The template name is determined by (in order of preference):
-1. An explicit `.template_name` attribute set on the response.
+1. An explicit `template_name` argument passed to the response.
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 `TemplateHTMLRenderer`:
- class UserInstance(generics.RetrieveUserAPIView):
+ class UserDetail(generics.RetrieveUserAPIView):
"""
A view that returns a templated HTML representations of a given user.
"""
- model = Users
+ queryset = User.objects.all()
renderer_classes = (TemplateHTMLRenderer,)
def get(self, request, *args, **kwargs)
@@ -164,7 +167,7 @@ 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.
+Renders data into HTML for the Browsable 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.
**.media_type**: `text/html`
@@ -271,13 +274,32 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## MessagePack
+
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
+
+## CSV
+
+Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
-[CORS]: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
+[cors]: http://www.w3.org/TR/cors/
+[cors-docs]: ../topics/ajax-csrf-cors.md
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
-[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views \ No newline at end of file
+[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
+[messagepack]: http://msgpack.org/
+[juanriaza]: https://github.com/juanriaza
+[mjumbewu]: https://github.com/mjumbewu
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md
index 72932f5d..39a34fcf 100644
--- a/docs/api-guide/requests.md
+++ b/docs/api-guide/requests.md
@@ -83,13 +83,13 @@ You won't typically need to access this property.
# Browser enhancements
-REST framework supports a few browser enhancements such as browser-based `PUT` and `DELETE` forms.
+REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms.
## .method
`request.method` returns the **uppercased** string representation of the request's HTTP method.
-Browser-based `PUT` and `DELETE` forms are transparently supported.
+Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported.
For more information see the [browser enhancements documentation].
diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md
new file mode 100644
index 00000000..6588d7e5
--- /dev/null
+++ b/docs/api-guide/routers.md
@@ -0,0 +1,111 @@
+<a class="github" href="routers.py"></a>
+
+# Routers
+
+> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
+>
+> &mdash; [Ruby on Rails Documentation][cite]
+
+Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.
+
+REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.
+
+## Usage
+
+Here's an example of a simple URL conf, that uses `DefaultRouter`.
+
+ router = routers.SimpleRouter()
+ router.register(r'users', UserViewSet)
+ router.register(r'accounts', AccountViewSet)
+ urlpatterns = router.urls
+
+There are two mandatory arguments to the `register()` method:
+
+* `prefix` - The URL prefix to use for this set of routes.
+* `viewset` - The viewset class.
+
+Optionally, you may also specify an additional argument:
+
+* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `model` or `queryset` attribute on the viewset, if it has one.
+
+The example above would generate the following URL patterns:
+
+* URL pattern: `^users/$` Name: `'user-list'`
+* URL pattern: `^users/{pk}/$` Name: `'user-detail'`
+* URL pattern: `^accounts/$` Name: `'account-list'`
+* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'`
+
+### Extra link and actions
+
+Any methods on the viewset decorated with `@link` or `@action` will also be routed.
+For example, a given method like this on the `UserViewSet` class:
+
+ @action(permission_classes=[IsAdminOrIsSelf])
+ def set_password(self, request, pk=None):
+ ...
+
+The following URL pattern would additionally be generated:
+
+* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
+
+# API Guide
+
+## SimpleRouter
+
+This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@link` or `@action` decorators.
+
+<table border=1>
+ <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
+ <tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
+ <tr><td>POST</td><td>create</td></tr>
+ <tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
+ <tr><td>PUT</td><td>update</td></tr>
+ <tr><td>PATCH</td><td>partial_update</td></tr>
+ <tr><td>DELETE</td><td>destroy</td></tr>
+ <tr><td rowspan=2>{prefix}/{lookup}/{methodname}/</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
+ <tr><td>POST</td><td>@action decorated method</td></tr>
+</table>
+
+## DefaultRouter
+
+This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
+
+<table border=1>
+ <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
+ <tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
+ <tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
+ <tr><td>POST</td><td>create</td></tr>
+ <tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
+ <tr><td>PUT</td><td>update</td></tr>
+ <tr><td>PATCH</td><td>partial_update</td></tr>
+ <tr><td>DELETE</td><td>destroy</td></tr>
+ <tr><td rowspan=2>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
+ <tr><td>POST</td><td>@action decorated method</td></tr>
+</table>
+
+# Custom Routers
+
+Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
+
+The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset.
+
+## Example
+
+The following example will only route to the `list` and `retrieve` actions, and unlike the routers included by REST framework, it does not use the trailing slash convention.
+
+ class ReadOnlyRouter(SimpleRouter):
+ """
+ A router for read-only APIs, which doesn't use trailing suffixes.
+ """
+ routes = [
+ (r'^{prefix}$', {'get': 'list'}, '{basename}-list'),
+ (r'^{prefix}/{lookup}$', {'get': 'retrieve'}, '{basename}-detail')
+ ]
+
+## Advanced custom routers
+
+If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
+
+You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
+
+[cite]: http://guides.rubyonrails.org/routing.html
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 19efde3c..c83a0967 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -4,8 +4,7 @@
> Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
-will take some serious design work. Any offers to help out in this
-area would be gratefully accepted.
+will take some serious design work.
>
> &mdash; Russell Keith-Magee, [Django users group][cite]
@@ -26,6 +25,7 @@ Let's start by creating a simple object we can use for example purposes:
comment = Comment(email='leila@example.com', content='foo bar')
We'll declare a serializer that we can use to serialize and deserialize `Comment` objects.
+
Declaring a serializer looks very similar to declaring a form:
class CommentSerializer(serializers.Serializer):
@@ -34,14 +34,20 @@ Declaring a serializer looks very similar to declaring a form:
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
+ """
+ Given a dictionary of deserialized field values, either update
+ an existing model instance, or create a new model instance.
+ """
if instance is not None:
- instance.title = attrs['title']
- instance.content = attrs['content']
- instance.created = attrs['created']
+ instance.title = attrs.get('title', instance.title)
+ instance.content = attrs.get('content', instance.content)
+ instance.created = attrs.get('created', instance.created)
return instance
return Comment(**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. The `restore_object` method is optional, and is only required if we want our serializer to support deserialization.
+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.
+
+The `restore_object` method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items.
## Serializing objects
@@ -53,14 +59,15 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments.
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
- stream = JSONRenderer().render(data)
- stream
+ json = JSONRenderer().render(serializer.data)
+ json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
## Deserializing objects
Deserialization is similar. First we parse a stream into python native datatypes...
+ stream = StringIO(json)
data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance.
@@ -83,9 +90,19 @@ By default, serializers must be passed values for all required fields or they wi
## Validation
-When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages.
+When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example:
+
+ serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
+ serializer.is_valid()
+ # False
+ serializer.errors
+ # {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
+
+Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors.
-### Field-level validation
+When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
+
+#### Field-level validation
You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analagous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments.
@@ -108,32 +125,65 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio
raise serializers.ValidationError("Blog post is not about Django")
return attrs
-### Object-level validation
+#### Object-level validation
+
+To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example:
+
+ from rest_framework import serializers
-To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
+ class EventSerializer(serializers.Serializer):
+ description = serializers.CharField(max_length=100)
+ start = serializers.DateTimeField()
+ finish = serializers.DateTimeField()
+
+ def validate(self, attrs):
+ """
+ Check that the start is before the stop.
+ """
+ if attrs['start'] < attrs['finish']:
+ raise serializers.ValidationError("finish must occur after start")
+ return attrs
## Saving object state
-Serializers also include a `.save()` method that you can override if you want to provide a method of persisting the state of a deserialized object. The default behavior of the method is to simply call `.save()` on the deserialized object instance.
+To save the deserialized objects created by a serializer, call the `.save()` method:
+
+ if serializer.is_valid():
+ serializer.save()
+
+The default behavior of the method is to simply call `.save()` on the deserialized object instance. You can override the default save behaviour by overriding the `.save_object(obj)` method on the serializer class.
The generic views provided by REST framework call the `.save()` method when updating or creating entities.
## Dealing with nested objects
-The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects,
-where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
+The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
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.Field()
- username = serializers.Field()
+ email = serializers.EmailField()
+ username = serializers.CharField(max_length=100)
class CommentSerializer(serializers.Serializer):
user = UserSerializer()
- title = serializers.Field()
- content = serializers.Field()
- created = serializers.Field()
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer.
+
+ class CommentSerializer(serializers.Serializer):
+ user = UserSerializer(required=False) # May be an anonymous user.
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+Similarly if a nested representation should be a list of items, you should the `many=True` flag to the nested serialized.
+
+ class CommentSerializer(serializers.Serializer):
+ user = UserSerializer(required=False)
+ edits = EditItemSerializer(many=True) # A nested list of 'edit' items.
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
---
@@ -141,57 +191,111 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent
---
+## Dealing with multiple objects
-## Creating custom fields
+The `Serializer` class can also handle serializing or deserializing lists of objects.
-If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects.
+#### Serializing multiple objects
-The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation.
+To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
-Let's look at an example of serializing a class that represents an RGB color value:
+ queryset = Book.objects.all()
+ serializer = BookSerializer(queryset, many=True)
+ serializer.data
+ # [
+ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
+ # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
+ # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
+ # ]
- class Color(object):
- """
- 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)
- self.red, self.green, self.blue = red, green, blue
+#### Deserializing multiple objects for creation
- class ColourField(serializers.WritableField):
- """
- Color objects are serialized into "rgb(#, #, #)" notation.
- """
- def to_native(self, obj):
- return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
-
- def from_native(self, data):
- data = data.strip('rgb(').rstrip(')')
- red, green, blue = [int(col) for col in data.split(',')]
- return Color(red, green, blue)
-
+To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the `many=True` flag, and pass a list of data to be deserialized.
-By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`.
+This allows you to write views that create multiple items when a `POST` request is made.
-As an example, let's create a field that can be used represent the class name of the object being serialized:
+For example:
- class ClassNameField(serializers.WritableField):
- def field_to_native(self, obj, field_name):
- """
- Serialize the object's class name, not an attribute of the object.
- """
- return obj.__class__.__name__
+ data = [
+ {'title': 'The bell jar', 'author': 'Sylvia Plath'},
+ {'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'}
+ ]
+ serializer = BookSerializer(data=data, many=True)
+ serializer.is_valid()
+ # True
+ serializer.save() # `.save()` will be called on each deserialized instance
+
+#### Deserializing multiple objects for update
+
+You can also deserialize a list of objects as part of a bulk update of multiple existing items.
+In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with.
+
+This allows you to write views that update or create multiple items when a `PUT` request is made.
+
+ # Capitalizing the titles of the books
+ queryset = Book.objects.all()
+ data = [
+ {'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'},
+ {'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'}
+ ]
+ serializer = BookSerializer(queryset, data=data, many=True)
+ serializer.is_valid()
+ # True
+ serialize.save() # `.save()` will be called on each updated or newly created instance.
+
+By default bulk updates will be limited to updating instances that already exist in the provided queryset.
+
+When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass `allow_add_remove=True` to the serializer.
+
+ serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
+ serializer.is_valid()
+ # True
+ serializer.save() # `.save()` will be called on updated or newly created instances.
+ # `.delete()` will be called on any other items in the `queryset`.
+
+Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects.
- def field_from_native(self, data, field_name, into):
+#### How identity is determined when performing bulk updates
+
+Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances.
+
+By default the serializer class will use the `id` key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the `get_identity` method on the `Serializer` class. For example:
+
+ class AccountSerializer(serializers.Serializer):
+ slug = serializers.CharField(max_length=100)
+ created = serializers.DateTimeField()
+ ... # Various other fields
+
+ def get_identity(self, data):
"""
- We don't want to set anything when we revert this field.
+ This hook is required for bulk update.
+ We need to override the default, to use the slug as the identity.
+
+ Note that the data has not yet been validated at this point,
+ so we need to deal gracefully with incorrect datatypes.
"""
- pass
+ try:
+ return data.get('slug', None)
+ except AttributeError:
+ return None
+
+To map the incoming data items to their corresponding object instances, the `.get_identity()` method will be called both against the incoming data, and against the serialized representation of the existing objects.
+
+## Including extra context
+
+There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.
+
+You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example:
+
+ serializer = AccountSerializer(account, context={'request': request})
+ serializer.data
+ # {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
+
+The context dictionary can be used within any serializer field logic, such as a custom `.to_native()` method, by accessing the `self.context` attribute.
---
-# ModelSerializers
+# ModelSerializer
Often you'll want serializer classes that map closely to model definitions.
The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields.
@@ -200,15 +304,52 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit
class Meta:
model = Account
-**[TODO: Explain model field to serializer field mapping in more detail]**
+By default, all the model fields on the class will be mapped to corresponding serializer fields.
+
+Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Other models fields will be mapped to a corresponding serializer field.
+
+## Specifying which fields should be included
+
+If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
+
+For example:
+
+ class AccountSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Account
+ fields = ('id', 'account_name', 'users', 'created')
+
+## Specifying nested serialization
+
+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
+ fields = ('id', 'account_name', 'users', 'created')
+ depth = 1
+
+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.
+
+## Specifying which fields should be read-only
+
+You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
+
+ class AccountSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Account
+ fields = ('id', 'account_name', 'users', 'created')
+ read_only_fields = ('account_name',)
+
+Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
## Specifying fields explicitly
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', read_only=True)
- group = NaturalKeyField()
+ url = serializers.CharField(source='get_absolute_url', read_only=True)
+ groups = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Account
@@ -217,55 +358,74 @@ Extra fields can correspond to any property or callable on the model.
## Relational fields
-When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation is to use the primary keys of the related instances.
+When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances.
-Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances.
+Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
-The `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` fields provide alternative flat representations.
+For full details see the [serializer relations][relations] documentation.
-The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations.
+---
-The `RelatedField` class may be subclassed to create a custom representation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported.
+# HyperlinkedModelSerializer
-All the relational fields may be used for any relationship or reverse relationship on a model.
+The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys.
-## Specifying which fields should be included
+By default the serializer will include a `url` field instead of a primary key field.
-If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
+The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field.
-For example:
+You can explicitly include the primary key by adding it to the `fields` option, for example:
- class AccountSerializer(serializers.ModelSerializer):
+ class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
- exclude = ('id',)
+ fields = ('url', 'id', 'account_name', 'users', 'created')
-## Specifiying nested serialization
+## How hyperlinked views are determined
-The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
+There needs to be a way of determining which views should be used for hyperlinking to model instances.
- class AccountSerializer(serializers.ModelSerializer):
+By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument.
+
+You can change the field that is used for object lookups by setting the `lookup_field` option. The value of this option should correspond both with a kwarg in the URL conf, and with an field on the model. For example:
+
+ class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
- exclude = ('id',)
- depth = 1
+ fields = ('url', 'account_name', 'users', 'created')
+ lookup_field = 'slug'
+
+For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
+
+ class AccountSerializer(serializers.HyperlinkedModelSerializer):
+ url = serializers.HyperlinkedIdentityField(
+ view_name='account_detail',
+ lookup_field='account_name'
+ )
+ users = serializers.HyperlinkedRelatedField(
+ view_name='user-detail',
+ lookup_field='username',
+ many=True,
+ read_only=True
+ )
-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.
+ class Meta:
+ model = Account
+ fields = ('url', 'account_name', 'users', 'created')
-## Specifying which fields should be read-only
+---
-You may wish to specify multiple fields as read-only. Instead of adding each field explicitely with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
+# Advanced serializer usage
- class AccountSerializer(serializers.ModelSerializer):
- class Meta:
- model = Account
- read_only_fields = ('created', 'modified')
+You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields.
+
+Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.
## Customising the default fields
-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.
+The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
-Each of these methods may either return a field or serializer instance, or `None`.
+For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
### get_pk_field
@@ -275,23 +435,27 @@ Returns the field instance that should be used to represent the pk field.
### get_nested_field
-**Signature**: `.get_nested_field(self, model_field)`
+**Signature**: `.get_nested_field(self, model_field, related_model, to_many)`
Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
+Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
+
### get_related_field
-**Signature**: `.get_related_field(self, model_field, to_many=False)`
+**Signature**: `.get_related_field(self, model_field, related_model, to_many)`
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.
+Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
+
### get_field
**Signature**: `.get_field(self, model_field)`
Returns the field instance that should be used for non-relational, non-pk fields.
-### Example:
+## Example
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
@@ -302,3 +466,4 @@ The following custom model serializer could be used as a base class for model se
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
+[relations]: relations.md
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 7884d096..b00ab4c1 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -34,7 +34,11 @@ The `api_settings` object will check for any user-defined settings, and otherwis
# API Reference
-## DEFAULT_RENDERER_CLASSES
+## API policy settings
+
+*The following settings control the basic API policies, and are applied to every `APIView` class based view, or `@api_view` function based view.*
+
+#### DEFAULT_RENDERER_CLASSES
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
@@ -43,10 +47,9 @@ Default:
(
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
- 'rest_framework.renderers.TemplateHTMLRenderer'
)
-## DEFAULT_PARSER_CLASSES
+#### DEFAULT_PARSER_CLASSES
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.DATA` property.
@@ -54,10 +57,11 @@ Default:
(
'rest_framework.parsers.JSONParser',
- 'rest_framework.parsers.FormParser'
+ 'rest_framework.parsers.FormParser',
+ 'rest_framework.parsers.MultiPartParser'
)
-## DEFAULT_AUTHENTICATION_CLASSES
+#### DEFAULT_AUTHENTICATION_CLASSES
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties.
@@ -65,10 +69,10 @@ Default:
(
'rest_framework.authentication.SessionAuthentication',
- 'rest_framework.authentication.UserBasicAuthentication'
+ 'rest_framework.authentication.BasicAuthentication'
)
-## DEFAULT_PERMISSION_CLASSES
+#### DEFAULT_PERMISSION_CLASSES
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
@@ -78,53 +82,78 @@ Default:
'rest_framework.permissions.AllowAny',
)
-## DEFAULT_THROTTLE_CLASSES
+#### DEFAULT_THROTTLE_CLASSES
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
Default: `()`
-## DEFAULT_MODEL_SERIALIZER_CLASS
+#### DEFAULT_CONTENT_NEGOTIATION_CLASS
+
+A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
+
+Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
+
+---
+
+## Generic view settings
-**TODO**
+*The following settings control the behavior of the generic class based views.*
-Default: `rest_framework.serializers.ModelSerializer`
+#### DEFAULT_MODEL_SERIALIZER_CLASS
-## DEFAULT_PAGINATION_SERIALIZER_CLASS
+A class that determines the default type of model serializer that should be used by a generic view if `model` is specified, but `serializer_class` is not provided.
-**TODO**
+Default: `'rest_framework.serializers.ModelSerializer'`
+
+#### DEFAULT_PAGINATION_SERIALIZER_CLASS
+
+A class the determines the default serialization style for paginated responses.
Default: `rest_framework.pagination.PaginationSerializer`
-## FILTER_BACKEND
+#### DEFAULT_FILTER_BACKENDS
-The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled.
+A list of filter backend classes that should be used for generic filtering.
+If set to `None` then generic filtering is disabled.
-## PAGINATE_BY
+#### PAGINATE_BY
The default page size to use for pagination. If set to `None`, pagination is disabled by default.
Default: `None`
-## PAGINATE_BY_KWARG
+#### PAGINATE_BY_PARAM
The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size.
Default: `None`
-## UNAUTHENTICATED_USER
+---
+
+## Authentication settings
+
+*The following settings control the behavior of unauthenticated requests.*
+
+#### UNAUTHENTICATED_USER
The class that should be used to initialize `request.user` for unauthenticated requests.
Default: `django.contrib.auth.models.AnonymousUser`
-## UNAUTHENTICATED_TOKEN
+#### UNAUTHENTICATED_TOKEN
The class that should be used to initialize `request.auth` for unauthenticated requests.
Default: `None`
-## FORM_METHOD_OVERRIDE
+---
+
+## Browser overrides
+
+*The following settings provide URL or form-based overrides of the default browser behavior.*
+
+#### FORM_METHOD_OVERRIDE
The name of a form field that may be used to override the HTTP method of the form.
@@ -132,7 +161,7 @@ If the value of this setting is `None` then form method overloading will be disa
Default: `'_method'`
-## FORM_CONTENT_OVERRIDE
+#### FORM_CONTENT_OVERRIDE
The name of a form field that may be used to override the content of the form payload. Must be used together with `FORM_CONTENTTYPE_OVERRIDE`.
@@ -140,7 +169,7 @@ If either setting is `None` then form content overloading will be disabled.
Default: `'_content'`
-## FORM_CONTENTTYPE_OVERRIDE
+#### FORM_CONTENTTYPE_OVERRIDE
The name of a form field that may be used to override the content type of the form payload. Must be used together with `FORM_CONTENT_OVERRIDE`.
@@ -148,7 +177,7 @@ If either setting is `None` then form content overloading will be disabled.
Default: `'_content_type'`
-## URL_ACCEPT_OVERRIDE
+#### URL_ACCEPT_OVERRIDE
The name of a URL parameter that may be used to override the HTTP `Accept` header.
@@ -156,14 +185,75 @@ If the value of this setting is `None` then URL accept overloading will be disab
Default: `'accept'`
-## URL_FORMAT_OVERRIDE
+#### URL_FORMAT_OVERRIDE
+
+The name of a URL parameter that may be used to override the default `Accept` header based content negotiation.
Default: `'format'`
-## FORMAT_SUFFIX_KWARG
+---
+
+## Date and time formatting
+
+*The following settings are used to control how date and time representations may be parsed and rendered.*
+
+#### DATETIME_FORMAT
+
+A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return python `datetime` objects, and the datetime encoding will be determined by the renderer.
+
+May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string.
+
+Default: `None`
+
+#### DATETIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
+
+May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings.
+
+Default: `['iso-8601']`
+
+#### DATE_FORMAT
+
+A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return python `date` objects, and the date encoding will be determined by the renderer.
+
+May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string.
+
+Default: `None`
+
+#### DATE_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
+
+May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings.
+
+Default: `['iso-8601']`
+
+#### TIME_FORMAT
+
+A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return python `time` objects, and the time encoding will be determined by the renderer.
+
+May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string.
+
+Default: `None`
+
+#### TIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
+
+May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings.
+
+Default: `['iso-8601']`
+
+---
+
+## Miscellaneous settings
+
+#### FORMAT_SUFFIX_KWARG
-**TODO**
+The name of a parameter in the URL conf that may be used to provide a format suffix.
Default: `'format'`
[cite]: http://www.python.org/dev/peps/pep-0020/
+[strftime]: http://docs.python.org/2/library/time.html#time.strftime
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index b03bc9e0..d6de85ba 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -6,8 +6,6 @@
>
> [Twitter API rate limiting response][cite]
-[cite]: https://dev.twitter.com/docs/error-codes-responses
-
Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
@@ -42,7 +40,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
-You can also set the throttling policy on a per-view basis, using the `APIView` class based views.
+You can also set the throttling policy on a per-view or per-viewset basis,
+using the `APIView` class based views.
class ExampleView(APIView):
throttle_classes = (UserThrottle,)
@@ -63,6 +62,10 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
+## Setting up the cache
+
+The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
+
---
# API Reference
@@ -150,8 +153,19 @@ User requests to either `ContactListView` or `ContactDetailView` would be restri
# Custom throttles
-To create a custom throttle, override `BaseThrottle` and implement `.allow_request(request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
+To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
+## Example
+
+The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
+
+ class RandomRateThrottle(throttles.BaseThrottle):
+ def allow_request(self, request, view):
+ return random.randint(1, 10) == 1
+
+[cite]: https://dev.twitter.com/docs/error-codes-responses
[permissions]: permissions.md
+[cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches
+[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index d1e42ec1..8b26b3e3 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -76,16 +76,16 @@ The following methods are used by REST framework to instantiate the various plug
The following methods are called before dispatching to the handler method.
-### .check_permissions(...)
+### .check_permissions(self, request)
-### .check_throttles(...)
+### .check_throttles(self, request)
-### .perform_content_negotiation(...)
+### .perform_content_negotiation(self, request, force=False)
## Dispatch methods
The following methods are called directly by the view's `.dispatch()` method.
-These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()` and `.delete()`.
+These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`.
### .initial(self, request, \*args, **kwargs)
diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md
new file mode 100644
index 00000000..cd92dc58
--- /dev/null
+++ b/docs/api-guide/viewsets.md
@@ -0,0 +1,219 @@
+<a class="github" href="viewsets.py"></a>
+
+# ViewSets
+
+> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
+>
+> &mdash; [Ruby on Rails Documentation][cite]
+
+
+Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
+
+A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
+
+The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method.
+
+Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
+
+## Example
+
+Let's define a simple viewset that can be used to list or retrieve all the users in the system.
+
+ class UserViewSet(viewsets.ViewSet):
+ """
+ A simple ViewSet that for listing or retrieving users.
+ """
+ def list(self, request):
+ queryset = User.objects.all()
+ serializer = UserSerializer(queryset, many=True)
+ return Response(serializer.data)
+
+ def retrieve(self, request, pk=None):
+ queryset = User.objects.all()
+ user = get_object_or_404(queryset, pk=pk)
+ serializer = UserSerializer(user)
+ return Response(serializer.data)
+
+If we need to, we can bind this viewset into two seperate views, like so:
+
+ user_list = UserViewSet.as_view({'get': 'list'})
+ user_detail = UserViewSet.as_view({'get': 'retrieve'})
+
+Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
+
+ router = DefaultRouter()
+ router.register(r'users', UserViewSet)
+ urlpatterns = router.urls
+
+Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
+
+ class UserViewSet(viewsets.ModelViewSet):
+ """
+ A viewset for viewing and editing user instances.
+ """
+ serializer_class = UserSerializer
+ queryset = User.objects.all()
+
+There are two main advantages of using a `ViewSet` class over using a `View` class.
+
+* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views.
+* By using routers, we no longer need to deal with wiring up the URL conf ourselves.
+
+Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
+
+## Marking extra methods for routing
+
+The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
+
+ class UserViewSet(viewsets.VietSet):
+ """
+ Example empty viewset demonstrating the standard
+ actions that will be handled by a router class.
+
+ If you're using format suffixes, make sure to also include
+ the `format=None` keyword argument for each action.
+ """
+
+ def list(self, request):
+ pass
+
+ def create(self, request):
+ pass
+
+ def retrieve(self, request, pk=None):
+ pass
+
+ def update(self, request, pk=None):
+ pass
+
+ def partial_update(self, request, pk=None):
+ pass
+
+ def destroy(self, request, pk=None):
+ pass
+
+If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decroator will route `POST` requests.
+
+For example:
+
+ from django.contrib.auth.models import User
+ from rest_framework import viewsets
+ from rest_framework.decorators import action
+ from myapp.serializers import UserSerializer
+
+ class UserViewSet(viewsets.ModelViewSet):
+ """
+ A viewset that provides the standard actions
+ """
+ queryset = User.objects.all()
+ serializer_class = UserSerializer
+
+ @action
+ def set_password(self, request, pk=None):
+ user = self.get_object()
+ serializer = PasswordSerializer(data=request.DATA)
+ if serializer.is_valid():
+ user.set_password(serializer.data['password'])
+ user.save()
+ return Response({'status': 'password set'})
+ else:
+ return Response(serializer.errors,
+ status=status.HTTP_400_BAD_REQUEST)
+
+The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example...
+
+ @action(permission_classes=[IsAdminOrIsSelf])
+ def set_password(self, request, pk=None):
+ ...
+
+---
+
+# API Reference
+
+## ViewSet
+
+The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset.
+
+The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly.
+
+## GenericViewSet
+
+The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default.
+
+In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
+
+## ModelViewSet
+
+The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
+
+The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`.
+
+#### Example
+
+Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
+
+ class AccountViewSet(viewsets.ModelViewSet):
+ """
+ A simple ViewSet for viewing and editing accounts.
+ """
+ queryset = Account.objects.all()
+ serializer_class = AccountSerializer
+ permission_classes = [IsAccountAdminOrReadOnly]
+
+Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this:
+
+ class AccountViewSet(viewsets.ModelViewSet):
+ """
+ A simple ViewSet for viewing and editing the accounts
+ associated with the user.
+ """
+ serializer_class = AccountSerializer
+ permission_classes = [IsAccountAdminOrReadOnly]
+
+ def get_queryset(self):
+ return request.user.accounts.all()
+
+Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
+
+## ReadOnlyModelViewSet
+
+The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`.
+
+#### Example
+
+As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
+
+ class AccountViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ A simple ViewSet for viewing accounts.
+ """
+ queryset = Account.objects.all()
+ serializer_class = AccountSerializer
+
+Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`.
+
+# Custom ViewSet base classes
+
+You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way.
+
+## Example
+
+To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
+
+ class CreateListRetrieveViewSet(mixins.CreateMixin,
+ mixins.ListMixin,
+ mixins.RetrieveMixin,
+ viewsets.GenericViewSet):
+ pass
+
+ """
+ A viewset that provides `retrieve`, `update`, and `list` actions.
+
+ To use it, override the class and set the `.queryset` and
+ `.serializer_class` attributes.
+ """
+ pass
+
+By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API.
+
+[cite]: http://guides.rubyonrails.org/routing.html
diff --git a/docs/css/default.css b/docs/css/default.css
index 57446ff9..998efa27 100644
--- a/docs/css/default.css
+++ b/docs/css/default.css
@@ -25,18 +25,29 @@ pre {
margin-top: 9px;
}
+body.index-page #main-content p.badges {
+ padding-bottom: 1px;
+}
+
/* GitHub 'Star' badge */
-body.index-page #main-content iframe {
+body.index-page #main-content iframe.github-star-button {
float: right;
margin-top: -12px;
margin-right: -15px;
}
+/* Tweet button */
+body.index-page #main-content iframe.twitter-share-button {
+ float: right;
+ margin-top: -12px;
+ margin-right: 8px;
+}
+
/* Travis CI badge */
-body.index-page #main-content p:first-of-type {
+body.index-page #main-content img.travis-build-image {
float: right;
margin-right: 8px;
- margin-top: -14px;
+ margin-top: -11px;
margin-bottom: 0px;
}
@@ -266,3 +277,24 @@ footer a {
footer a:hover {
color: gray;
}
+
+.btn-inverse {
+ background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important;
+ background-image: -webkit-linear-gradient(top, #606060, #404040) !important;
+}
+
+.modal-open .modal,.btn:focus{outline:none;}
+
+@media (max-width: 650px) {
+ .repo-link.btn-inverse {display: none;}
+}
+
+td, th {
+ padding: 0.25em;
+ background-color: #f7f7f9;
+ border-color: #e1e1e8;
+}
+
+table {
+ border-color: white;
+}
diff --git a/docs/index.md b/docs/index.md
index cc0f2a13..7c38efd3 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,25 +1,29 @@
-<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
-[![Travis build image][travis-build-image]][travis]
+<p class="badges">
+<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
-# Django REST framework
-
-**A toolkit for building well-connected, self-describing Web APIs.**
+<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a>
+<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
----
+<img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image">
+</p>
-**Note**: This documentation is for the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub.
+# Django REST framework
----
+**Awesome web-browsable Web APIs.**
-Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
+Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
-Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
+Some reasons you might want to use REST framework:
-If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
+* The Web browseable API is a huge useability win for your developers.
+* Authentication policies including OAuth1a and OAuth2 out of the box.
+* Serialization that supports both ORM and non-ORM data sources.
+* Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
+* Extensive documentation, and great community support.
-There is also a sandbox API you can use for testing purposes, [available here][sandbox].
+There is a live example API for testing purposes, [available here][sandbox].
-**Below**: *Screenshot from the browseable API*
+**Below**: *Screenshot from the browsable API*
![Screenshot][image]
@@ -27,50 +31,102 @@ There is also a sandbox API you can use for testing purposes, [available here][s
REST framework requires the following:
-* Python (2.6, 2.7)
+* Python (2.6.5+, 2.7, 3.2, 3.3)
* Django (1.3, 1.4, 1.5)
The following packages are optional:
-* [Markdown][markdown] (2.1.0+) - Markdown support for the browseable API.
+* [Markdown][markdown] (2.1.0+) - Markdown support for the browsable API.
* [PyYAML][yaml] (3.10+) - YAML content-type support.
+* [defusedxml][defusedxml] (0.3+) - XML content-type support.
* [django-filter][django-filter] (0.5.4+) - Filtering support.
+* [django-oauth-plus][django-oauth-plus] (2.0+) and [oauth2][oauth2] (1.5.211+) - OAuth 1.0a support.
+* [django-oauth2-provider][django-oauth2-provider] (0.2.3+) - OAuth 2.0 support.
+
+**Note**: The `oauth2` python package is badly misnamed, and actually provides OAuth 1.0a support. Also note that packages required for both OAuth 1.0a, and OAuth 2.0 are not yet Python 3 compatible.
## Installation
Install using `pip`, including any optional packages you want...
pip install djangorestframework
- pip install markdown # Markdown support for the browseable API.
- pip install pyyaml # YAML content-type support.
+ pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
...or clone the project from github.
git clone git@github.com:tomchristie/django-rest-framework.git
- cd django-rest-framework
- pip install -r requirements.txt
- pip install -r optionals.txt
-Add `rest_framework` to your `INSTALLED_APPS`.
+Add `'rest_framework'` to your `INSTALLED_APPS` setting.
INSTALLED_APPS = (
...
'rest_framework',
)
-If you're intending to use the browseable API you'll want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
+If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
urlpatterns = patterns('',
...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
-Note that the URL path can be whatever you want, but you must include `rest_framework.urls` with the `rest_framework` namespace.
+Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace.
+
+## Example
+
+Let's take a look at a quick example of using REST framework to build a simple model-backed API.
+
+We'll create a read-write API for accessing users and groups.
+
+Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module:
+
+ REST_FRAMEWORK = {
+ # Use hyperlinked styles by default.
+ # Only used if the `serializer_class` attribute is not set on a view.
+ 'DEFAULT_MODEL_SERIALIZER_CLASS':
+ 'rest_framework.serializers.HyperlinkedModelSerializer',
+
+ # Use Django's standard `django.contrib.auth` permissions,
+ # or allow read-only access for unauthenticated users.
+ 'DEFAULT_PERMISSION_CLASSES': [
+ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
+ ]
+ }
+
+Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS`.
+
+We're ready to create our API now.
+Here's our project's root `urls.py` module:
+
+ from django.conf.urls.defaults import url, patterns, include
+ from django.contrib.auth.models import User, Group
+ from rest_framework import viewsets, routers
+
+ # ViewSets define the view behavior.
+ class UserViewSet(viewsets.ModelViewSet):
+ model = User
+
+ class GroupViewSet(viewsets.ModelViewSet):
+ model = Group
+
+
+ # Routers provide an easy way of automatically determining the URL conf
+ router = routers.DefaultRouter()
+ router.register(r'users', UserViewSet)
+ router.register(r'groups', GroupViewSet)
+
+
+ # Wire up our API using automatic URL routing.
+ # Additionally, we include login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+ )
## Quickstart
-Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running with REST framework.
+Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
## Tutorial
@@ -81,6 +137,7 @@ The tutorial will walk you through the building blocks that make up REST framewo
* [3 - Class based views][tut-3]
* [4 - Authentication & permissions][tut-4]
* [5 - Relationships & hyperlinked APIs][tut-5]
+* [6 - Viewsets & routers][tut-6]
## API Guide
@@ -90,10 +147,13 @@ The API guide is your complete reference manual to all the functionality provide
* [Responses][response]
* [Views][views]
* [Generic views][generic-views]
+* [Viewsets][viewsets]
+* [Routers][routers]
* [Parsers][parsers]
* [Renderers][renderers]
* [Serializers][serializers]
* [Serializer fields][fields]
+* [Serializer relations][relations]
* [Authentication][authentication]
* [Permissions][permissions]
* [Throttling][throttling]
@@ -110,10 +170,13 @@ The API guide is your complete reference manual to all the functionality provide
General guides to using REST framework.
+* [AJAX, CSRF & CORS][ajax-csrf-cors]
* [Browser enhancements][browser-enhancements]
* [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [2.0 Announcement][rest-framework-2-announcement]
+* [2.2 Announcement][2.2-announcement]
+* [2.3 Announcement][2.3-announcement]
* [Release Notes][release-notes]
* [Credits][credits]
@@ -129,15 +192,24 @@ Run the tests:
./rest_framework/runtests/runtests.py
+To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`:
+
+ tox
+
## Support
-For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`.
+For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
+
+[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
-Paid support is also available from [DabApps], and can include work on REST framework core, or support with building your REST framework API. Please contact [Tom Christie][email] if you'd like to discuss commercial support options.
+For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
+<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
+<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
+
## License
-Copyright (c) 2011-2012, Tom Christie
+Copyright (c) 2011-2013, Tom Christie
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -161,11 +233,15 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
-[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
+[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
[urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML
-[django-filter]: https://github.com/alex/django-filter
+[defusedxml]: https://pypi.python.org/pypi/defusedxml
+[django-filter]: http://pypi.python.org/pypi/django-filter
+[oauth2]: https://github.com/simplegeo/python-oauth2
+[django-oauth-plus]: https://bitbucket.org/david/django-oauth-plus/wiki/Home
+[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
[image]: img/quickstart.png
[sandbox]: http://restframework.herokuapp.com/
@@ -176,15 +252,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[tut-3]: tutorial/3-class-based-views.md
[tut-4]: tutorial/4-authentication-and-permissions.md
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
+[tut-6]: tutorial/6-viewsets-and-routers.md
[request]: api-guide/requests.md
[response]: api-guide/responses.md
[views]: api-guide/views.md
[generic-views]: api-guide/generic-views.md
+[viewsets]: api-guide/viewsets.md
+[routers]: api-guide/routers.md
[parsers]: api-guide/parsers.md
[renderers]: api-guide/renderers.md
[serializers]: api-guide/serializers.md
[fields]: api-guide/fields.md
+[relations]: api-guide/relations.md
[authentication]: api-guide/authentication.md
[permissions]: api-guide/permissions.md
[throttling]: api-guide/throttling.md
@@ -197,15 +277,24 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[status]: api-guide/status-codes.md
[settings]: api-guide/settings.md
-[csrf]: topics/csrf.md
+[ajax-csrf-cors]: topics/ajax-csrf-cors.md
[browser-enhancements]: topics/browser-enhancements.md
[browsableapi]: topics/browsable-api.md
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
[contributing]: topics/contributing.md
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
+[2.2-announcement]: topics/2.2-announcement.md
+[2.3-announcement]: topics/2.3-announcement.md
[release-notes]: topics/release-notes.md
[credits]: topics/credits.md
+[tox]: http://testrun.org/tox/latest/
+
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
-[DabApps]: http://dabapps.com
-[email]: mailto:tom@tomchristie.com
+[stack-overflow]: http://stackoverflow.com/
+[django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework
+[django-tag]: http://stackoverflow.com/questions/tagged/django
+[paid-support]: http://dabapps.com/services/build/api-development/
+[dabapps]: http://dabapps.com
+[contact-dabapps]: http://dabapps.com/contact/
+[twitter]: https://twitter.com/_tomchristie
diff --git a/docs/template.html b/docs/template.html
index 676a4807..53656e7d 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -2,11 +2,11 @@
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
- <title>Django REST framework</title>
+ <title>{{ title }}</title>
<link href="{{ base_url }}/img/favicon.ico" rel="icon" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
+ <meta name="description" content="{{ description }}">
+ <meta name="author" content="Tom Christie">
<!-- Le styles -->
<link href="{{ base_url }}/css/prettify.css" rel="stylesheet">
@@ -41,6 +41,9 @@
<div class="navbar-inner">
<div class="container-fluid">
<a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
+ <a class="repo-link btn btn-inverse btn-small {{ next_url_disabled }}" href="{{ next_url }}">Next <i class="icon-arrow-right icon-white"></i></a>
+ <a class="repo-link btn btn-inverse btn-small {{ prev_url_disabled }}" href="{{ prev_url }}"><i class="icon-arrow-left icon-white"></i> Previous</a>
+ <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
@@ -59,6 +62,7 @@
<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-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-viewsets-and-routers{{ suffix }}">6 - Viewsets and routers</a></li>
</ul>
</li>
<li class="dropdown">
@@ -68,10 +72,13 @@
<li><a href="{{ base_url }}/api-guide/responses{{ suffix }}">Responses</a></li>
<li><a href="{{ base_url }}/api-guide/views{{ suffix }}">Views</a></li>
<li><a href="{{ base_url }}/api-guide/generic-views{{ suffix }}">Generic views</a></li>
+ <li><a href="{{ base_url }}/api-guide/viewsets{{ suffix }}">Viewsets</a></li>
+ <li><a href="{{ base_url }}/api-guide/routers{{ suffix }}">Routers</a></li>
<li><a href="{{ base_url }}/api-guide/parsers{{ suffix }}">Parsers</a></li>
<li><a href="{{ base_url }}/api-guide/renderers{{ suffix }}">Renderers</a></li>
<li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li>
<li><a href="{{ base_url }}/api-guide/fields{{ suffix }}">Serializer fields</a></li>
+ <li><a href="{{ base_url }}/api-guide/relations{{ suffix }}">Serializer relations</a></li>
<li><a href="{{ base_url }}/api-guide/authentication{{ suffix }}">Authentication</a></li>
<li><a href="{{ base_url }}/api-guide/permissions{{ suffix }}">Permissions</a></li>
<li><a href="{{ base_url }}/api-guide/throttling{{ suffix }}">Throttling</a></li>
@@ -88,10 +95,13 @@
<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/ajax-csrf-cors{{ suffix }}">AJAX, CSRF & CORS</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/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
+ <li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
+ <li><a href="{{ base_url }}/topics/2.3-announcement{{ suffix }}">2.3 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>
</ul>
@@ -115,6 +125,34 @@
<div class="body-content">
<div class="container-fluid">
+
+<!-- Search Modal -->
+<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
+ <div class="modal-header">
+ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
+ <h3 id="myModalLabel">Documentation search</h3>
+ </div>
+ <div class="modal-body">
+ <!-- Custom google search -->
+ <script>
+ (function() {
+ var cx = '015016005043623903336:rxraeohqk6w';
+ var gcse = document.createElement('script');
+ gcse.type = 'text/javascript';
+ gcse.async = true;
+ gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
+ '//www.google.com/cse/cse.js?cx=' + cx;
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(gcse, s);
+ })();
+ </script>
+ <gcse:search></gcse:search>
+ </div>
+ <div class="modal-footer">
+ <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
+ </div>
+</div>
+
<div class="row-fluid">
<div class="span3">
diff --git a/docs/topics/2.2-announcement.md b/docs/topics/2.2-announcement.md
new file mode 100644
index 00000000..d7164ce4
--- /dev/null
+++ b/docs/topics/2.2-announcement.md
@@ -0,0 +1,159 @@
+# REST framework 2.2 announcement
+
+The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.
+
+## Python 3 support
+
+Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently [considered experimental][django-python-3].
+
+Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.
+
+If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
+
+Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
+
+## Deprecation policy
+
+We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
+
+The timeline for deprecation works as follows:
+
+* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
+
+* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default.
+
+* Version 2.4 will remove the deprecated bits of API entirely.
+
+Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
+
+## Community
+
+As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in [the credits][credits], is now at over **one hundred individuals**. Each name on that list represents at least one merged pull request, however large or small.
+
+Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons].
+
+---
+
+## API changes
+
+The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.
+
+### Cleaner to-many related fields
+
+The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax.
+
+For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
+
+ class UserSerializer(serializers.HyperlinkedModelSerializer):
+ questions = serializers.PrimaryKeyRelatedField(many=True)
+
+ class Meta:
+ fields = ('username', 'questions')
+
+The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.
+
+The change also applies to serializers. If you have a nested serializer, you should start using `many=True` for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:
+
+ class TrackSerializer(serializer.ModelSerializer):
+ class Meta:
+ model = Track
+ fields = ('name', 'duration')
+
+ class AlbumSerializer(serializer.ModelSerializer):
+ tracks = TrackSerializer(many=True)
+
+ class Meta:
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
+
+Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the `many=True` flag.
+
+ serializer = SnippetSerializer(Snippet.objects.all(), many=True)
+ serializer.data
+
+This more explicit behavior on serializing and deserializing data [makes integration with non-ORM backends such as MongoDB easier][564], as instances to be serialized can include the `__iter__` method, without incorrectly triggering list-based serialization, or requiring workarounds.
+
+The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag.
+
+**Note**: If you need to forcibly turn off the implict "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4.
+
+### Cleaner optional relationships
+
+Serializer relationships for nullable Foreign Keys will change from using the current `null=True` flag, to instead using `required=False`.
+
+For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a `Serializer` class:
+
+ current_company = serializers.HyperlinkedRelatedField(required=False)
+
+This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API.
+
+Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
+
+The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`.
+
+### Cleaner CharField syntax
+
+The `CharField` API previously took an optional `blank=True` argument, which was intended to differentiate between null CharField input, and blank CharField input.
+
+In keeping with Django's CharField API, REST framework's `CharField` will only ever return the empty string, for missing or `None` inputs. The `blank` flag will no longer be in use, and you should instead just use the `required=<bool>` flag. For example:
+
+ extra_details = CharField(required=False)
+
+The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`.
+
+### Simpler object-level permissions
+
+Custom permissions classes previously used the signatute `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance.
+
+The global permissions check and object-level permissions check are now seperated into two seperate methods, which gives a cleaner, more obvious API.
+
+* Global permission checks now use the `.has_permission(self, request, view)` signature.
+* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`.
+
+For example, the following custom permission class:
+
+ class IsOwner(permissions.BasePermission):
+ """
+ Custom permission to only allow owners of an object to view or edit it.
+ Model instances are expected to include an `owner` attribute.
+ """
+
+ def has_permission(self, request, view, obj=None):
+ if obj is None:
+ # Ignore global permissions check
+ return True
+
+ return obj.owner == request.user
+
+Now becomes:
+
+ class IsOwner(permissions.BasePermission):
+ """
+ Custom permission to only allow owners of an object to view or edit it.
+ Model instances are expected to include an `owner` attribute.
+ """
+
+ def has_object_permission(self, request, view, obj):
+ return obj.owner == request.user
+
+If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but it's use will raise a `PendingDeprecationWarning`.
+
+Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.
+
+### More explicit hyperlink relations behavior
+
+When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fallback to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.
+
+From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but it's use will raise a `PendingDeprecationWarning`.
+
+[xordoquy]: https://github.com/xordoquy
+[django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3
+[porting-python-3]: https://docs.djangoproject.com/en/dev/topics/python3/
+[python-compat]: https://docs.djangoproject.com/en/dev/releases/1.5/#python-compatibility
+[django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
+[credits]: http://django-rest-framework.org/topics/credits.html
+[mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
+[django-rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs
+[marcgibbons]: https://github.com/marcgibbons/
+[issues]: https://github.com/tomchristie/django-rest-framework/issues
+[564]: https://github.com/tomchristie/django-rest-framework/issues/564
diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md
new file mode 100644
index 00000000..4df9c819
--- /dev/null
+++ b/docs/topics/2.3-announcement.md
@@ -0,0 +1,264 @@
+# REST framework 2.3 announcement
+
+REST framework 2.3 makes it even quicker and easier to build your Web APIs.
+
+## ViewSets and Routers
+
+The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes.
+
+A viewset is simply a type of class based view that allows you to group multiple views into a single common class.
+
+Routers allow you to automatically determine the URLconf for your viewset classes.
+
+As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module:
+
+ """
+ A REST framework API for viewing and editing users and groups.
+ """
+ from django.conf.urls.defaults import url, patterns, include
+ from django.contrib.auth.models import User, Group
+ from rest_framework import viewsets, routers
+
+
+ # ViewSets define the view behavior.
+ class UserViewSet(viewsets.ModelViewSet):
+ model = User
+
+ class GroupViewSet(viewsets.ModelViewSet):
+ model = Group
+
+
+ # Routers provide an easy way of automatically determining the URL conf
+ router = routers.DefaultRouter()
+ router.register(r'users', UserViewSet)
+ router.register(r'groups', GroupViewSet)
+
+
+ # Wire up our API using automatic URL routing.
+ # Additionally, we include login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+ )
+
+The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage.
+
+## Simpler views
+
+This release rationalises the API and implementation of the generic views, dropping the dependancy on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
+
+This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
+
+## Easier Serializers
+
+REST framework lets you be totally explict regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.
+
+The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class.
+
+For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
+
+ class BlogSerializer(serializers.ModelSerializer):
+ comments = serializers.PrimaryKeyRelatedField(many=True)
+
+ class Meta:
+ model = Blog
+ fields = ('id', 'title', 'created', 'comments')
+
+As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
+
+ class BlogSerializer(serializers.ModelSerializer):
+ """
+ Don't need to specify the 'comments' field explicitly anymore.
+ """
+ class Meta:
+ model = Blog
+ fields = ('id', 'title', 'created', 'comments')
+
+Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.
+
+ class BlogSerializer(serializers.HyperlinkedModelSerializer):
+ """
+ This is a hyperlinked serializer, which default to using
+ a field named 'url' as the primary identifier.
+ Note that we can now easily also add in the 'id' field.
+ """
+ class Meta:
+ model = Blog
+ fields = ('url', 'id', 'title', 'created', 'comments')
+
+## More flexible filtering
+
+The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class.
+
+The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting.
+
+Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.
+
+---
+
+# API Changes
+
+## Simplified generic view classes
+
+The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.
+
+Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.
+
+Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses.
+
+### Removed attributes
+
+The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unusedand have now been entirely removed.
+
+* context_object_name
+* get_context_data()
+* get_context_object_name()
+
+The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.
+
+* paginator_class
+* get_paginator()
+* get_allow_empty()
+* get_slug_field()
+
+There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.
+
+Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.
+
+### Simplified methods
+
+The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.
+
+Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`.
+
+The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropraite page size, or returns `None`, if pagination is not configured for the view.
+
+Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`.
+
+### Deprecated attributes
+
+The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.
+
+* pk_url_kwarg = 'pk'
+* slug_url_kwarg = 'slug'
+* slug_field = 'slug'
+
+Their usage is replaced with a single attribute:
+
+* lookup_field = 'pk'
+
+This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.
+
+For example, a view with 'username' based lookup might look like this:
+
+ class UserDetail(generics.RetrieveAPIView):
+ lookup_field = 'username'
+ queryset = User.objects.all()
+ serializer_class = UserSerializer
+
+And would have the following entry in the urlconf:
+
+ url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
+
+Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
+
+The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets.
+
+For example:
+
+ class DisallowEmptyQuerysetMixin(object):
+ def get_queryset(self):
+ queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
+ if not queryset.exists():
+ raise Http404
+ return queryset
+
+In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-inforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
+
+## Simpler URL lookups
+
+The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments.
+
+For example, you might have a field that references it's relationship by a hyperlink based on a slug field:
+
+ account = HyperlinkedRelatedField(read_only=True,
+ lookup_field='slug',
+ view_name='account-detail')
+
+Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
+
+## FileUploadParser
+
+2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support.
+
+## DecimalField
+
+2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances.
+
+For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implmentation.
+
+## ModelSerializers and reverse relationships
+
+The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
+
+In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For revese relationships `model_field` will be `None`.
+
+The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
+
+## View names and descriptions
+
+The mechanics of how the names and descriptions used in the browseable API are generated has been modified and cleaned up somewhat.
+
+If you've been customizing this behavior, for example perhaps to use `rst` markup for the browseable API, then you'll need to take a look at the implementation to see what updates you need to make.
+
+Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
+
+---
+
+# Other notes
+
+## More explicit style
+
+The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explict `queryset` and `serializer_class` attributes.
+
+For example, the following is now the recommended style for using generic views:
+
+ class AccountListView(generics.RetrieveAPIView):
+ queryset = MyModel.objects.all()
+ serializer_class = MyModelSerializer
+
+Using an explict `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute.
+
+It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious.
+
+ class AccountListView(generics.RetrieveAPIView):
+ serializer_class = MyModelSerializer
+
+ def get_queryset(self):
+ """
+ Determine the queryset dynamically, depending on the
+ user making the request.
+
+ Note that overriding this method follows on more obviously now
+ that an explicit `queryset` attribute is the usual view style.
+ """
+ return self.user.accounts
+
+## Django 1.3 support
+
+The 2.3.x release series will be the last series to provide compatiblity with Django 1.3.
+
+## Version 2.2 API changes
+
+All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
+
+## What comes next?
+
+* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
+* Extra filter backends for searching and ordering of results are planned to be added shortly.
+
+The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.
+
+[viewset]: ../api-guide/viewsets.md
+[router]: ../api-guide/routers.md
+[part-6]: ../tutorial/6-viewsets-and-routers.md
diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md
new file mode 100644
index 00000000..f7d12940
--- /dev/null
+++ b/docs/topics/ajax-csrf-cors.md
@@ -0,0 +1,41 @@
+# Working with AJAX, CSRF & CORS
+
+> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability &mdash; very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
+>
+> &mdash; [Jeff Atwood][cite]
+
+## Javascript clients
+
+If your building a javascript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
+
+AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
+
+AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`.
+
+## CSRF protection
+
+[Cross Site Request Forgery][csrf] protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
+
+To guard against these type of attacks, you need to do two things:
+
+1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state.
+2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token.
+
+If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
+
+The Django documentation describes how to [include CSRF tokens in AJAX requests][csrf-ajax].
+
+## CORS
+
+[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
+
+The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
+
+[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
+
+[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
+[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
+[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
+[cors]: http://www.w3.org/TR/cors/
+[ottoyiu]: https://github.com/ottoyiu/
+[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
index 9fe82e69..8ee01824 100644
--- a/docs/topics/browsable-api.md
+++ b/docs/topics/browsable-api.md
@@ -35,23 +35,20 @@ A suitable replacement theme can be generated using Bootstrap's [Customize Tool]
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
-For more specific CSS tweaks, use the `extra_style` block instead.
+For more specific CSS tweaks, use the `style` block instead.
### Blocks
All of the blocks available in the browsable API base template that can be used in your `api.html`.
-* `blockbots` - `<meta>` tag that blocks crawlers
* `bodyclass` - (empty) class attribute for the `<body>`
* `bootstrap_theme` - CSS for the Bootstrap theme
* `bootstrap_navbar_variant` - CSS class for the navbar
* `branding` - section of the navbar, see [Bootstrap components][bcomponentsnav]
* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
-* `extrastyle` - (empty) extra CSS for the page
-* `extrahead` - (empty) extra markup for the page `<head>`
* `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned)
-* `global_heading` - (empty) Use to insert content below the header but before the breadcrumbs.
+* `style` - CSS stylesheets for the page
* `title` - title of the page
* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
@@ -63,6 +60,17 @@ All of the [Bootstrap components][bcomponents] are available.
The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay.
+### Login Template
+
+To add branding and customize the look-and-feel of the auth login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`, that extends the `rest_framework/base_login.html` template.
+
+You can add your site name or branding by including the branding block:
+
+ {% block branding %}
+ <h3 style="margin: 0 0 20px;">My Site Name</h3>
+ {% endblock %}
+
+You can also customize the style by adding the `bootstrap_theme` or `style` block similar to `api.html`.
### Advanced Customization
diff --git a/docs/topics/browser-enhancements.md b/docs/topics/browser-enhancements.md
index 6a11f0fa..ce07fe95 100644
--- a/docs/topics/browser-enhancements.md
+++ b/docs/topics/browser-enhancements.md
@@ -19,6 +19,21 @@ For example, given the following form:
`request.method` would return `"DELETE"`.
+## HTTP header based method overriding
+
+REST framework also supports method overriding via the semi-standard `X-HTTP-Method-Override` header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as `PATCH`. For example [Amazon Web Services ELB][aws_elb].
+
+To use it, make a `POST` request, setting the `X-HTTP-Method-Override` header.
+
+For example, making a `PATCH` request via `POST` in jQuery:
+
+ $.ajax({
+ url: '/myresource/',
+ method: 'POST',
+ headers: {'X-HTTP-Method-Override': 'PATCH'},
+ ...
+ });
+
## Browser based submission of non-form content
Browser-based submission of content types other than form are supported by
@@ -62,3 +77,4 @@ as well as how to support content types other than form-encoded data.
[rails]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
[html5]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
[put_delete]: http://amundsen.com/examples/put-delete-forms/
+[aws_elb]: https://forums.aws.amazon.com/thread.jspa?messageID=400724
diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md
index 7fd61c10..1d1fe892 100644
--- a/docs/topics/contributing.md
+++ b/docs/topics/contributing.md
@@ -4,12 +4,138 @@
>
> &mdash; [Tim Berners-Lee][cite]
-## Running the tests
+There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
-## Building the docs
+# Community
-## Managing compatibility issues
+If you use and enjoy REST framework please consider [staring the project on GitHub][github], and [upvoting it on Django packages][django-packages]. Doing so helps potential new users see that the project is well used, and help us continue to attract new users.
-**Describe compat module**
+You might also consider writing a blog post on your experience with using REST framework, writing a tutorial about using the project with a particular javascript framework, or simply sharing the love on Twitter.
-[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html \ No newline at end of file
+Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
+
+When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
+
+# Issues
+
+It's really helpful if you make sure you address issues to the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
+
+Some tips on good issue reporting:
+
+* When decribing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
+* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
+* If reporting a bug, then try to include a pull request with a failing test case. This'll help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
+
+
+
+* TODO: Triage
+
+# Development
+
+* git clone & PYTHONPATH
+* Pep8
+* Recommend editor that runs pep8
+
+### Pull requests
+
+* Make pull requests early
+* Describe branching
+
+### Managing compatibility issues
+
+* Describe compat module
+
+# Testing
+
+* Running the tests
+* tox
+
+# Documentation
+
+The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
+
+There are many great markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
+
+## Building the documentation
+
+To build the documentation, simply run the `mkdocs.py` script.
+
+ ./mkdocs.py
+
+This will build the html output into the `html` directory.
+
+You can build the documentation and open a preview in a browser window by using the `-p` flag.
+
+ ./mkdocs.py -p
+
+## Language style
+
+Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
+
+Some other tips:
+
+* Keep paragraphs reasonably short.
+* Use double spacing after the end of sentences.
+* Don't use the abbreviations such as 'e.g..' but instead use long form, such as 'For example'.
+
+## Markdown style
+
+There are a couple of conventions you should follow when working on the documentation.
+
+##### 1. Headers
+
+Headers should use the hash style. For example:
+
+ ### Some important topic
+
+The underline style should not be used. **Don't do this:**
+
+ Some important topic
+ ====================
+
+##### 2. Links
+
+Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
+
+ Here is a link to [some other thing][other-thing].
+
+ More text...
+
+ [other-thing]: http://example.com/other/thing
+
+This style helps keep the documentation source consistent and readable.
+
+If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
+
+ [authentication]: ../api-guide/authentication.md
+
+Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
+
+##### 3. Notes
+
+If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
+
+ ---
+
+ **Note:** Make sure you do this thing.
+
+ ---
+
+# Third party packages
+
+* Django reusable app
+
+# Core committers
+
+* Still use pull reqs
+* Credits
+
+[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
+[github]: https://github.com/tomchristie/django-rest-framework
+[django-packages]: https://www.djangopackages.com/grids/g/api/
+[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
+[so-filter]: http://stackexchange.com/filters/66475/rest-framework
+[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
+[markdown]: http://daringfireball.net/projects/markdown/basics
+[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
+[mou]: http://mouapp.com/
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index 8b8cac1a..8151b4d3 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -2,9 +2,9 @@
The following people have helped make REST framework great.
-* Tom Christie - [tomchristie]
+* Tom Christie - [tomchristie]
* Marko Tibold - [markotibold]
-* Paul Bagwell - [pbgwl]
+* Paul Miller - [paulmillr]
* Sébastien Piquemal - [sebpiq]
* Carmen Wick - [cwick]
* Alex Ehlke - [aehlke]
@@ -19,7 +19,7 @@ The following people have helped make REST framework great.
* Craig Blaszczyk - [jakul]
* Garcia Solero - [garciasolero]
* Tom Drummond - [devioustree]
-* Danilo Bargen - [gwrtheyrn]
+* Danilo Bargen - [dbrgn]
* Andrew McCloud - [amccloud]
* Thomas Steinacher - [thomasst]
* Meurig Freeman - [meurig]
@@ -81,6 +81,49 @@ The following people have helped make REST framework great.
* Szymon Teżewski - [sunscrapers]
* Joel Marcotte - [joual]
* Trey Hunner - [treyhunner]
+* Roman Akinfold - [akinfold]
+* Toran Billups - [toranb]
+* Sébastien Béal - [sebastibe]
+* Andrew Hankinson - [ahankinson]
+* Juan Riaza - [juanriaza]
+* Michael Mior - [michaelmior]
+* Marc Tamlyn - [mjtamlyn]
+* Richard Wackerbarth - [wackerbarth]
+* Johannes Spielmann - [shezi]
+* James Cleveland - [radiosilence]
+* Steve Gregory - [steve-gregory]
+* Federico Capoano - [nemesisdesign]
+* Bruno Renié - [brutasse]
+* Kevin Stone - [kevinastone]
+* Guglielmo Celata - [guglielmo]
+* Mike Tums - [mktums]
+* Michael Elovskikh - [wronglink]
+* Michał Jaworski - [swistakm]
+* Andrea de Marco - [z4r]
+* Fernando Rocha - [fernandogrd]
+* Xavier Ordoquy - [xordoquy]
+* Adam Wentz - [floppya]
+* Andreas Pelme - [pelme]
+* Ryan Detzel - [ryanrdetzel]
+* Omer Katz - [thedrow]
+* Wiliam Souza - [waa]
+* Jonas Braun - [iekadou]
+* Ian Dash - [bitmonkey]
+* Bouke Haarsma - [bouke]
+* Pierre Dulac - [dulaccc]
+* Dave Kuhn - [kuhnza]
+* Sitong Peng - [stoneg]
+* Victor Shih - [vshih]
+* Atle Frenvik Sveen - [atlefren]
+* J Paul Reed - [preed]
+* Matt Majewski - [forgingdestiny]
+* Jerome Chen - [chenjyw]
+* Andrew Hughes - [eyepulp]
+* Daniel Hepper - [dhepper]
+* Hamish Campbell - [hamishcampbell]
+* Marlon Bailey - [avinash240]
+* James Summerfield - [jsummerfield]
+* Andy Freeland - [rouge8]
Many thanks to everyone who's contributed to the project.
@@ -92,9 +135,9 @@ Project hosting is with [GitHub].
Continuous integration testing is managed with [Travis CI][travis-ci].
-The [live sandbox][sandbox] is hosted on [Heroku].
+The [live sandbox][sandbox] is hosted on [Heroku].
-Various inspiration taken from the [Piston], [Tastypie] and [Dagny] projects.
+Various inspiration taken from the [Rails], [Piston], [Tastypie], [Dagny] and [django-viewsets] projects.
Development of REST framework 2.0 was sponsored by [DabApps].
@@ -103,16 +146,17 @@ Development of REST framework 2.0 was sponsored by [DabApps].
For usage questions please see the [REST framework discussion group][group].
You can also contact [@_tomchristie][twitter] directly on twitter.
-
-[email]: mailto:tom@tomchristie.com
+
[twitter]: http://twitter.com/_tomchristie
[bootstrap]: http://twitter.github.com/bootstrap/
[markdown]: http://daringfireball.net/projects/markdown/
[github]: https://github.com/tomchristie/django-rest-framework
[travis-ci]: https://secure.travis-ci.org/tomchristie/django-rest-framework
+[rails]: http://rubyonrails.org/
[piston]: https://bitbucket.org/jespern/django-piston
[tastypie]: https://github.com/toastdriven/django-tastypie
[dagny]: https://github.com/zacharyvoase/dagny
+[django-viewsets]: https://github.com/BertrandBordage/django-viewsets
[dabapps]: http://lab.dabapps.com
[sandbox]: http://restframework.herokuapp.com/
[heroku]: http://www.heroku.com/
@@ -120,7 +164,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[tomchristie]: https://github.com/tomchristie
[markotibold]: https://github.com/markotibold
-[pbgwl]: https://github.com/pbgwl
+[paulmillr]: https://github.com/paulmillr
[sebpiq]: https://github.com/sebpiq
[cwick]: https://github.com/cwick
[aehlke]: https://github.com/aehlke
@@ -135,7 +179,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[jakul]: https://github.com/jakul
[garciasolero]: https://github.com/garciasolero
[devioustree]: https://github.com/devioustree
-[gwrtheyrn]: https://github.com/gwrtheyrn
+[dbrgn]: https://github.com/dbrgn
[amccloud]: https://github.com/amccloud
[thomasst]: https://github.com/thomasst
[meurig]: https://github.com/meurig
@@ -197,3 +241,46 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[sunscrapers]: https://github.com/sunscrapers
[joual]: https://github.com/joual
[treyhunner]: https://github.com/treyhunner
+[akinfold]: https://github.com/akinfold
+[toranb]: https://github.com/toranb
+[sebastibe]: https://github.com/sebastibe
+[ahankinson]: https://github.com/ahankinson
+[juanriaza]: https://github.com/juanriaza
+[michaelmior]: https://github.com/michaelmior
+[mjtamlyn]: https://github.com/mjtamlyn
+[wackerbarth]: https://github.com/wackerbarth
+[shezi]: https://github.com/shezi
+[radiosilence]: https://github.com/radiosilence
+[steve-gregory]: https://github.com/steve-gregory
+[nemesisdesign]: https://github.com/nemesisdesign
+[brutasse]: https://github.com/brutasse
+[kevinastone]: https://github.com/kevinastone
+[guglielmo]: https://github.com/guglielmo
+[mktums]: https://github.com/mktums
+[wronglink]: https://github.com/wronglink
+[swistakm]: https://github.com/swistakm
+[z4r]: https://github.com/z4r
+[fernandogrd]: https://github.com/fernandogrd
+[xordoquy]: https://github.com/xordoquy
+[floppya]: https://github.com/floppya
+[pelme]: https://github.com/pelme
+[ryanrdetzel]: https://github.com/ryanrdetzel
+[thedrow]: https://github.com/thedrow
+[waa]: https://github.com/wiliamsouza
+[iekadou]: https://github.com/iekadou
+[bitmonkey]: https://github.com/bitmonkey
+[bouke]: https://github.com/bouke
+[dulaccc]: https://github.com/dulaccc
+[kuhnza]: https://github.com/kuhnza
+[stoneg]: https://github.com/stoneg
+[vshih]: https://github.com/vshih
+[atlefren]: https://github.com/atlefren
+[preed]: https://github.com/preed
+[forgingdestiny]: https://github.com/forgingdestiny
+[chenjyw]: https://github.com/chenjyw
+[eyepulp]: https://github.com/eyepulp
+[dhepper]: https://github.com/dhepper
+[hamishcampbell]: https://github.com/hamishcampbell
+[avinash240]: https://github.com/avinash240
+[jsummerfield]: https://github.com/jsummerfield
+[rouge8]: https://github.com/rouge8
diff --git a/docs/topics/csrf.md b/docs/topics/csrf.md
deleted file mode 100644
index 043144c1..00000000
--- a/docs/topics/csrf.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Working with AJAX and CSRF
-
-> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
->
-> &mdash; [Jeff Atwood][cite]
-
-* Explain need to add CSRF token to AJAX requests.
-* Explain deferred CSRF style used by REST framework
-* Why you should use Django's standard login/logout views, and not REST framework view
-
-
-[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
diff --git a/docs/topics/migration.md b/docs/topics/migration.md
deleted file mode 100644
index 25fc9074..00000000
--- a/docs/topics/migration.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# 2.0 Migration Guide
-
-> Move fast and break things
->
-> &mdash; Mark Zuckerberg, [the Hacker Way][cite].
-
-REST framework 2.0 introduces a radical redesign of the core components, and a large number of backwards breaking changes.
-
-### Serialization redesign.
-
-REST framework's serialization and deserialization previously used a slightly odd combination of serializers for output, and Django Forms and Model Forms for input. The serialization core has been completely redesigned based on work that was originally intended for Django core.
-
-2.0's form-like serializers comprehensively address those issues, and are a much more flexible and clean solution to the problems around accepting both form-based and non-form based inputs.
-
-### Generic views improved.
-
-When REST framework 0.1 was released the current Django version was 1.2. REST framework included a backport of the Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
-
-As of 2.0 the generic views in REST framework tie in much more cleanly and obviously with Django's existing codebase, and the mixin architecture is radically simplified.
-
-### Cleaner request-response cycle.
-
-REST framework 2.0's request-response cycle is now much less complex.
-
-* Responses inherit from `SimpleTemplateResponse`, allowing rendering to be delegated to the response, not handled by the view.
-* Requests extend the regular `HttpRequest`, allowing authentication and parsing to be delegated to the request, not handled by the view.
-
-### Renamed attributes & classes.
-
-Various attributes and classes have been renamed in order to fit in better with Django's conventions.
-
-## Example: Blog Posts API
-
-Let's take a look at an example from the REST framework 0.4 documentation...
-
- from djangorestframework.resources import ModelResource
- from djangorestframework.reverse import reverse
- from blogpost.models import BlogPost, Comment
-
-
- class BlogPostResource(ModelResource):
- """
- A Blog Post has a *title* and *content*, and can be associated
- with zero or more comments.
- """
- model = BlogPost
- fields = ('created', 'title', 'slug', 'content', 'url', 'comments')
- ordering = ('-created',)
-
- def url(self, instance):
- return reverse('blog-post',
- kwargs={'key': instance.key},
- request=self.request)
-
- def comments(self, instance):
- return reverse('comments',
- kwargs={'blogpost': instance.key},
- request=self.request)
-
-
- class CommentResource(ModelResource):
- """
- A Comment is associated with a given Blog Post and has a
- *username* and *comment*, and optionally a *rating*.
- """
- model = Comment
- fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost')
- ordering = ('-created',)
-
- def blogpost(self, instance):
- return reverse('blog-post',
- kwargs={'key': instance.blogpost.key},
- request=self.request)
-
-There's a bit of a mix of concerns going on there. We've got some information about how the data should be serialized, such as the `fields` attribute, and some information about how it should be retrieved from the database - the `ordering` attribute.
-
-Let's start to re-write this for REST framework 2.0.
-
- from rest_framework import serializers
-
- class BlogPostSerializer(serializers.HyperlinkedModelSerializer):
- model = BlogPost
- fields = ('created', 'title', 'slug', 'content', 'url', 'comments')
-
- class CommentSerializer(serializers.HyperlinkedModelSerializer):
- model = Comment
- fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost')
-
-[cite]: http://www.wired.com/business/2012/02/zuck-letter/
diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md
index 71fa3c03..560dd305 100644
--- a/docs/topics/release-notes.md
+++ b/docs/topics/release-notes.md
@@ -4,10 +4,245 @@
>
> &mdash; Eric S. Raymond, [The Cathedral and the Bazaar][cite].
-## 2.1.x series
+## Versioning
+
+Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
+
+Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
+
+Major version numbers (x.0.0) are reserved for substantial project milestones. No major point releases are currently planned.
+
+## Deprecation policy
+
+REST framework releases follow a formal deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy].
+
+The timeline for deprecation of a feature present in version 1.0 would work as follows:
+
+* Version 1.1 would remain **fully backwards compatible** with 1.0, but would raise `PendingDeprecationWarning` warnings if you use the feature that are due to be deprecated. These warnings are **silent by default**, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
+
+* Version 1.2 would escalate these warnings to `DeprecationWarning`, which is loud by default.
+
+* Version 1.3 would remove the deprecated bits of API entirely.
+
+Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
+
+## Upgrading
+
+To upgrade Django REST framework to the latest version, use pip:
+
+ pip install -U djangorestframework
+
+You can determine your currently installed version using `pip freeze`:
+
+ pip freeze | grep djangorestframework
+
+---
+
+## 2.3.x series
### Master
+* Bugfix: HyperlinkedIdentityField now uses `lookup_field` kwarg.
+
+### 2.3.2
+
+**Date**: 16th May 2013
+
+* Added SearchFilter
+* Added OrderingFilter
+* Added GenericViewSet
+* Bugfix: Multiple `@action` and `@link` methods now allowed on viewsets.
+* Bugfix: Fix API Root view issue with DjangoModelPermissions
+
+### 2.3.2
+
+**Date**: 8th May 2013
+
+* Bugfix: Fix `TIME_FORMAT`, `DATETIME_FORMAT` and `DATE_FORMAT` settings.
+* Bugfix: Fix `DjangoFilterBackend` issue, failing when used on view with queryset attribute.
+
+### 2.3.1
+
+**Date**: 7th May 2013
+
+* Bugfix: Fix breadcrumb rendering issue.
+
+### 2.3.0
+
+**Date**: 7th May 2013
+
+* ViewSets and Routers.
+* ModelSerializers support reverse relations in 'fields' option.
+* HyperLinkedModelSerializers support 'id' field in 'fields' option.
+* Cleaner generic views.
+* Support for multiple filter classes.
+* FileUploadParser support for raw file uploads.
+* DecimalField support.
+* Made Login template easier to restyle.
+* Bugfix: Fix issue with depth>1 on ModelSerializer.
+
+**Note**: See the [2.3 announcement][2.3-announcement] for full details.
+
+---
+
+## 2.2.x series
+
+### 2.2.7
+
+**Date**: 17th April 2013
+
+* Loud failure when view does not return a `Response` or `HttpResponse`.
+* Bugfix: Fix for Django 1.3 compatiblity.
+* Bugfix: Allow overridden `get_object()` to work correctly.
+
+### 2.2.6
+
+**Date**: 4th April 2013
+
+* OAuth2 authentication no longer requires unneccessary URL parameters in addition to the token.
+* URL hyperlinking in browsable API now handles more cases correctly.
+* Long HTTP headers in browsable API are broken in multiple lines when possible.
+* Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views.
+* Bugfix: OAuth should fail hard when invalid token used.
+* Bugfix: Fix serializer potentially returning `None` object for models that define `__bool__` or `__len__`.
+
+### 2.2.5
+
+**Date**: 26th March 2013
+
+* Serializer support for bulk create and bulk update operations.
+* Regression fix: Date and time fields return date/time objects by default. Fixes regressions caused by 2.2.2. See [#743][743] for more details.
+* Bugfix: Fix 500 error is OAuth not attempted with OAuthAuthentication class installed.
+* `Serializer.save()` now supports arbitrary keyword args which are passed through to the object `.save()` method. Mixins use `force_insert` and `force_update` where appropriate, resulting in one less database query.
+
+### 2.2.4
+
+**Date**: 13th March 2013
+
+* OAuth 2 support.
+* OAuth 1.0a support.
+* Support X-HTTP-Method-Override header.
+* Filtering backends are now applied to the querysets for object lookups as well as lists. (Eg you can use a filtering backend to control which objects should 404)
+* Deal with error data nicely when deserializing lists of objects.
+* Extra override hook to configure `DjangoModelPermissions` for unauthenticated users.
+* Bugfix: Fix regression which caused extra database query on paginated list views.
+* Bugfix: Fix pk relationship bug for some types of 1-to-1 relations.
+* Bugfix: Workaround for Django bug causing case where `Authtoken` could be registered for cascade delete from `User` even if not installed.
+
+### 2.2.3
+
+**Date**: 7th March 2013
+
+* Bugfix: Fix None values for for `DateField`, `DateTimeField` and `TimeField`.
+
+### 2.2.2
+
+**Date**: 6th March 2013
+
+* Support for custom input and output formats for `DateField`, `DateTimeField` and `TimeField`.
+* Cleanup: Request authentication is no longer lazily evaluated, instead authentication is always run, which results in more consistent, obvious behavior. Eg. Supplying bad auth credentials will now always return an error response, even if no permissions are set on the view.
+* Bugfix for serializer data being uncacheable with pickle protocol 0.
+* Bugfixes for model field validation edge-cases.
+* Bugfix for authtoken migration while using a custom user model and south.
+
+### 2.2.1
+
+**Date**: 22nd Feb 2013
+
+* Security fix: Use `defusedxml` package to address XML parsing vulnerabilities.
+* Raw data tab added to browsable API. (Eg. Allow for JSON input.)
+* Added TimeField.
+* Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults.
+* Unicode support for view names/descriptions in browsable API.
+* Bugfix: request.DATA should return an empty `QueryDict` with no data, not `None`.
+* Bugfix: Remove unneeded field validation, which caused extra queries.
+
+**Security note**: Following the [disclosure of security vulnerabilities][defusedxml-announce] in Python's XML parsing libraries, use of the `XMLParser` class now requires the `defusedxml` package to be installed.
+
+The security vulnerabilities only affect APIs which use the `XMLParser` class, by enabling it in any views, or by having it set in the `DEFAULT_PARSER_CLASSES` setting. Note that the `XMLParser` class is not enabled by default, so this change should affect a minority of users.
+
+### 2.2.0
+
+**Date**: 13th Feb 2013
+
+* Python 3 support.
+* Added a `post_save()` hook to the generic views.
+* Allow serializers to handle dicts as well as objects.
+* Deprecate `ManyRelatedField()` syntax in favor of `RelatedField(many=True)`
+* Deprecate `null=True` on relations in favor of `required=False`.
+* Deprecate `blank=True` on CharFields, just use `required=False`.
+* Deprecate optional `obj` argument in permissions checks in favor of `has_object_permission`.
+* Deprecate implicit hyperlinked relations behavior.
+* Bugfix: Fix broken DjangoModelPermissions.
+* Bugfix: Allow serializer output to be cached.
+* Bugfix: Fix styling on browsable API login.
+* Bugfix: Fix issue with deserializing empty to-many relations.
+* Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom `.restore_object()` method.
+
+**Note**: See the [2.2 announcement][2.2-announcement] for full details.
+
+---
+
+## 2.1.x series
+
+### 2.1.17
+
+**Date**: 26th Jan 2013
+
+* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
+* Support json encoding of timedelta objects.
+* `format_suffix_patterns()` now supports `include` style URL patterns.
+* Bugfix: Fix issues with custom pagination serializers.
+* Bugfix: Nested serializers now accept `source='*'` argument.
+* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
+* Bugfix: Support nullable FKs with `SlugRelatedField`.
+* Bugfix: Don't call custom validation methods if the field has an error.
+
+**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
+
+### 2.1.16
+
+**Date**: 14th Jan 2013
+
+* Deprecate `django.utils.simplejson` in favor of Python 2.6's built-in json module.
+* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only.
+* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`.
+* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.
+* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
+* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
+
+**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
+
+### 2.1.15
+
+**Date**: 3rd Jan 2013
+
+* Added `PATCH` support.
+* Added `RetrieveUpdateAPIView`.
+* Remove unused internal `save_m2m` flag on `ModelSerializer.save()`.
+* Tweak behavior of hyperlinked fields with an explicit format suffix.
+* Relation changes are now persisted in `.save()` instead of in `.restore_object()`.
+* Bugfix: Fix issue with FileField raising exception instead of validation error when files=None.
+* Bugfix: Partial updates should not set default values if field is not included.
+
+### 2.1.14
+
+**Date**: 31st Dec 2012
+
+* Bugfix: ModelSerializers now include reverse FK fields on creation.
+* Bugfix: Model fields with `blank=True` are now `required=False` by default.
+* Bugfix: Nested serializers now support nullable relationships.
+
+**Note**: From 2.1.14 onwards, relational fields move out of the `fields.py` module and into the new `relations.py` module, in order to separate them from regular data type fields, such as `CharField` and `IntegerField`.
+
+This change will not affect user code, so long as it's following the recommended import style of `from rest_framework import serializers` and referring to fields using the style `serializers.PrimaryKeyRelatedField`.
+
+
+### 2.1.13
+
+**Date**: 28th Dec 2012
+
+* Support configurable `STATICFILES_STORAGE` storage.
* Bugfix: Related fields now respect the required flag, and may be required=False.
### 2.1.12
@@ -15,14 +250,14 @@
**Date**: 21st Dec 2012
* Bugfix: Fix bug that could occur using ChoiceField.
-* Bugfix: Fix exception in browseable API on DELETE.
+* Bugfix: Fix exception in browsable API on DELETE.
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
### 2.1.11
**Date**: 17th Dec 2012
-* Bugfix: Fix issue with M2M fields in browseable API.
+* Bugfix: Fix issue with M2M fields in browsable API.
### 2.1.10
@@ -105,7 +340,7 @@
* Support use of HTML exception templates. Eg. `403.html`
* Hyperlinked fields take optional `slug_field`, `slug_url_kwarg` and `pk_url_kwarg` arguments.
-* Bugfix: Deal with optional trailing slashs properly when generating breadcrumbs.
+* Bugfix: Deal with optional trailing slashes properly when generating breadcrumbs.
* Bugfix: Make textareas same width as other fields in browsable API.
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
@@ -113,16 +348,16 @@
**Date**: 5th Nov 2012
-**Warning**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0.
-
* **Serializer `instance` and `data` keyword args have their position swapped.**
* `queryset` argument is now optional on writable model fields.
* Hyperlinked related fields optionally take `slug_field` and `slug_url_kwarg` arguments.
* Support Django's cache framework.
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
-* Bugfix: Support choice field in Browseable API.
+* Bugfix: Support choice field in Browsable API.
* Bugfix: Related fields with `read_only=True` do not require a `queryset` argument.
+**API-incompatible changes**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0.
+
---
## 2.0.x series
@@ -159,9 +394,9 @@
* Allow views to specify template used by TemplateRenderer
* More consistent error responses
* Some serializer fixes
-* Fix internet explorer ajax behaviour
+* Fix internet explorer ajax behavior
* Minor xml and yaml fixes
-* Improve setup (eg use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
+* Improve setup (e.g. use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
* Sensible absolute URL generation, not using hacky set_script_prefix
---
@@ -172,13 +407,13 @@
* Added DjangoModelPermissions class to support `django.contrib.auth` style permissions.
* Use `staticfiles` for css files.
- - Easier to override. Won't conflict with customised admin styles (eg grappelli)
+ - Easier to override. Won't conflict with customized admin styles (e.g. grappelli)
* Templates are now nicely namespaced.
- Allows easier overriding.
* Drop implied 'pk' filter if last arg in urlconf is unnamed.
- - Too magical. Explict is better than implicit.
-* Saner template variable autoescaping.
-* Tider setup.py
+ - Too magical. Explicit is better than implicit.
+* Saner template variable auto-escaping.
+* Tidier setup.py
* Updated for URLObject 2.0
* Bugfixes:
- Bug with PerUserThrottling when user contains unicode chars.
@@ -266,5 +501,14 @@
* Initial release.
[cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html
+[deprecation-policy]: #deprecation-policy
+[django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
+[defusedxml-announce]: http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html
+[2.2-announcement]: 2.2-announcement.md
+[2.3-announcement]: 2.3-announcement.md
+[743]: https://github.com/tomchristie/django-rest-framework/pull/743
+[staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag
+[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
[announcement]: rest-framework-2-announcement.md
+[#582]: https://github.com/tomchristie/django-rest-framework/issues/582
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index 885d1918..309548d0 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -62,19 +62,19 @@ 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.
-## The Browseable API
+## The Browsable 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.
-Browseable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
+Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
-With REST framework 2, the browseable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
+With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
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]
+![Browsable API][image]
-**Image above**: An example of the browseable API in REST framework 2
+**Image above**: An example of the browsable API in REST framework 2
## Documentation
diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md
index 10ab9dfe..43e5a8c6 100644
--- a/docs/topics/rest-hypermedia-hateoas.md
+++ b/docs/topics/rest-hypermedia-hateoas.md
@@ -26,7 +26,7 @@ REST framework is an agnostic Web API toolkit. It does help guide you towards b
## What REST framework provides.
-It is self evident that REST framework makes it possible to build Hypermedia APIs. The browseable API that it offers is built on HTML - the hypermedia language of the web.
+It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
REST framework also includes [serialization] and [parser]/[renderer] components that make it easy to build appropriate media types, [hyperlinked relations][fields] for building well-connected systems, and great support for [content negotiation][conneg].
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index e61fb946..ed54a876 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -4,11 +4,11 @@
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. -->
+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.
---
-**Note**: The final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also a sandbox version for testing, [available here][sandbox].
+**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
---
@@ -60,7 +60,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
INSTALLED_APPS = (
...
'rest_framework',
- 'snippets'
+ 'snippets',
)
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
@@ -73,19 +73,20 @@ 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 `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` 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. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models
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()))
+
+ LEXERS = [item for item in get_all_lexers() if item[1]]
+ LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
+ STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
- title = models.CharField(max_length=100, default='')
+ title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
@@ -108,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets
from rest_framework import serializers
- from snippets import models
+ from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
@@ -118,26 +119,30 @@ The first thing we need to get started on our Web API is provide a way of serial
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
- language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES,
+ language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
- style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
+ style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
def restore_object(self, attrs, instance=None):
"""
- Create or update a new snippet instance.
+ Create or update a new snippet instance, given a dictionary
+ of deserialized field values.
+
+ Note that if we don't define this method, then deserializing
+ data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
- instance.title = attrs['title']
- instance.code = attrs['code']
- instance.linenos = attrs['linenos']
- instance.language = attrs['language']
- instance.style = attrs['style']
+ instance.title = attrs.get('title', instance.title)
+ instance.code = attrs.get('code', instance.code)
+ instance.linenos = attrs.get('linenos', instance.linenos)
+ instance.language = attrs.get('language', instance.language)
+ instance.style = attrs.get('style', instance.style)
return instance
# Create new instance
- return models.Snippet(**attrs)
+ return 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.
@@ -149,13 +154,16 @@ Before we go any further we'll familiarize ourselves with using our new Serializ
python manage.py shell
-Okay, once we've got a few imports out of the way, let's create a code snippet to work with.
+Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
+ snippet = Snippet(code='foo = "bar"\n')
+ snippet.save()
+
snippet = Snippet(code='print "hello, world"\n')
snippet.save()
@@ -163,13 +171,13 @@ We've now got a few snippet instances to play with. Let's take a look at serial
serializer = SnippetSerializer(snippet)
serializer.data
- # {'pk': 1, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
+ # {'pk': 2, '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 finalize the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data)
content
- # '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
+ # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into python native datatypes...
@@ -188,9 +196,15 @@ Deserialization is similar. First we parse a stream into python native datatype
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.
+We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments.
+
+ serializer = SnippetSerializer(Snippet.objects.all(), many=True)
+ serializer.data
+ # [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
+
## 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.
+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 our 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.
@@ -202,8 +216,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet
fields = ('id', '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.
@@ -229,7 +241,6 @@ Edit the `snippet/views.py` file, and add the following.
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 snippets, or creating a new snippet.
@csrf_exempt
@@ -239,7 +250,7 @@ The root of our API is going to be a view that supports listing all the existing
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
@@ -288,16 +299,45 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file:
urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail')
+ url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
)
It's worth noting that there are 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.
## Testing our first attempt at a Web API
-**TODO: Describe using runserver and making example requests from console**
+Now we can start up a sample server that serves our snippets.
+
+Quit out of the shell...
+
+ quit()
+
+...and start up Django's development server.
+
+ python manage.py runserver
+
+ Validating models...
+
+ 0 errors found
+ Django version 1.4.3, using settings 'tutorial.settings'
+ Development server is running at http://127.0.0.1:8000/
+ Quit the server with CONTROL-C.
+
+In another terminal window, we can test the server.
+
+We can get a list of all of the snippets.
+
+ curl http://127.0.0.1:8000/snippets/
+
+ [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
+
+Or we can get a particular snippet by referencing its id.
+
+ curl http://127.0.0.1:8000/snippets/2/
+
+ {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
-**TODO: Describe opening in a web browser and viewing json output**
+Similarly, you can have the same json displayed by visiting these URLs in a web browser.
## Where are we now
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index 08cf91cd..260c4d83 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -8,7 +8,7 @@ Let's introduce a couple of essential building blocks.
REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.DATA` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.
- request.DATA # Handles arbitrary data. Works any HTTP request with content.
+ request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
## Response objects
@@ -31,7 +31,6 @@ These wrappers provide a few bits of functionality such as making sure you recei
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
-
## Pulling it all together
Okay, let's go ahead and start using these new components to write a few views.
@@ -52,7 +51,7 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
@@ -63,7 +62,6 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
-
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.
Here is the view for an individual snippet.
@@ -77,11 +75,11 @@ Here is the view for an individual snippet.
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
-
+
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
-
+
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.DATA)
if serializer.is_valid():
@@ -117,7 +115,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail')
+ url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -128,16 +126,43 @@ We don't necessarily need to add these extra url patterns in, but it gives us a
Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
-**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
+We can get a list of all of the snippets, as before.
+
+ curl http://127.0.0.1:8000/snippets/
+
+ [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
+
+We can control the format of the response that we get back, either by using the `Accept` header:
+
+ curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json' # Request JSON
+ curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html' # Request HTML
+
+Or by appending a format suffix:
+
+ curl http://127.0.0.1:8000/snippets/.json # JSON suffix
+ curl http://127.0.0.1:8000/snippets/.api # Browsable API suffix
+
+Similarly, we can control the format of the request that we send, using the `Content-Type` header.
+
+ # POST using form data
+ curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
+
+ {"id": 3, "title": "", "code": "123", "linenos": false, "language": "python", "style": "friendly"}
+
+ # POST using JSON
+ curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
+
+ {"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
### Browsability
-Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans.
+Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
-See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
+Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
+See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it.
## What's next?
@@ -145,6 +170,6 @@ In [tutorial part 3][tut-3], we'll start using class based views, and see how ge
[json-url]: http://example.com/api/items/4.json
[devserver]: http://127.0.0.1:8000/snippets/
-[browseable-api]: ../topics/browsable-api.md
+[browsable-api]: ../topics/browsable-api.md
[tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index b115b022..70cf2c54 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -20,7 +20,7 @@ We'll start by rewriting the root view as a class based view. All this involves
"""
def get(self, request, format=None):
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
@@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
urlpatterns = patterns('',
url(r'^snippets/$', views.SnippetList.as_view()),
- url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view())
+ url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -92,8 +92,8 @@ Let's take a look at how we can compose our views by using the mixin classes.
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
- generics.MultipleObjectAPIView):
- model = Snippet
+ generics.GenericAPIView):
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
@@ -102,15 +102,15 @@ Let's take a look at how we can compose our views by using the mixin classes.
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
-We'll take a moment to examine exactly what's happening here. We're building our view using `MultipleObjectAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
+We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
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 SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
- generics.SingleObjectAPIView):
- model = Snippet
+ generics.GenericAPIView):
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
@@ -122,7 +122,7 @@ The base class provides the core functionality, and the mixin classes provide th
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
-Pretty similar. This time we're using the `SingleObjectAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
+Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
## Using generic class based views
@@ -134,12 +134,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than
class SnippetList(generics.ListCreateAPIView):
- model = Snippet
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
- model = Snippet
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 9576a7f0..f6c3efb0 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -22,14 +22,14 @@ We'd also need to make sure that when the model is saved, that we populate the h
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name
- from pygments.formatters import HtmlFormatter
+ from pygments.formatters.html 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
+ Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
@@ -54,8 +54,10 @@ You might also want to create a few different users, to use for testing the API.
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:
+ from django.contrib.auth.models import User
+
class UserSerializer(serializers.ModelSerializer):
- snippets = serializers.ManyPrimaryKeyRelatedField()
+ snippets = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = User
@@ -66,18 +68,18 @@ Because `'snippets'` is a *reverse* relationship on the User model, it will not
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
+ queryset = User.objects.all()
serializer_class = UserSerializer
- class UserInstance(generics.RetrieveAPIView):
- model = User
+ class UserDetail(generics.RetrieveAPIView):
+ queryset = User.objects.all()
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())
+ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
## Associating Snippets with Users
@@ -102,8 +104,6 @@ This field is doing something quite interesting. The `source` argument controls
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.
@@ -118,23 +118,21 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
-**TODO: Now that the permissions are restricted, demonstrate using HTTP basic authentication with curl requests**
+## Adding login to the Browsable API
-## Adding login to the Browseable API
+If you open a browser and navigate to the browsable API at the moment, you'll find that 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.
-If you open a browser and navigate to the browseable API at the moment, you'll find that 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.
+We can add a login view for use with the browsable 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.
+And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls',
- namespace='rest_framework'))
+ 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.
@@ -145,7 +143,7 @@ Once you've created a few code snippets, navigate to the '/users/' endpoint, and
## 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.
+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 to update or delete it.
To do that we're going to need to create a custom permission.
@@ -159,12 +157,9 @@ In the snippets app, create a new file, `permissions.py`
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
+ def has_object_permission(self, request, view, obj):
+ # Read permissions are allowed to any request,
+ # so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
@@ -182,10 +177,31 @@ Make sure to also import the `IsOwnerOrReadOnly` class.
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.
+## Authenticating with the API
+
+Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any [authentication classes][authentication], so the defaults are currently applied, which are `SessionAuthentication` and `BasicAuthentication`.
+
+When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
+
+If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
+
+If we try to create a snippet without authenticating, we'll get an error:
+
+ curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
+
+ {"detail": "Authentication credentials were not provided."}
+
+We can make a successful request by including the username and password of one of the users we created earlier.
+
+ curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password
+
+ {"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"}
+
## 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.
+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 highlighted 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 \ No newline at end of file
+[authentication]: ../api-guide/authentication.md
+[tut-5]: 5-relationships-and-hyperlinked-apis.md
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 216ca433..cb2e092c 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -1,4 +1,4 @@
-# Tutorial 5 - Relationships & Hyperlinked APIs
+# Tutorial 5: Relationships & Hyperlinked APIs
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.
@@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing
@api_view(('GET',))
def api_root(request, format=None):
return Response({
- 'users': reverse('user-list', request=request),
- 'snippets': reverse('snippet-list', request=request)
+ 'users': reverse('user-list', request=request, format=format),
+ 'snippets': reverse('snippet-list', request=request, format=format)
})
Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
@@ -34,8 +34,8 @@ Instead of using a concrete generic view, we'll use the base class for represent
from rest_framework import renderers
from rest_framework.response import Response
- class SnippetHighlight(generics.SingleObjectAPIView):
- model = Snippet
+ class SnippetHighlight(generics.GenericAPIView):
+ queryset = Snippet.objects.all()
renderer_classes = (renderers.StaticHTMLRenderer,)
def get(self, request, *args, **kwargs):
@@ -70,8 +70,8 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
* 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`.
+* Relationships use `HyperlinkedRelatedField`,
+ instead of `PrimaryKeyRelatedField`.
We can easily re-write our existing serializers to use hyperlinking.
@@ -86,7 +86,7 @@ We can easily re-write our existing serializers to use hyperlinking.
class UserSerializer(serializers.HyperlinkedModelSerializer):
- snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail')
+ snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
class Meta:
model = User
@@ -116,21 +116,21 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
- url(r'^snippets/(?P<pk>[0-9]+)/highlight/$'
+ 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(),
+ views.UserDetail.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'))
+ namespace='rest_framework')),
)
## Adding pagination
@@ -143,34 +143,16 @@ We can change the default list style to use pagination, by modifying our `settin
'PAGINATE_BY': 10
}
-Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well seperated from your other project settings.
+Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
-## Reviewing our work
+## Browsing the API
-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.
+If we open a browser and navigate to the browsable 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 highlighted 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.
+In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
-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 submitting 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 awesome things.**
-
-[repo]: https://github.com/tomchristie/rest-framework-tutorial
-[sandbox]: http://restframework.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 \ No newline at end of file
+[tut-6]: 6-viewsets-and-routers.md
diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md
new file mode 100644
index 00000000..277804e2
--- /dev/null
+++ b/docs/tutorial/6-viewsets-and-routers.md
@@ -0,0 +1,151 @@
+# Tutorial 6 - ViewSets & Routers
+
+REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
+
+`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.
+
+A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.
+
+## Refactoring to use ViewSets
+
+Let's take our current set of views, and refactor them into view sets.
+
+First of all let's refactor our `UserListView` and `UserDetailView` views into a single `UserViewSet`. We can remove the two views, and replace then with a single class:
+
+ class UserViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ This viewset automatically provides `list` and `detail` actions.
+ """
+ queryset = User.objects.all()
+ serializer_class = UserSerializer
+
+Here we've used `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
+
+Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
+
+ from rest_framework import viewsets
+ from rest_framework.decorators import link
+
+ class SnippetViewSet(viewsets.ModelViewSet):
+ """
+ This viewset automatically provides `list`, `create`, `retrieve`,
+ `update` and `destroy` actions.
+
+ Additionally we also provide an extra `highlight` action.
+ """
+ queryset = Snippet.objects.all()
+ serializer_class = SnippetSerializer
+ permission_classes = (permissions.IsAuthenticatedOrReadOnly,
+ IsOwnerOrReadOnly,)
+
+ @link(renderer_classes=[renderers.StaticHTMLRenderer])
+ def highlight(self, request, *args, **kwargs):
+ snippet = self.get_object()
+ return Response(snippet.highlighted)
+
+ def pre_save(self, obj):
+ obj.owner = self.request.user
+
+This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
+
+Notice that we've also used the `@link` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
+
+Custom actions which use the `@link` decorator will respond to `GET` requests. We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests.
+
+## Binding ViewSets to URLs explicitly
+
+The handler methods only get bound to the actions when we define the URLConf.
+To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
+
+In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views.
+
+ from snippets.resources import SnippetResource, UserResource
+
+ snippet_list = SnippetViewSet.as_view({
+ 'get': 'list',
+ 'post': 'create'
+ })
+ snippet_detail = SnippetViewSet.as_view({
+ 'get': 'retrieve',
+ 'put': 'update',
+ 'patch': 'partial_update',
+ 'delete': 'destroy'
+ })
+ snippet_highlight = SnippetViewSet.as_view({
+ 'get': 'highlight'
+ })
+ user_list = UserViewSet.as_view({
+ 'get': 'list'
+ })
+ user_detail = UserViewSet.as_view({
+ 'get': 'retrieve'
+ })
+
+Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
+
+Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual.
+
+ urlpatterns = format_suffix_patterns(patterns('snippets.views',
+ url(r'^$', 'api_root'),
+ url(r'^snippets/$', snippet_list, name='snippet-list'),
+ url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
+ url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
+ url(r'^users/$', user_list, name='user-list'),
+ url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
+ ))
+
+## Using Routers
+
+Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
+
+Here's our re-wired `urls.py` file.
+
+ from snippets import views
+ from rest_framework.routers import DefaultRouter
+
+ # Create a router and register our viewsets with it.
+ router = DefaultRouter()
+ router.register(r'snippets', views.SnippetViewSet)
+ router.register(r'users', views.UserViewSet)
+
+ # The API URLs are now determined automatically by the router.
+ # Additionally, we include the login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+ )
+
+Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
+
+The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
+
+## Trade-offs between views vs viewsets
+
+Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
+
+That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
+
+## Reviewing our work
+
+With an incredibly small amount of code, 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 submitting issues, and making pull requests.
+* Join the [REST framework discussion group][group], and help build the community.
+* Follow [the author][twitter] on Twitter and say hi.
+
+**Now go build awesome things.**
+
+
+[repo]: https://github.com/tomchristie/rest-framework-tutorial
+[sandbox]: http://restframework.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
diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md
index 74084541..52fe3acf 100644
--- a/docs/tutorial/quickstart.md
+++ b/docs/tutorial/quickstart.md
@@ -8,7 +8,7 @@ Create a new Django project, and start a new app called `quickstart`. Once you'
First up we're going to define some serializers in `quickstart/serializers.py` that we'll use for our data representations.
- from django.contrib.auth.models import User, Group, Permission
+ from django.contrib.auth.models import User, Group
from rest_framework import serializers
@@ -19,109 +19,64 @@ First up we're going to define some serializers in `quickstart/serializers.py` t
class GroupSerializer(serializers.HyperlinkedModelSerializer):
- permissions = serializers.ManySlugRelatedField(
- slug_field='codename',
- queryset=Permission.objects.all()
- )
-
class Meta:
model = Group
- fields = ('url', 'name', 'permissions')
+ fields = ('url', 'name')
Notice that we're using hyperlinked relations in this case, with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
-We've also overridden the `permission` field on the `GroupSerializer`. In this case we don't want to use a hyperlinked representation, but instead use the list of permission codenames associated with the group, so we've used a `ManySlugRelatedField`, using the `codename` field for the representation.
-
## Views
Right, we'd better write some views then. Open `quickstart/views.py` and get typing.
from django.contrib.auth.models import User, Group
- from rest_framework import generics
- from rest_framework.decorators import api_view
- from rest_framework.reverse import reverse
- from rest_framework.response import Response
+ from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer
- @api_view(['GET'])
- def api_root(request, format=None):
- """
- The entry endpoint of our API.
- """
- return Response({
- 'users': reverse('user-list', request=request),
- 'groups': reverse('group-list', request=request),
- })
-
-
- class UserList(generics.ListCreateAPIView):
- """
- API endpoint that represents a list of users.
- """
- model = User
- serializer_class = UserSerializer
-
-
- class UserDetail(generics.RetrieveUpdateDestroyAPIView):
+ class UserViewSet(viewsets.ModelViewSet):
"""
- API endpoint that represents a single user.
+ API endpoint that allows users to be viewed or edited.
"""
- model = User
+ queryset = User.objects.all()
serializer_class = UserSerializer
- class GroupList(generics.ListCreateAPIView):
+ class GroupViewSet(viewsets.ModelViewSet):
"""
- API endpoint that represents a list of groups.
+ API endpoint that allows groups to be viewed or edited.
"""
- model = Group
- serializer_class = GroupSerializer
-
-
- class GroupDetail(generics.RetrieveUpdateDestroyAPIView):
- """
- API endpoint that represents a single group.
- """
- model = Group
+ queryset = Group.objects.all()
serializer_class = GroupSerializer
-Let's take a moment to look at what we've done here before we move on. We have one function-based view representing the root of the API, and four class-based views which map to our database models, and specify which serializers should be used for representing that data. Pretty simple stuff.
+Rather that write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
+
+We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
## URLs
-Okay, let's wire this baby up. On to `quickstart/urls.py`...
+Okay, now let's wire up the API URLs. On to `quickstart/urls.py`...
from django.conf.urls import patterns, url, include
- from rest_framework.urlpatterns import format_suffix_patterns
- from quickstart.views import UserList, UserDetail, GroupList, GroupDetail
-
-
- urlpatterns = patterns('quickstart.views',
- url(r'^$', 'api_root'),
- url(r'^users/$', UserList.as_view(), name='user-list'),
- url(r'^users/(?P<pk>\d+)/$', UserDetail.as_view(), name='user-detail'),
- url(r'^groups/$', GroupList.as_view(), name='group-list'),
- url(r'^groups/(?P<pk>\d+)/$', GroupDetail.as_view(), name='group-detail'),
- )
-
-
- # Format suffixes
- urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
+ from rest_framework import routers
+ from quickstart import views
+ router = routers.DefaultRouter()
+ router.register(r'users', views.UserViewSet)
+ router.register(r'groups', views.GroupViewSet)
- # Default login/logout views
- urlpatterns += patterns('',
+ # Wire up our API using automatic URL routing.
+ # Additionally, we include login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
-There's a few things worth noting here.
-
-Firstly the names `user-detail` and `group-detail` are important. We're using the default hyperlinked relationships without explicitly specifying the view names, so we need to use names of the style `{modelname}-detail` to represent the model instance views.
+Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
-Secondly, we're modifying the urlpatterns using `format_suffix_patterns`, to append optional `.json` style suffixes to our URLs.
+Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.
-Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browseable API.
+Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
## Settings