diff --git a/.travis.yml b/.travis.yml index 0dc878373..205feef92 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,16 +3,34 @@ 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="django==1.5 --use-mirrors" + - 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 + - pip install defusedxml==0.3 + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install oauth2==1.5.211 --use-mirrors; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth-plus==2.0 --use-mirrors; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth2-provider==0.2.3 --use-mirrors; fi" + - "if [[ ${DJANGO::11} == 'django==1.3' ]]; then pip install django-filter==0.5.4 --use-mirrors; fi" + - "if [[ ${DJANGO::11} != 'django==1.3' ]]; then pip install django-filter==0.6a1 --use-mirrors; 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/MANIFEST.in b/MANIFEST.in index 00e450866..15c4d0b08 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,2 @@ recursive-include rest_framework/static *.js *.css *.png -recursive-include rest_framework/templates *.txt *.html +recursive-include rest_framework/templates *.html diff --git a/README.md b/README.md index a70201661..c76db7ecc 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **Author:** Tom Christie. [Follow me on Twitter][twitter]. -**Support:** [REST framework discussion group][group]. +**Support:** [REST framework group][group], or `#restframework` on freenode IRC. [![build-status-image]][travis] @@ -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,14 +26,15 @@ There is also a sandbox API you can use for testing purposes, [available here][s # Requirements -* Python (2.6, 2.7) +* Python (2.6.5+, 2.7, 3.2, 3.3) * Django (1.3, 1.4, 1.5) **Optional:** -* [Markdown] - Markdown support for the self describing API. -* [PyYAML] - YAML content type support. -* [django-filter] - Filtering support. +* [Markdown][markdown] - Markdown support for the self describing API. +* [PyYAML][pyyaml] - YAML content type support. +* [defusedxml][defusedxml] - XML content-type support. +* [django-filter][django-filter] - Filtering support. # Installation @@ -44,6 +43,7 @@ Install using `pip`, including any optional packages you want... pip install djangorestframework pip install markdown # Markdown support for the browseable API. pip install pyyaml # YAML content-type support. + pip install defusedxml # XML content-type support. pip install django-filter # Filtering support ...or clone the project from github. @@ -79,182 +79,9 @@ To run the tests. ./rest_framework/runtests/runtests.py -# Changelog +To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`: -### 2.1.16 - -**Date**: 14th Jan 2013 - -* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. -* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only. -* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`. -* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. -* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. -* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one - -### 2.1.15 - -**Date**: 3rd Jan 2013 - -* Added `PATCH` support. -* Added `RetrieveUpdateAPIView`. -* Relation changes are now persisted in `.save` instead of in `.restore_object`. -* Remove unused internal `save_m2m` flag on `ModelSerializer.save()`. -* Tweak behavior of hyperlinked fields with an explicit format suffix. -* Bugfix: Fix issue with FileField raising exception instead of validation error when files=None. -* Bugfix: Partial updates should not set default values if field is not included. - -### 2.1.14 - -**Date**: 31st Dec 2012 - -* Bugfix: ModelSerializers now include reverse FK fields on creation. -* Bugfix: Model fields with `blank=True` are now `required=False` by default. -* Bugfix: Nested serializers now support nullable relationships. - -**Note**: From 2.1.14 onwards, relational fields move out of the `fields.py` module and into the new `relations.py` module, in order to seperate them from regular data type fields, such as `CharField` and `IntegerField`. - -This change will not affect user code, so long as it's following the recommended import style of `from rest_framework import serializers` and refering to fields using the style `serializers.PrimaryKeyRelatedField`. - -### 2.1.13 - -**Date**: 28th Dec 2012 - -* Support configurable `STATICFILES_STORAGE` storage. -* Bugfix: Related fields now respect the required flag, and may be required=False. - -### 2.1.12 - -**Date**: 21st Dec 2012 - -* Bugfix: Fix bug that could occur using ChoiceField. -* 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 - -**Date**: 17th Dec 2012 - -* Bugfix: Fix issue with M2M fields in browseable API. - -## 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 - -**Date**: 11th Dec 2012 - -* Bugfix: Fix broken nested serialization. -* 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 - -**Date**: 8th Dec 2012 - -* Fix for creating nullable Foreign Keys with `''` as well as `None`. -* Added `null=` related field option. - -## 2.1.7 - -**Date**: 7th Dec 2012 - -* Serializers now properly support nullable Foreign Keys. -* Serializer validation now includes model field validation, such as uniqueness constraints. -* Support 'true' and 'false' string values for BooleanField. -* Added pickle support for serialized data. -* Support `source='dotted.notation'` style for nested serializers. -* Make `Request.user` settable. -* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer` - -## 2.1.6 - -**Date**: 23rd Nov 2012 - -* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.) - -## 2.1.5 - -**Date**: 23rd Nov 2012 - -* Bugfix: Fix DjangoModelPermissions. - -## 2.1.4 - -**Date**: 22nd Nov 2012 - -* Support for partial updates with serializers. -* Added `RegexField`. -* Added `SerializerMethodField`. -* Serializer performance improvements. -* Added `obtain_token_view` to get tokens when using `TokenAuthentication`. -* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`. - -## 2.1.3 - -**Date**: 16th Nov 2012 - -* Added `FileField` and `ImageField`. For use with `MultiPartParser`. -* Added `URLField` and `SlugField`. -* Support for `read_only_fields` on `ModelSerializer` classes. -* Support for clients overriding the pagination page sizes. Use the `PAGINATE_BY_PARAM` setting or set the `paginate_by_param` attribute on a generic view. -* 201 Responses now return a 'Location' header. -* Bugfix: Serializer fields now respect `max_length`. - -## 2.1.2 - -**Date**: 9th Nov 2012 - -* **Filtering support.** -* Bugfix: Support creation of objects with reverse M2M relations. - -## 2.1.1 - -**Date**: 7th Nov 2012 - -* Support use of HTML exception templates. Eg. `403.html` -* Hyperlinked fields take optional `slug_field`, `slug_url_kwarg` and `pk_url_kwarg` arguments. -* Bugfix: Deal with optional trailing slashs properly when generating breadcrumbs. -* Bugfix: 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 - -**Date**: 5th Nov 2012 - -**Warning**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0. - -* **Serializer `instance` and `data` keyword args have their position swapped.** -* `queryset` argument is now optional on writable model fields. -* Hyperlinked related fields optionally take `slug_field` and `slug_field_kwarg` arguments. -* Support Django's cache framework. -* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.) -* Bugfixes (Support choice field in Browseable API) - -## 2.0.2 - -**Date**: 2nd Nov 2012 - -* Fix issues with pk related fields in the browsable API. - -## 2.0.1 - -**Date**: 1st Nov 2012 - -* Add support for relational fields in the browsable API. -* Added SlugRelatedField and ManySlugRelatedField. -* If PUT creates an instance return '201 Created', instead of '200 OK'. - -## 2.0.0 - -**Date**: 30th Oct 2012 - -* Redesign of core components. -* Fix **all of the things**. + tox # License @@ -290,9 +117,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion +[tox]: http://testrun.org/tox/latest/ + [docs]: http://django-rest-framework.org/ [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [pyyaml]: http://pypi.python.org/pypi/PyYAML +[defusedxml]: https://pypi.python.org/pypi/defusedxml [django-filter]: http://pypi.python.org/pypi/django-filter - diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index afd9a2619..541c65756 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": "", "scope": "read", "expires_in": 86399, "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 " 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 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..9a745cf19 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 — normalizing it to a consistent format. > > — [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 53ea7cbcc..ed9463681 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 6d5feba42..dae3dea37 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[0-9]+)/$', 'comment_instance') + url(r'^comments/$', 'comment_list'), + url(r'^comments/(?P[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 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..13d4760a3 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 de9685578..a28304922 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 fce68f6db..4772c5e0d 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: -The method should return `True` if the request should be granted access, and `False` otherwise. +* `.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 + +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 351b5e09e..623fe1a90 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -12,35 +12,319 @@ 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.`. --- +# API Reference + +In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. + + class Album(models.Model): + album_name = models.CharField(max_length=100) + artist = models.CharField(max_length=100) + + class Track(models.Model): + album = models.ForeignKey(Album, related_name='tracks') + order = models.IntegerField() + title = models.CharField(max_length=100) + duration = models.IntegerField() + + class Meta: + unique_together = ('album', 'order') + order_by = 'order' + + def __unicode__(self): + return '%d: %s' % (self.order, self.title) + ## RelatedField -This field can be applied to any of the following: +`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method. -* A `ForeignKey` field. -* A `OneToOneField` field. -* A reverse OneToOne relationship -* Any other "to-one" relationship. - -By default `RelatedField` will represent the target of the field using it's `__unicode__` method. - -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: +For example, the following serializer. -* A `ManyToManyField` field. -* A reverse ManyToMany relationship. -* A reverse ForeignKey relationship -* Any other "to-many" relationship. + class AlbumSerializer(serializers.ModelSerializer): + tracks = RelatedField(many=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') -By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method. +Would serialize to the following representation. -For example, given the following models: + { + 'album_name': 'Things We Lost In The Fire', + 'artist': 'Low' + 'tracks': [ + '1: Sunflower', + '2: Whitetail', + '3: Dinosaur Act', + ... + ] + } + +This field is read only. + +**Arguments**: + +* `many` - If applied to a to-many relationship, you should set this argument to `True`. + +## PrimaryKeyRelatedField + +`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. + +For example, the following serializer: + + class AlbumSerializer(serializers.ModelSerializer): + tracks = PrimaryKeyRelatedField(many=True, read_only=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'The Roots', + 'artist': 'Undun' + 'tracks': [ + 89, + 90, + 91, + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +**Arguments**: + +* `many` - If applied to a to-many relationship, you should set this argument to `True`. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. +* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. + +## HyperlinkedRelatedField + +`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. + +For example, the following serializer: + + class AlbumSerializer(serializers.ModelSerializer): + tracks = HyperlinkedRelatedField(many=True, read_only=True, + view_name='track-detail') + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Graceland', + 'artist': 'Paul Simon' + 'tracks': [ + 'http://www.example.com/api/tracks/45', + 'http://www.example.com/api/tracks/46', + 'http://www.example.com/api/tracks/47', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +**Arguments**: + +* `view_name` - The view name that should be used as the target of the relationship. **required**. +* `many` - If applied to a to-many relationship, you should set this argument to `True`. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. +* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. +* `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 + +`SlugRelatedField` may be used to represent the target of the relationship using a field on the target. + +For example, the following serializer: + + class AlbumSerializer(serializers.ModelSerializer): + tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Dear John', + 'artist': 'Loney Dear' + 'tracks': [ + 'Airport Surroundings', + 'Everything Turns to You', + 'I Was Only Going Out', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`. + +**Arguments**: + +* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required** +* `many` - If applied to a to-many relationship, you should set this argument to `True`. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. +* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. + +## HyperlinkedIdentityField + +This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: + + class AlbumSerializer(serializers.HyperlinkedModelSerializer): + track_listing = HyperlinkedIdentityField(view_name='track-list') + + class Meta: + model = Album + fields = ('album_name', 'artist', 'track_listing') + +Would serialize to a representation like this: + + { + 'album_name': 'The Eraser', + 'artist': 'Thom Yorke' + 'track_listing': 'http://www.example.com/api/track_list/12', + } + +This field is always read-only. + +**Arguments**: + +* `view_name` - The view name that should be used as the target of the relationship. **required**. +* `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): """ @@ -48,15 +332,16 @@ For example, given the following models: See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ """ - tag = models.SlugField() + tag_name = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() - content_object = GenericForeignKey('content_type', 'object_id') + 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. @@ -64,76 +349,71 @@ For example, given the following models: url = models.URLField() tags = GenericRelation(TaggedItem) -And a model serializer defined like this: - class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.ManyRelatedField(source='tags') + 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) - class Meta: - model = Bookmark - exclude = ('id',) +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. -Then an example output format for a Bookmark instance would be: + class TaggedObjectRelatedField(serializers.RelatedField): + """ + A custom field to use for the `tagged_object` generic relationship. + """ - { - 'tags': [u'django', u'python'], - 'url': u'https://www.djangoproject.com/' - } + 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') -## PrimaryKeyRelatedField -## ManyPrimaryKeyRelatedField +If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method: -`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key. + 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') -By default these fields are read-write, although you can change this behavior using the `read_only` flag. + return serializer.data -**Arguments**: +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. -* `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. +For more information see [the Django documentation on generic relations][generic-relations]. -## SlugRelatedField -## ManySlugRelatedField +--- -`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug. +## Deprecated APIs -By default these fields read-write, although you can change this behavior using the `read_only` flag. +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. -**Arguments**: +* `ManyRelatedField` +* `ManyPrimaryKeyRelatedField` +* `ManyHyperlinkedRelatedField` +* `ManySlugRelatedField` -* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. -* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships. +The `null=` flag has been deprecated in favor of the `required=` flag. It will continue to function, but will raise a `PendingDeprecationWarning`. -## HyperlinkedRelatedField -## ManyHyperlinkedRelatedField +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. -`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 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`. +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 b4f7ec3d4..3c8396aa1 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 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..42edf9af1 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. + 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__ --- @@ -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. +When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances. -Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances. +Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation. -The `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` fields provide alternative flat representations. - -The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations. - -The `RelatedField` class may be subclassed to create a custom representation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported. - -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 a422e5f61..116386969 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 -**TODO** +A content negotiation class, that determines how a renderer is selected for the response, given an incoming request. -Default: `rest_framework.serializers.ModelSerializer` +Default: `'rest_framework.negotiation.DefaultContentNegotiation'` -## DEFAULT_PAGINATION_SERIALIZER_CLASS +--- -**TODO** +## Generic view settings + +*The following settings control the behavior of the generic class based views.* + +#### DEFAULT_MODEL_SERIALIZER_CLASS + +A class that determines the default type of model serializer that should be used by a generic view if `model` is specified, but `serializer_class` is not provided. + +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 +--- -**TODO** +## 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 + +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 b03bc9e04..1abd49f47 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 d1e42ec1c..8b26b3e35 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 57446ff98..c160b63d1 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 497f19004..5357536d9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,19 +1,19 @@ - -[![Travis build image][travis-build-image]][travis] +

+ + + + + +Travis build image +

# Django REST framework -**A toolkit for building well-connected, self-describing Web APIs.** +**Web APIs for Django, made easy.** ---- +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. -**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. +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. + + + + ## 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 d789cc582..3e0f29aa0 100644 --- a/docs/template.html +++ b/docs/template.html @@ -2,11 +2,11 @@ - Django REST framework + {{ title }} - - + + @@ -89,10 +89,12 @@