diff --git a/.travis.yml b/.travis.yml index 0dc878373..662ea5c8b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,16 +3,30 @@ language: python python: - "2.6" - "2.7" + - "3.2" + - "3.3" env: - - DJANGO=https://github.com/django/django/zipball/master - - DJANGO=django==1.4.3 --use-mirrors - - DJANGO=django==1.3.5 --use-mirrors + - DJANGO=https://www.djangoproject.com/download/1.5c1/tarball/ + - DJANGO="django==1.4.3 --use-mirrors" + - DJANGO="django==1.3.5 --use-mirrors" install: - pip install $DJANGO - - pip install django-filter==0.5.4 --use-mirrors + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-filter==0.5.4 --use-mirrors; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} == '3' ]]; then pip install https://github.com/alex/django-filter/tarball/master; fi" - export PYTHONPATH=. script: - python rest_framework/runtests/runtests.py + +matrix: + exclude: + - python: "3.2" + env: DJANGO="django==1.4.3 --use-mirrors" + - python: "3.2" + env: DJANGO="django==1.3.5 --use-mirrors" + - python: "3.3" + env: DJANGO="django==1.4.3 --use-mirrors" + - python: "3.3" + env: DJANGO="django==1.3.5 --use-mirrors" diff --git a/README.md b/README.md index d7cc1c6d6..62131ac68 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,6 @@ **Full documentation for REST framework is available on [http://django-rest-framework.org][docs].** -Note that this is 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. - --- # Overview @@ -28,7 +26,7 @@ There is also a sandbox API you can use for testing purposes, [available here][s # Requirements -* Python (2.6, 2.7) +* Python (2.6, 2.7, 3.2, 3.3) * Django (1.3, 1.4, 1.5) **Optional:** @@ -81,6 +79,21 @@ To run the tests. # Changelog +### 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 @@ -131,20 +144,20 @@ This change will not affect user code, so long as it's following the recommended * Bugfix: Fix exception in browseable API on DELETE. * Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg. -## 2.1.11 +### 2.1.11 **Date**: 17th Dec 2012 * Bugfix: Fix issue with M2M fields in browseable API. -## 2.1.10 +### 2.1.10 **Date**: 17th Dec 2012 * Bugfix: Ensure read-only fields don't have model validation applied. * Bugfix: Fix hyperlinked fields in paginated results. -## 2.1.9 +### 2.1.9 **Date**: 11th Dec 2012 @@ -152,14 +165,14 @@ This change will not affect user code, so long as it's following the recommended * Bugfix: Fix `Meta.fields` only working as tuple not as list. * Bugfix: Edge case if unnecessarily specifying `required=False` on read only field. -## 2.1.8 +### 2.1.8 **Date**: 8th Dec 2012 * Fix for creating nullable Foreign Keys with `''` as well as `None`. * Added `null=` related field option. -## 2.1.7 +### 2.1.7 **Date**: 7th Dec 2012 @@ -171,19 +184,19 @@ This change will not affect user code, so long as it's following the recommended * Make `Request.user` settable. * Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer` -## 2.1.6 +### 2.1.6 **Date**: 23rd Nov 2012 * Bugfix: Unfix DjangoModelPermissions. (I am a doofus.) -## 2.1.5 +### 2.1.5 **Date**: 23rd Nov 2012 * Bugfix: Fix DjangoModelPermissions. -## 2.1.4 +### 2.1.4 **Date**: 22nd Nov 2012 @@ -194,7 +207,7 @@ This change will not affect user code, so long as it's following the recommended * Added `obtain_token_view` to get tokens when using `TokenAuthentication`. * Bugfix: Django 1.5 configurable user support for `TokenAuthentication`. -## 2.1.3 +### 2.1.3 **Date**: 16th Nov 2012 @@ -205,14 +218,14 @@ This change will not affect user code, so long as it's following the recommended * 201 Responses now return a 'Location' header. * Bugfix: Serializer fields now respect `max_length`. -## 2.1.2 +### 2.1.2 **Date**: 9th Nov 2012 * **Filtering support.** * Bugfix: Support creation of objects with reverse M2M relations. -## 2.1.1 +### 2.1.1 **Date**: 7th Nov 2012 @@ -222,7 +235,7 @@ This change will not affect user code, so long as it's following the recommended * Bugfix: Make textareas same width as other fields in browsable API. * Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization. -## 2.1.0 +### 2.1.0 **Date**: 5th Nov 2012 @@ -235,13 +248,13 @@ This change will not affect user code, so long as it's following the recommended * Minor field improvements. (Don't stringify dicts, more robust many-pk fields.) * Bugfixes (Support choice field in Browseable API) -## 2.0.2 +### 2.0.2 **Date**: 2nd Nov 2012 * Fix issues with pk related fields in the browsable API. -## 2.0.1 +### 2.0.1 **Date**: 1st Nov 2012 @@ -249,12 +262,12 @@ This change will not affect user code, so long as it's following the recommended * Added SlugRelatedField and ManySlugRelatedField. * If PUT creates an instance return '201 Created', instead of '200 OK'. -## 2.0.0 +### 2.0.0 **Date**: 30th Oct 2012 * Redesign of core components. -* Fix **all of the things**. +* **Fix all of the things**. # License diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index afd9a2619..9c899f17c 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,16 @@ 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 +169,67 @@ 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`. -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. # 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 `.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 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) + +--- + +# 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 +[juanriaza]: https://github.com/juanriaza +[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index ba57fde87..8b3e50f1e 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 5bc8f7f7c..3f8a36e2a 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. @@ -230,7 +240,9 @@ 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 diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 693e210d6..20f1be63a 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 71253afb0..51c0fb4bd 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 de9685578..0cd016391 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 fce68f6db..1814b8110 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 351b5e09e..c5da084b5 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -12,92 +12,159 @@ 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.`. +**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.`. --- -## RelatedField +# API Reference -This field can be applied to any of the following: +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. -* A `ForeignKey` field. -* A `OneToOneField` field. -* A reverse OneToOne relationship -* Any other "to-one" relationship. + class Album(models.Model): + album_name = models.CharField(max_length=100) + artist = models.CharField(max_length=100) -By default `RelatedField` will represent the target of the field using it's `__unicode__` method. - -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. - -By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method. - -For example, given the following models: - - class TaggedItem(models.Model): - """ - Tags arbitrary model instances using a generic relation. - - 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) - -And a model serializer defined like this: - - class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.ManyRelatedField(source='tags') + class Track(models.Model): + album = models.ForeignKey(Album, related_name='tracks') + order = models.IntegerField() + title = models.CharField(max_length=100) + duration = models.IntegerField() class Meta: - model = Bookmark - exclude = ('id',) + unique_together = ('album', 'order') + + def __unicode__(self): + return '%d: %s' % (self.order, self.title) -Then an example output format for a Bookmark instance would be: +## RelatedField + +`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method. + +For example, the following serializer. + + class AlbumSerializer(serializer.ModelSerializer): + tracks = RelatedField(many=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +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', + ... + ] } +This field is read only. + ## PrimaryKeyRelatedField -## ManyPrimaryKeyRelatedField -`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key. +`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. -By default these fields are read-write, although you can change this behavior using the `read_only` flag. +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = PrimaryKeyRelatedField(many=True, read_only=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'The Roots', + 'artist': 'Undun' + 'tracks': [ + 89, + 90, + 91, + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. **Arguments**: * `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. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. + +## HyperlinkedRelatedField + +`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. + +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = HyperlinkedRelatedField(many=True, read_only=True, + view_name='track-detail') + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Graceland', + 'artist': 'Paul Simon' + 'tracks': [ + 'http://www.example.com/api/tracks/45', + 'http://www.example.com/api/tracks/46', + 'http://www.example.com/api/tracks/47', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +**Arguments**: + +* `view_name` - The view name that should be used as the target of the relationship. **required**. +* `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`. +* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ## SlugRelatedField -## ManySlugRelatedField -`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug. +`SlugRelatedField` may be used to represent the target of the relationship using a field on the target. -By default these fields read-write, although you can change this behavior using the `read_only` flag. +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Dear John', + 'artist': 'Loney Dear' + 'tracks': [ + 'Airport Surroundings', + 'Everything Turns to You', + 'I Was Only Going Out', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`. **Arguments**: @@ -105,35 +172,183 @@ By default these fields read-write, although you can change this behavior using * `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. - -By default, `HyperlinkedRelatedField` 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. -* `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. - ## HyperLinkedIdentityField -This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. +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. For example: + + class TrackSerializer(serializer.ModelSerializer): + class Meta: + fields = ('order', 'title') + + class AlbumSerializer(serializer.ModelSerializer): + tracks = TrackSerializer(many=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. + +## 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. + + class TrackListingField(serializers.RelatedField): + def to_native(self, value): + return 'Track %d: %s' % (value.ordering, value.name) + +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. + +# 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(serializer.ModelSerializer): + class Meta: + fields = ('tracks', ...) + +Instead, you must explicitly add it to the serializer. For example: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = serializers.PrimaryKeyRelationship(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(serializer.ModelSerializer): + tracks = serializers.PrimaryKeyRelationship(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 relational fields + +The following classes have been deprecated, in favor of the `many=` syntax. +They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default. +In the 2.3 release, this warning will be escalated to a `DeprecationWarning`. +In the 2.4 release, they will be removed entirely. + +* `ManyRelatedField` +* `ManyPrimaryKeyRelatedField` +* `ManyHyperlinkedRelatedField` +* `ManySlugRelatedField` [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 diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index b4f7ec3d4..4c1fdc53b 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/requests.md b/docs/api-guide/requests.md index 72932f5d6..39a34fcfb 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 d98a602f7..487502e9a 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -190,18 +190,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. + Serialize the object's class name. """ - 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. - """ - pass + return obj.__class__ --- diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index b03bc9e04..923593bcc 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/api-guide/views.md b/docs/api-guide/views.md index d1e42ec1c..574020f9b 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -85,7 +85,7 @@ The following methods are called before dispatching to the handler method. ## 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 57446ff98..07c4884d1 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 497f19004..37e7cb3cf 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,16 +1,16 @@ - -[![Travis build image][travis-build-image]][travis] +

+ + + + + +Travis build image +

# Django REST framework **A toolkit for building well-connected, self-describing Web APIs.** ---- - -**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 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. 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. @@ -27,7 +27,7 @@ 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, 2.7, 3.2, 3.3) * Django (1.3, 1.4, 1.5) The following packages are optional: @@ -111,6 +111,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 +133,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 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. + + + + ## License Copyright (c) 2011-2013, Tom Christie @@ -199,7 +205,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 +215,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 d789cc582..2a87e92ba 100644 --- a/docs/template.html +++ b/docs/template.html @@ -89,6 +89,7 @@