aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
authorTom Christie2013-03-18 21:03:05 +0000
committerTom Christie2013-03-18 21:03:05 +0000
commit74fb366c595db87bb71baeffcacfb7d2482e3a18 (patch)
tree2e28cb52542742f32cdd3fbeb625f7f59cba0a3f /docs
parent4c6396108704d38f534a16577de59178b1d0df3b (diff)
parent034c4ce4081dd6d15ea47fb8318754321a3faf0c (diff)
downloaddjango-rest-framework-74fb366c595db87bb71baeffcacfb7d2482e3a18.tar.bz2
Merge branch 'master' into resources-routers
Diffstat (limited to 'docs')
-rw-r--r--docs/api-guide/authentication.md242
-rw-r--r--docs/api-guide/exceptions.md19
-rw-r--r--docs/api-guide/fields.md55
-rw-r--r--docs/api-guide/filtering.md8
-rw-r--r--docs/api-guide/format-suffixes.md21
-rw-r--r--docs/api-guide/generic-views.md9
-rw-r--r--docs/api-guide/pagination.md6
-rw-r--r--docs/api-guide/parsers.md15
-rw-r--r--docs/api-guide/permissions.md84
-rw-r--r--docs/api-guide/relations.md422
-rw-r--r--docs/api-guide/renderers.md13
-rw-r--r--docs/api-guide/requests.md4
-rw-r--r--docs/api-guide/serializers.md74
-rw-r--r--docs/api-guide/settings.md124
-rw-r--r--docs/api-guide/throttling.md19
-rw-r--r--docs/api-guide/views.md8
-rw-r--r--docs/css/default.css17
-rw-r--r--docs/index.md62
-rw-r--r--docs/template.html8
-rw-r--r--docs/topics/2.2-announcement.md159
-rw-r--r--docs/topics/ajax-csrf-cors.md41
-rw-r--r--docs/topics/browsable-api.md7
-rw-r--r--docs/topics/browser-enhancements.md16
-rw-r--r--docs/topics/credits.md51
-rw-r--r--docs/topics/csrf.md12
-rw-r--r--docs/topics/release-notes.md124
-rw-r--r--docs/tutorial/1-serialization.md63
-rw-r--r--docs/tutorial/2-requests-and-responses.md38
-rw-r--r--docs/tutorial/3-class-based-views.md2
-rw-r--r--docs/tutorial/4-authentication-and-permissions.md48
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md12
31 files changed, 1511 insertions, 272 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index afd9a261..541c6575 100644
--- 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,7 @@ 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 basis, using the `APIView` class based views.
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
@@ -60,24 +68,57 @@ 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`.
+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` 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.
## 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'
+ )
You'll also need to create tokens for your users.
@@ -93,10 +134,20 @@ 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
+
+---
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
+---
+
+#### Generating Tokens
+
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@receiver(post_save, sender=User)
@@ -112,8 +163,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,24 +175,186 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
+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.
+
+#### Custom user models
+
+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.
+
+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`.
-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`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
+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` only.
+
+---
+
+#### 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/?client_id=YOUR_CLIENT_ID\&client_secret=YOUR_CLIENT_SECRET
+
+---
# 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 5bc8f7f7..9a745cf1 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,7 +2,7 @@
# Serializer fields
-> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it -- normalizing it to a consistent format.
+> 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; [Django documentation][cite]
@@ -102,7 +102,7 @@ You can customize this behavior by overriding the `.to_native(self, value)` met
## 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
@@ -181,17 +181,56 @@ 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
+
+**Signature:** `DateTimeField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, the `DATETIME_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `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.000000'`)
+
## 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, the `DATE_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `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, the `TIME_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `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
@@ -230,7 +269,11 @@ Signature and validation is the same as with `FileField`.
---
**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.
+Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
+
+---
[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
+[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..ed946368 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -140,6 +140,14 @@ For more details on using filter sets see the [django-filter documentation][djan
---
+### Filtering and object lookups
+
+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:
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 693e210d..20f1be63 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -131,6 +131,15 @@ Each of the generic views provided is built by combining one of the base views b
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
+**Methods**:
+
+* `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_class(self)` - Returns the class that should be used for the serializer.
+* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance.
+* `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.
+
+
**Attributes**:
* `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.
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 71253afb..13d4760a 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.
@@ -114,8 +114,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 de968557..a2830492 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.
@@ -59,6 +69,8 @@ Parses `JSON` request content.
Parses `YAML` request content.
+Requires the `pyyaml` package to be installed.
+
**.media_type**: `application/yaml`
## XMLParser
@@ -69,6 +81,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
@@ -169,6 +183,7 @@ The following third party packages are also available.
[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
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index fce68f6d..4772c5e0 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -90,29 +90,105 @@ 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.
+If you want to use `DjangoModelPermissions` but also allow unauthenticated users to have read permission, override the class and set the `authenticated_users_only` property to `False`. For example:
+
+ class HasModelPermissionsOrReadOnly(DjangoModelPermissions):
+ authenticated_users_only = False
+
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.
+## 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
index 351b5e09..623fe1a9 100644
--- a/docs/api-guide/relations.md
+++ b/docs/api-guide/relations.md
@@ -12,128 +12,408 @@ Relational fields are used to represent model relationships. They can be applie
---
-**Note:** The relational fields are declared in `relations.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
+**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>`.
---
-## 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.
+# API Reference
-By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+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.
-You can customize this behavior by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
-
-## ManyRelatedField
-
-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.
+ class Album(models.Model):
+ album_name = models.CharField(max_length=100)
+ artist = models.CharField(max_length=100)
-By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+ class Track(models.Model):
+ album = models.ForeignKey(Album, related_name='tracks')
+ order = models.IntegerField()
+ title = models.CharField(max_length=100)
+ duration = models.IntegerField()
-For example, given the following models:
-
- class TaggedItem(models.Model):
- """
- Tags arbitrary model instances using a generic relation.
+ class Meta:
+ unique_together = ('album', 'order')
+ order_by = 'order'
- See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
- """
- 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):
- """
- A bookmark consists of a URL, and 0 or more descriptive tags.
- """
- url = models.URLField()
- tags = GenericRelation(TaggedItem)
+ return '%d: %s' % (self.order, self.title)
-And a model serializer defined like this:
+## RelatedField
- class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
+`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 = Bookmark
- exclude = ('id',)
+ model = Album
+ fields = ('album_name', 'artist', 'tracks')
-Then an example output format for a Bookmark instance would be:
+Would serialize to the following representation.
{
- 'tags': [u'django', u'python'],
- 'url': u'https://www.djangoproject.com/'
+ 'album_name': 'Things We Lost In The Fire',
+ 'artist': 'Low'
+ 'tracks': [
+ '1: Sunflower',
+ '2: Whitetail',
+ '3: Dinosaur Act',
+ ...
+ ]
}
-## PrimaryKeyRelatedField
-## ManyPrimaryKeyRelatedField
+This field is read only.
-`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
+**Arguments**:
-By default these fields are read-write, although you can change this behavior using the `read_only` flag.
+* `many` - If applied to a to-many relationship, you should set this argument to `True`.
-**Arguments**:
+## PrimaryKeyRelatedField
-* `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 empty-string for nullable relationships.
+`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key.
-## SlugRelatedField
-## ManySlugRelatedField
+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')
-`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
+Would serialize to a representation like this:
-By default these fields read-write, although you can change this behavior using the `read_only` flag.
+ {
+ '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**:
-* `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`.
+* `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`.
-* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
## HyperlinkedRelatedField
-## ManyHyperlinkedRelatedField
-`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
+`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, `HyperlinkedRelatedField` is read-write, although you can change this behavior using the `read_only` flag.
+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**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `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`.
* `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 empty-string for nullable relationships.
+* `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`.
-## HyperLinkedIdentityField
+**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`.
-This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
+## 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**.
-* `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`.
+* `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 generated by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you cannot simply add it to the fields list.
+
+**The following will not work:**
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ class Meta:
+ fields = ('tracks', ...)
+
+Instead, you must explicitly add it to the serializer. For example:
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = serializers.PrimaryKeyRelatedField(many=True)
+ ...
+
+By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work.
+
+The best way to ensure this is typically to make sure that the relationship on the model definition has it's `related_name` argument properly set. For example:
+
+ class Track(models.Model):
+ album = models.ForeignKey(Album, related_name='tracks')
+ ...
+
+Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example.
+
+ class AlbumSerializer(serializers.ModelSerializer):
+ tracks = serializers.PrimaryKeyRelatedField(many=True, source='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].
+
+---
+
+## 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 b4f7ec3d..3c8396aa 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -80,7 +80,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 +90,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,13 +117,13 @@ 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.
"""
@@ -288,7 +290,8 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[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/
@@ -298,4 +301,4 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[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 \ No newline at end of file
+[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/serializers.md b/docs/api-guide/serializers.md
index d98a602f..42edf9af 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -25,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):
@@ -33,10 +34,17 @@ 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.
+
+ Note that if we don't define this method, then deserializing
+ data will simply return a dictionary of items.
+ """
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)
@@ -80,9 +88,21 @@ By default, serializers must be passed values for all required fields or they wi
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data
+## Serializing querysets
+
+To serialize a queryset instead of an object instance, you should pass the `many=True` flag when instantiating the serializer.
+
+ queryset = Comment.objects.all()
+ serializer = CommentSerializer(queryset, many=True)
+ serializer.data
+ # [{'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}, {'email': u'jamie@example.com', 'content': u'baz', 'created': datetime.datetime(2013, 1, 12, 16, 12, 45, 104445)}]
+
## 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.
+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.
+
+When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
### Field-level validation
@@ -114,7 +134,7 @@ To do any other validation that requires access to multiple fields, add a method
from rest_framework import serializers
class EventSerializer(serializers.Serializer):
- description = serializers.CahrField(max_length=100)
+ description = serializers.CharField(max_length=100)
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
@@ -155,6 +175,17 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent
---
+## 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.
## Creating custom fields
@@ -190,18 +221,12 @@ By default field values are treated as mapping to an attribute on the object. I
As an example, let's create a field that can be used represent the class name of the object being serialized:
- class ClassNameField(serializers.WritableField):
+ class ClassNameField(serializers.Field):
def field_to_native(self, obj, field_name):
"""
- Serialize the object's class name, not an attribute of the object.
- """
- return obj.__class__.__name__
-
- def field_from_native(self, data, field_name, into):
- """
- We don't want to set anything when we revert this field.
+ Serialize the object's class name.
"""
- pass
+ return obj.__class__
---
@@ -214,15 +239,17 @@ 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 foreign keys on the model will be mapped to `PrimaryKeyRelatedField` if you're using a `ModelSerializer`, or `HyperlinkedRelatedField` if you're using a `HyperlinkedModelSerializer`.
## 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
@@ -231,17 +258,11 @@ 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.
-
-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.
-
-The `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` fields provide alternative flat representations.
-
-The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations.
+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.
-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.
+Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
-All the relational fields may be used for any relationship or reverse relationship on a model.
+For full details see the [serializer relations][relations] documentation.
## Specifying which fields should be included
@@ -316,3 +337,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 a422e5f6..11638696 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.
@@ -68,7 +72,7 @@ Default:
'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,77 @@ 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'`
+
+---
-**TODO**
+## Generic view settings
-Default: `rest_framework.serializers.ModelSerializer`
+*The following settings control the behavior of the generic class based views.*
-## DEFAULT_PAGINATION_SERIALIZER_CLASS
+#### DEFAULT_MODEL_SERIALIZER_CLASS
-**TODO**
+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.
+
+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
+#### FILTER_BACKEND
The filter backend class 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_PARAM
+#### 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 +160,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 +168,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 +176,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,13 +184,61 @@ 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/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.
+
+Default: `'iso-8601'`
+
+#### DATETIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
+
+Default: `['iso-8601']`
+
+#### DATE_FORMAT
+
+A format string that should be used by default for rendering the output of `DateField` serializer fields.
+
+Default: `'iso-8601'`
+
+#### DATE_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
+
+Default: `['iso-8601']`
+
+#### TIME_FORMAT
+
+A format string that should be used by default for rendering the output of `TimeField` serializer fields.
+
+Default: `'iso-8601'`
+
+#### TIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
+
+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'`
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index b03bc9e0..1abd49f4 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.
@@ -63,6 +61,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 +152,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 \ No newline at end of file
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/css/default.css b/docs/css/default.css
index 57446ff9..c160b63d 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;
}
diff --git a/docs/index.md b/docs/index.md
index 497f1900..5357536d 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,19 +1,19 @@
-<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
----
+**Web APIs for Django, made easy.**
-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 flexible, powerful library that makes it incredibly easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
-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.
+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.
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcement][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
@@ -27,14 +27,19 @@ 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.
* [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
@@ -70,7 +75,7 @@ Note that the URL path can be whatever you want, but you must include `'rest_fra
## 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
@@ -111,10 +116,12 @@ 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]
* [Release Notes][release-notes]
* [Credits][credits]
@@ -130,12 +137,21 @@ 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 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.
+[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.
+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-2013, Tom Christie
@@ -166,7 +182,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML
+[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/
@@ -199,15 +219,23 @@ 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
[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 d789cc58..3e0f29aa 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">
@@ -89,10 +89,12 @@
<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/release-notes{{ suffix }}">Release Notes</a></li>
<li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>
</ul>
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/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..5f80c4f9 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.
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/credits.md b/docs/topics/credits.md
index b0b00c12..b533daa9 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -4,7 +4,7 @@ The following people have helped make REST framework great.
* 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]
@@ -91,6 +91,27 @@ The following people have helped make REST framework great.
* 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]
Many thanks to everyone who's contributed to the project.
@@ -114,7 +135,6 @@ 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/
@@ -130,7 +150,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
@@ -145,7 +165,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
@@ -217,3 +237,24 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[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
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/release-notes.md b/docs/topics/release-notes.md
index f43dc1d3..c45fff88 100644
--- a/docs/topics/release-notes.md
+++ b/docs/topics/release-notes.md
@@ -8,29 +8,140 @@
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 minor API changes. You should read the release notes carefully before upgrading between medium point releases.
+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 project milestones. No major point releases are currently planned.
+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.1.x series
+## 2.2.x series
### Master
+* `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 browseable 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 browseable 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.
+* 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
@@ -319,7 +430,12 @@ This change will not affect user code, so long as it's following the recommended
* 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
[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/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index d3ada9e3..205ee7e0 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 code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. As pieces of code are introduced, they are committed to this repository. The completed implementation is also online as 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].
---
@@ -86,7 +86,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
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,
@@ -109,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):
@@ -119,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.
@@ -150,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()
@@ -164,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...
@@ -189,6 +196,12 @@ 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.
@@ -237,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':
@@ -295,11 +308,11 @@ It's worth noting that there are a couple of edge cases we're not dealing with p
Now we can start up a sample server that serves our snippets.
-Quit out of the shell
+Quit out of the shell...
quit()
-and start up Django's development server
+...and start up Django's development server.
python manage.py runserver
@@ -312,19 +325,19 @@ and start up Django's development server
In another terminal window, we can test the server.
-We can get a list of all of the snippets (we only have one at the moment)
+We can get a list of all of the snippets.
curl http://127.0.0.1:8000/snippets/
- [{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
+ [{"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
+Or we can get a particular snippet by referencing its id.
- curl http://127.0.0.1:8000/snippets/1/
+ curl http://127.0.0.1:8000/snippets/2/
- {"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
+ {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
-Similarly, you can have the same json displayed by referencing these URLs from your favorite web browser.
+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 340ea28e..63cee3a6 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -51,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':
@@ -75,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():
@@ -126,13 +126,41 @@ 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 # Browseable 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.
+
+Having a web-browseable 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][browseable-api] topic for more information about the browsable API feature and how to customize it.
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index 290ea5e9..e05017c5 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):
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index f6daebb7..3ee755a2 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -22,7 +22,7 @@ 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:
@@ -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
@@ -70,14 +72,14 @@ We'll also add a couple of views. We'd like to just use read-only views for the
serializer_class = UserSerializer
- class UserInstance(generics.RetrieveAPIView):
+ class UserDetail(generics.RetrieveAPIView):
model = User
serializer_class = UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf.
url(r'^users/$', views.UserList.as_view()),
- url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()),
+ 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,8 +118,6 @@ 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 Browseable API
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.
@@ -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 havn'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 27898f7b..a702a09d 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -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
@@ -123,7 +123,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
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')
))
@@ -165,7 +165,7 @@ We've reached the end of our tutorial. If you want to get more involved in the
* 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.
+* Follow [the author][twitter] on Twitter and say hi.
**Now go build awesome things.**
@@ -173,4 +173,4 @@ We've reached the end of our tutorial. If you want to get more involved in the
[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
+[twitter]: https://twitter.com/_tomchristie