aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
authorMichael Elovskikh2013-01-28 16:26:16 +0600
committerMichael Elovskikh2013-01-28 16:26:16 +0600
commit499d6424aee5b71b8e6b2500bf14fa85321bfc26 (patch)
tree34f575fb078377208ded5251aea050668355d82a /docs
parent180c94dc44a9cc5b882364a58b0b12a8ab430c22 (diff)
parent3bcd38b7d0ddaa2c051ad230cb0d749f9737fd82 (diff)
downloaddjango-rest-framework-499d6424aee5b71b8e6b2500bf14fa85321bfc26.tar.bz2
Merge branch 'upstream_master' into docs_patch_method
Conflicts: docs/api-guide/authentication.md
Diffstat (limited to 'docs')
-rw-r--r--docs/api-guide/authentication.md97
-rw-r--r--docs/api-guide/exceptions.md19
-rw-r--r--docs/api-guide/fields.md10
-rw-r--r--docs/api-guide/pagination.md4
-rw-r--r--docs/api-guide/parsers.md11
-rw-r--r--docs/api-guide/permissions.md9
-rw-r--r--docs/api-guide/relations.md2
-rw-r--r--docs/api-guide/renderers.md5
-rw-r--r--docs/api-guide/throttling.md10
-rw-r--r--docs/css/default.css17
-rw-r--r--docs/index.md31
-rw-r--r--docs/template.html1
-rw-r--r--docs/topics/ajax-csrf-cors.md41
-rw-r--r--docs/topics/credits.md10
-rw-r--r--docs/topics/csrf.md12
-rw-r--r--docs/topics/release-notes.md22
-rw-r--r--docs/tutorial/1-serialization.md16
-rw-r--r--docs/tutorial/4-authentication-and-permissions.md9
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md2
19 files changed, 275 insertions, 53 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 2d34d788..da494746 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -8,7 +8,7 @@
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.
@@ -16,17 +16,25 @@ The `request.user` property will typically be set to an instance of the `contrib
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,52 @@ 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.
You'll also need to create tokens for your users.
@@ -93,10 +129,15 @@ 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.
+=======
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)
@@ -127,22 +168,56 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
## SessionAuthentication
-This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
+This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
If successfully authenticated, `SessionAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
+Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
+
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
# 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, without checking any other authentication schemes.
+
+You *may* also override the `.authentication_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 `.authentication_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 has_permission(self, request, view, obj=None):
+ 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)
+
[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
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..e43282ce 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -193,6 +193,16 @@ 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
+
## IntegerField
An integer representation.
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 71253afb..51c0fb4b 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -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..0cd01639 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.
@@ -169,6 +179,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..1814b811 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -110,6 +110,15 @@ To implement a custom permission, override `BasePermission` and implement the `.
The method should return `True` if the request should be granted access, and `False` otherwise.
+## Example
+
+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):
+ def has_permission(self, request, view, obj=None):
+ ip_addr = request.META['REMOTE_ADDR']
+ blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
+ return not blacklisted
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
index 351b5e09..9f5a04b2 100644
--- a/docs/api-guide/relations.md
+++ b/docs/api-guide/relations.md
@@ -67,7 +67,7 @@ For example, given the following models:
And a model serializer defined like this:
class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
+ tags = serializers.ManyRelatedField()
class Meta:
model = Bookmark
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index b4f7ec3d..4c1fdc53 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`
@@ -288,7 +288,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/
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index b03bc9e0..923593bc 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -150,8 +150,16 @@ 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
+
[permissions]: permissions.md
diff --git a/docs/css/default.css b/docs/css/default.css
index 57446ff9..07c4884d 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: -9px;
margin-bottom: 0px;
}
diff --git a/docs/index.md b/docs/index.md
index 497f1900..453a67b8 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,5 +1,11 @@
-<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>
+
+<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Current status: 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>
# Django REST framework
@@ -111,6 +117,7 @@ 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]
@@ -132,10 +139,15 @@ Run the tests:
## Support
-For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`.
+For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
+
+[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
-Paid support is also available from [DabApps], and can include work on REST framework core, or support with building your REST framework API. Please contact [Tom Christie][email] if you'd like to discuss commercial support options.
+For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
+<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
+<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
+
## License
Copyright (c) 2011-2013, Tom Christie
@@ -199,7 +211,7 @@ 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
@@ -209,5 +221,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[credits]: topics/credits.md
[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..2a87e92b 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -89,6 +89,7 @@
<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>
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/credits.md b/docs/topics/credits.md
index 68d07f20..19a6397c 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -92,6 +92,11 @@ The following people have helped make REST framework great.
* 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]
Many thanks to everyone who's contributed to the project.
@@ -219,3 +224,8 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[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
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 e00a5e93..84b30d85 100644
--- a/docs/topics/release-notes.md
+++ b/docs/topics/release-notes.md
@@ -12,14 +12,34 @@ Medium version numbers (0.x.0) may include minor API changes. You should read t
Major version numbers (x.0.0) are reserved for project milestones. No major point releases are currently planned.
+## 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
-### Master
+### 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
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index d3ada9e3..5f292211 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -4,7 +4,7 @@
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.
---
@@ -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
class SnippetSerializer(serializers.Serializer):
@@ -130,15 +130,15 @@ The first thing we need to get started on our Web API is provide a way of serial
"""
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.
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index f6daebb7..e9e5246a 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,6 +54,8 @@ 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()
@@ -164,7 +166,8 @@ In the snippets app, create a new file, `permissions.py`
if obj is None:
return True
- # Read permissions are allowed to any request
+ # 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
@@ -188,4 +191,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
-[tut-5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file
+[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..de856611 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -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.**