Update documentation

This commit is contained in:
Tom Christie 2015-11-04 14:59:23 +00:00
parent 5bbec106d9
commit 69194018d5
53 changed files with 966 additions and 949 deletions

View File

@ -457,7 +457,7 @@
<h1 id="authentication">Authentication</h1>
<h1 id="authentication"><a class="toclink" href="#authentication">Authentication</a></h1>
<blockquote>
<p>Auth needs to be pluggable.</p>
<p>&mdash; Jacob Kaplan-Moss, <a href="http://jacobian.org/writing/rest-worst-practices/">"REST worst practices"</a></p>
@ -471,11 +471,11 @@
<p><strong>Note:</strong> Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
<p>For information on how to setup the permission polices for your API please see the <a href="../permissions/">permissions documentation</a>.</p>
<hr />
<h2 id="how-authentication-is-determined">How authentication is determined</h2>
<h2 id="how-authentication-is-determined"><a class="toclink" href="#how-authentication-is-determined">How authentication is determined</a></h2>
<p>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 <code>request.user</code> and <code>request.auth</code> using the return value of the first class that successfully authenticates.</p>
<p>If no class authenticates, <code>request.user</code> will be set to an instance of <code>django.contrib.auth.models.AnonymousUser</code>, and <code>request.auth</code> will be set to <code>None</code>.</p>
<p>The value of <code>request.user</code> and <code>request.auth</code> for unauthenticated requests can be modified using the <code>UNAUTHENTICATED_USER</code> and <code>UNAUTHENTICATED_TOKEN</code> settings.</p>
<h2 id="setting-the-authentication-scheme">Setting the authentication scheme</h2>
<h2 id="setting-the-authentication-scheme"><a class="toclink" href="#setting-the-authentication-scheme">Setting the authentication scheme</a></h2>
<p>The default authentication schemes may be set globally, using the <code>DEFAULT_AUTHENTICATION_CLASSES</code> setting. For example.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
@ -513,7 +513,7 @@ def example_view(request, format=None):
}
return Response(content)
</code></pre>
<h2 id="unauthorized-and-forbidden-responses">Unauthorized and Forbidden responses</h2>
<h2 id="unauthorized-and-forbidden-responses"><a class="toclink" href="#unauthorized-and-forbidden-responses">Unauthorized and Forbidden responses</a></h2>
<p>When an unauthenticated request is denied permission there are two different error codes that may be appropriate.</p>
<ul>
<li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2">HTTP 401 Unauthorized</a></li>
@ -522,15 +522,15 @@ def example_view(request, format=None):
<p>HTTP 401 responses must always include a <code>WWW-Authenticate</code> header, that instructs the client how to authenticate. HTTP 403 responses do not include the <code>WWW-Authenticate</code> header.</p>
<p>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. <strong>The first authentication class set on the view is used when determining the type of response</strong>.</p>
<p>Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a <code>403 Permission Denied</code> response will always be used, regardless of the authentication scheme.</p>
<h2 id="apache-mod_wsgi-specific-configuration">Apache mod_wsgi specific configuration</h2>
<h2 id="apache-mod_wsgi-specific-configuration"><a class="toclink" href="#apache-mod_wsgi-specific-configuration">Apache mod_wsgi specific configuration</a></h2>
<p>Note that if deploying to <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization">Apache using mod_wsgi</a>, 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.</p>
<p>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 <code>WSGIPassAuthorization</code> directive in the appropriate context and setting it to <code>'On'</code>.</p>
<pre><code># this can go in either server config, virtual host, directory or .htaccess
WSGIPassAuthorization On
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="basicauthentication">BasicAuthentication</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="basicauthentication"><a class="toclink" href="#basicauthentication">BasicAuthentication</a></h2>
<p>This authentication scheme uses <a href="http://tools.ietf.org/html/rfc2617">HTTP Basic Authentication</a>, signed against a user's username and password. Basic authentication is generally only appropriate for testing.</p>
<p>If successfully authenticated, <code>BasicAuthentication</code> provides the following credentials.</p>
<ul>
@ -541,7 +541,7 @@ WSGIPassAuthorization On
<pre><code>WWW-Authenticate: Basic realm="api"
</code></pre>
<p><strong>Note:</strong> If you use <code>BasicAuthentication</code> in production you must ensure that your API is only available over <code>https</code>. 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.</p>
<h2 id="tokenauthentication">TokenAuthentication</h2>
<h2 id="tokenauthentication"><a class="toclink" href="#tokenauthentication">TokenAuthentication</a></h2>
<p>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.</p>
<p>To use the <code>TokenAuthentication</code> scheme you'll need to <a href="#setting-the-authentication-scheme">configure the authentication classes</a> to include <code>TokenAuthentication</code>, and additionally include <code>rest_framework.authtoken</code> in your <code>INSTALLED_APPS</code> setting:</p>
<pre><code>INSTALLED_APPS = (
@ -575,7 +575,7 @@ print token.key
<hr />
<p><strong>Note:</strong> If you use <code>TokenAuthentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
<hr />
<h4 id="generating-tokens">Generating Tokens</h4>
<h4 id="generating-tokens"><a class="toclink" href="#generating-tokens">Generating Tokens</a></h4>
<p>If you want every user to have an automatically generated Token, you can simply catch the User's <code>post_save</code> signal.</p>
<pre><code>from django.conf import settings
from django.db.models.signals import post_save
@ -606,7 +606,7 @@ urlpatterns += [
<pre><code>{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
</code></pre>
<p>Note that the default <code>obtain_auth_token</code> 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 <code>obtain_auth_token</code> view, you can do so by overriding the <code>ObtainAuthToken</code> view class, and using that in your url conf instead.</p>
<h4 id="schema-migrations">Schema migrations</h4>
<h4 id="schema-migrations"><a class="toclink" href="#schema-migrations">Schema migrations</a></h4>
<p>The <code>rest_framework.authtoken</code> app includes both Django native migrations (for Django versions &gt;1.7) and South migrations (for Django versions &lt;1.7) that will create the authtoken table.</p>
<hr />
<p><strong>Note</strong>: From REST Framework v2.4.0 using South with Django &lt;1.7 requires upgrading South v1.0+</p>
@ -628,7 +628,7 @@ urlpatterns += [
python manage.py migrate
python manage.py createsuperuser
</code></pre>
<h2 id="sessionauthentication">SessionAuthentication</h2>
<h2 id="sessionauthentication"><a class="toclink" href="#sessionauthentication">SessionAuthentication</a></h2>
<p>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.</p>
<p>If successfully authenticated, <code>SessionAuthentication</code> provides the following credentials.</p>
<ul>
@ -639,7 +639,7 @@ python manage.py createsuperuser
<p>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 <code>PUT</code>, <code>PATCH</code>, <code>POST</code> or <code>DELETE</code> requests. See the <a href="https://docs.djangoproject.com/en/dev/ref/csrf/#ajax">Django CSRF documentation</a> for more details.</p>
<p><strong>Warning</strong>: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.</p>
<p>CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.</p>
<h1 id="custom-authentication">Custom authentication</h1>
<h1 id="custom-authentication"><a class="toclink" href="#custom-authentication">Custom authentication</a></h1>
<p>To implement a custom authentication scheme, subclass <code>BaseAuthentication</code> and override the <code>.authenticate(self, request)</code> method. The method should return a two-tuple of <code>(user, auth)</code> if authentication succeeds, or <code>None</code> otherwise.</p>
<p>In some circumstances instead of returning <code>None</code>, you may want to raise an <code>AuthenticationFailed</code> exception from the <code>.authenticate()</code> method.</p>
<p>Typically the approach you should take is:</p>
@ -649,7 +649,7 @@ python manage.py createsuperuser
</ul>
<p>You <em>may</em> also override the <code>.authenticate_header(self, request)</code> method. If implemented, it should return a string that will be used as the value of the <code>WWW-Authenticate</code> header in a <code>HTTP 401 Unauthorized</code> response.</p>
<p>If the <code>.authenticate_header()</code> method is not overridden, the authentication scheme will return <code>HTTP 403 Forbidden</code> responses when an unauthenticated request is denied access.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.</p>
<pre><code>from django.contrib.auth.models import User
from rest_framework import authentication
@ -669,11 +669,11 @@ class ExampleAuthentication(authentication.BaseAuthentication):
return (user, None)
</code></pre>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="django-oauth-toolkit">Django OAuth Toolkit</h2>
<h2 id="django-oauth-toolkit"><a class="toclink" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h2>
<p>The <a href="https://github.com/evonove/django-oauth-toolkit">Django OAuth Toolkit</a> package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by <a href="https://github.com/evonove/">Evonove</a> and uses the excellent <a href="https://github.com/idan/oauthlib">OAuthLib</a>. The package is well documented, and well supported and is currently our <strong>recommended package for OAuth 2.0 support</strong>.</p>
<h4 id="installation-configuration">Installation &amp; configuration</h4>
<h4 id="installation-configuration"><a class="toclink" href="#installation-configuration">Installation &amp; configuration</a></h4>
<p>Install using <code>pip</code>.</p>
<pre><code>pip install django-oauth-toolkit
</code></pre>
@ -690,31 +690,31 @@ REST_FRAMEWORK = {
}
</code></pre>
<p>For more details see the <a href="https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html">Django REST framework - Getting started</a> documentation.</p>
<h2 id="django-rest-framework-oauth">Django REST framework OAuth</h2>
<h2 id="django-rest-framework-oauth"><a class="toclink" href="#django-rest-framework-oauth">Django REST framework OAuth</a></h2>
<p>The <a href="http://jpadilla.github.io/django-rest-framework-oauth/">Django REST framework OAuth</a> package provides both OAuth1 and OAuth2 support for REST framework.</p>
<p>This package was previously included directly in REST framework but is now supported and maintained as a third party package.</p>
<h4 id="installation-configuration_1">Installation &amp; configuration</h4>
<h4 id="installation-configuration_1"><a class="toclink" href="#installation-configuration_1">Installation &amp; configuration</a></h4>
<p>Install the package using <code>pip</code>.</p>
<pre><code>pip install djangorestframework-oauth
</code></pre>
<p>For details on configuration and usage see the Django REST framework OAuth documentation for <a href="http://jpadilla.github.io/django-rest-framework-oauth/authentication/">authentication</a> and <a href="http://jpadilla.github.io/django-rest-framework-oauth/permissions/">permissions</a>.</p>
<h2 id="digest-authentication">Digest Authentication</h2>
<h2 id="digest-authentication"><a class="toclink" href="#digest-authentication">Digest Authentication</a></h2>
<p>HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-digestauth">djangorestframework-digestauth</a> package which provides HTTP digest authentication support for REST framework.</p>
<h2 id="django-oauth2-consumer">Django OAuth2 Consumer</h2>
<h2 id="django-oauth2-consumer"><a class="toclink" href="#django-oauth2-consumer">Django OAuth2 Consumer</a></h2>
<p>The <a href="https://github.com/Rediker-Software/doac">Django OAuth2 Consumer</a> library from <a href="https://github.com/Rediker-Software">Rediker Software</a> is another package that provides <a href="https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#">OAuth 2.0 support for REST framework</a>. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.</p>
<h2 id="json-web-token-authentication">JSON Web Token Authentication</h2>
<h2 id="json-web-token-authentication"><a class="toclink" href="#json-web-token-authentication">JSON Web Token Authentication</a></h2>
<p>JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. <a href="https://github.com/GetBlimp">Blimp</a> maintains the <a href="https://github.com/GetBlimp/django-rest-framework-jwt">djangorestframework-jwt</a> package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.</p>
<h2 id="hawk-http-authentication">Hawk HTTP Authentication</h2>
<h2 id="hawk-http-authentication"><a class="toclink" href="#hawk-http-authentication">Hawk HTTP Authentication</a></h2>
<p>The <a href="http://hawkrest.readthedocs.org/en/latest/">HawkREST</a> library builds on the <a href="http://mohawk.readthedocs.org/en/latest/">Mohawk</a> library to let you work with <a href="https://github.com/hueniverse/hawk">Hawk</a> signed requests and responses in your API. <a href="https://github.com/hueniverse/hawk">Hawk</a> lets two parties securely communicate with each other using messages signed by a shared key. It is based on <a href="http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05">HTTP MAC access authentication</a> (which was based on parts of <a href="http://oauth.net/core/1.0a">OAuth 1.0</a>).</p>
<h2 id="http-signature-authentication">HTTP Signature Authentication</h2>
<h2 id="http-signature-authentication"><a class="toclink" href="#http-signature-authentication">HTTP Signature Authentication</a></h2>
<p>HTTP Signature (currently a <a href="https://datatracker.ietf.org/doc/draft-cavage-http-signatures/">IETF draft</a>) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Amazon's HTTP Signature scheme</a>, used by many of its services, it permits stateless, per-request authentication. <a href="https://github.com/etoccalino/">Elvio Toccalino</a> maintains the <a href="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> package which provides an easy to use HTTP Signature Authentication mechanism.</p>
<h2 id="djoser">Djoser</h2>
<h2 id="djoser"><a class="toclink" href="#djoser">Djoser</a></h2>
<p><a href="https://github.com/sunscrapers/djoser">Djoser</a> library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.</p>
<h2 id="django-rest-auth">django-rest-auth</h2>
<h2 id="django-rest-auth"><a class="toclink" href="#django-rest-auth">django-rest-auth</a></h2>
<p><a href="https://github.com/Tivix/django-rest-auth">Django-rest-auth</a> library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.</p>
<h2 id="django-rest-framework-social-oauth2">django-rest-framework-social-oauth2</h2>
<h2 id="django-rest-framework-social-oauth2"><a class="toclink" href="#django-rest-framework-social-oauth2">django-rest-framework-social-oauth2</a></h2>
<p><a href="https://github.com/PhilipGarnero/django-rest-framework-social-oauth2">Django-rest-framework-social-oauth2</a> library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.</p>
<h2 id="django-rest-knox">django-rest-knox</h2>
<h2 id="django-rest-knox"><a class="toclink" href="#django-rest-knox">django-rest-knox</a></h2>
<p><a href="https://github.com/James1345/django-rest-knox">Django-rest-knox</a> library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).</p>

View File

@ -381,13 +381,13 @@
<h1 id="content-negotiation">Content negotiation</h1>
<h1 id="content-negotiation"><a class="toclink" href="#content-negotiation">Content negotiation</a></h1>
<blockquote>
<p>HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.</p>
<p>&mdash; <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html">RFC 2616</a>, Fielding et al.</p>
</blockquote>
<p>Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.</p>
<h2 id="determining-the-accepted-renderer">Determining the accepted renderer</h2>
<h2 id="determining-the-accepted-renderer"><a class="toclink" href="#determining-the-accepted-renderer">Determining the accepted renderer</a></h2>
<p>REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's <code>Accept:</code> header. The style used is partly client-driven, and partly server-driven.</p>
<ol>
<li>More specific media types are given preference to less specific media types.</li>
@ -408,12 +408,12 @@
<p><strong>Note</strong>: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.</p>
<p>This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.</p>
<hr />
<h1 id="custom-content-negotiation">Custom content negotiation</h1>
<h1 id="custom-content-negotiation"><a class="toclink" href="#custom-content-negotiation">Custom content negotiation</a></h1>
<p>It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override <code>BaseContentNegotiation</code>.</p>
<p>REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the <code>.select_parser(request, parsers)</code> and <code>.select_renderer(request, renderers, format_suffix)</code> methods.</p>
<p>The <code>select_parser()</code> method should return one of the parser instances from the list of available parsers, or <code>None</code> if none of the parsers can handle the incoming request.</p>
<p>The <code>select_renderer()</code> method should return a two-tuple of (renderer instance, media type), or raise a <code>NotAcceptable</code> exception.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following is a custom content negotiation class which ignores the client
request when selecting the appropriate parser or renderer.</p>
<pre><code>from rest_framework.negotiation import BaseContentNegotiation
@ -431,7 +431,7 @@ class IgnoreClientContentNegotiation(BaseContentNegotiation):
"""
return (renderers[0], renderers[0].media_type)
</code></pre>
<h2 id="setting-the-content-negotiation">Setting the content negotiation</h2>
<h2 id="setting-the-content-negotiation"><a class="toclink" href="#setting-the-content-negotiation">Setting the content negotiation</a></h2>
<p>The default content negotiation class may be set globally, using the <code>DEFAULT_CONTENT_NEGOTIATION_CLASS</code> setting. For example, the following settings would use our example <code>IgnoreClientContentNegotiation</code> class.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',

View File

@ -421,12 +421,12 @@
<h1 id="exceptions">Exceptions</h1>
<h1 id="exceptions"><a class="toclink" href="#exceptions">Exceptions</a></h1>
<blockquote>
<p>Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.</p>
<p>&mdash; Doug Hellmann, <a href="http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html">Python Exception Handling Techniques</a></p>
</blockquote>
<h2 id="exception-handling-in-rest-framework-views">Exception handling in REST framework views</h2>
<h2 id="exception-handling-in-rest-framework-views"><a class="toclink" href="#exception-handling-in-rest-framework-views">Exception handling in REST framework views</a></h2>
<p>REST framework's views handle various exceptions, and deal with returning appropriate error responses.</p>
<p>The handled exceptions are:</p>
<ul>
@ -455,7 +455,7 @@ Content-Length: 94
{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
</code></pre>
<h2 id="custom-exception-handling">Custom exception handling</h2>
<h2 id="custom-exception-handling"><a class="toclink" href="#custom-exception-handling">Custom exception handling</a></h2>
<p>You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.</p>
<p>The function must take a pair of arguments, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a <code>Response</code> object, or return <code>None</code> if the exception cannot be handled. If the handler returns <code>None</code> then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.</p>
<p>For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:</p>
@ -492,8 +492,8 @@ def custom_exception_handler(exc, context):
</code></pre>
<p>Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the <code>HTTP_400_BAD_REQUEST</code> responses that are returned by the generic views when serializer validation fails.</p>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="apiexception">APIException</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="apiexception"><a class="toclink" href="#apiexception">APIException</a></h2>
<p><strong>Signature:</strong> <code>APIException()</code></p>
<p>The <strong>base class</strong> for all exceptions raised inside an <code>APIView</code> class or <code>@api_view</code>.</p>
<p>To provide a custom exception, subclass <code>APIException</code> and set the <code>.status_code</code> and <code>.default_detail</code> properties on the class.</p>
@ -504,43 +504,43 @@ class ServiceUnavailable(APIException):
status_code = 503
default_detail = 'Service temporarily unavailable, try again later.'
</code></pre>
<h2 id="parseerror">ParseError</h2>
<h2 id="parseerror"><a class="toclink" href="#parseerror">ParseError</a></h2>
<p><strong>Signature:</strong> <code>ParseError(detail=None)</code></p>
<p>Raised if the request contains malformed data when accessing <code>request.data</code>.</p>
<p>By default this exception results in a response with the HTTP status code "400 Bad Request".</p>
<h2 id="authenticationfailed">AuthenticationFailed</h2>
<h2 id="authenticationfailed"><a class="toclink" href="#authenticationfailed">AuthenticationFailed</a></h2>
<p><strong>Signature:</strong> <code>AuthenticationFailed(detail=None)</code></p>
<p>Raised when an incoming request includes incorrect authentication.</p>
<p>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 <a href="../authentication/">authentication documentation</a> for more details.</p>
<h2 id="notauthenticated">NotAuthenticated</h2>
<h2 id="notauthenticated"><a class="toclink" href="#notauthenticated">NotAuthenticated</a></h2>
<p><strong>Signature:</strong> <code>NotAuthenticated(detail=None)</code></p>
<p>Raised when an unauthenticated request fails the permission checks.</p>
<p>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 <a href="../authentication/">authentication documentation</a> for more details.</p>
<h2 id="permissiondenied">PermissionDenied</h2>
<h2 id="permissiondenied"><a class="toclink" href="#permissiondenied">PermissionDenied</a></h2>
<p><strong>Signature:</strong> <code>PermissionDenied(detail=None)</code></p>
<p>Raised when an authenticated request fails the permission checks.</p>
<p>By default this exception results in a response with the HTTP status code "403 Forbidden".</p>
<h2 id="notfound">NotFound</h2>
<h2 id="notfound"><a class="toclink" href="#notfound">NotFound</a></h2>
<p><strong>Signature:</strong> <code>NotFound(detail=None)</code></p>
<p>Raised when a resource does not exists at the given URL. This exception is equivalent to the standard <code>Http404</code> Django exception.</p>
<p>By default this exception results in a response with the HTTP status code "404 Not Found".</p>
<h2 id="methodnotallowed">MethodNotAllowed</h2>
<h2 id="methodnotallowed"><a class="toclink" href="#methodnotallowed">MethodNotAllowed</a></h2>
<p><strong>Signature:</strong> <code>MethodNotAllowed(method, detail=None)</code></p>
<p>Raised when an incoming request occurs that does not map to a handler method on the view.</p>
<p>By default this exception results in a response with the HTTP status code "405 Method Not Allowed".</p>
<h2 id="notacceptable">NotAcceptable</h2>
<h2 id="notacceptable"><a class="toclink" href="#notacceptable">NotAcceptable</a></h2>
<p><strong>Signature:</strong> <code>NotAcceptable(detail=None)</code></p>
<p>Raised when an incoming request occurs with an <code>Accept</code> header that cannot be satisfied by any of the available renderers.</p>
<p>By default this exception results in a response with the HTTP status code "406 Not Acceptable".</p>
<h2 id="unsupportedmediatype">UnsupportedMediaType</h2>
<h2 id="unsupportedmediatype"><a class="toclink" href="#unsupportedmediatype">UnsupportedMediaType</a></h2>
<p><strong>Signature:</strong> <code>UnsupportedMediaType(media_type, detail=None)</code></p>
<p>Raised if there are no parsers that can handle the content type of the request data when accessing <code>request.data</code>.</p>
<p>By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".</p>
<h2 id="throttled">Throttled</h2>
<h2 id="throttled"><a class="toclink" href="#throttled">Throttled</a></h2>
<p><strong>Signature:</strong> <code>Throttled(wait=None, detail=None)</code></p>
<p>Raised when an incoming request fails the throttling checks.</p>
<p>By default this exception results in a response with the HTTP status code "429 Too Many Requests".</p>
<h2 id="validationerror">ValidationError</h2>
<h2 id="validationerror"><a class="toclink" href="#validationerror">ValidationError</a></h2>
<p><strong>Signature:</strong> <code>ValidationError(detail)</code></p>
<p>The <code>ValidationError</code> exception is slightly different from the other <code>APIException</code> classes:</p>
<ul>

View File

@ -567,7 +567,7 @@
<h1 id="serializer-fields">Serializer fields</h1>
<h1 id="serializer-fields"><a class="toclink" href="#serializer-fields">Serializer fields</a></h1>
<blockquote>
<p>Each field in a Form class is responsible not only for validating data, but also for "cleaning" it &mdash; normalizing it to a consistent format.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data">Django documentation</a></p>
@ -576,42 +576,42 @@
<hr />
<p><strong>Note:</strong> The serializer fields are declared in <code>fields.py</code>, but by convention you should import them using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.&lt;FieldName&gt;</code>.</p>
<hr />
<h2 id="core-arguments">Core arguments</h2>
<h2 id="core-arguments"><a class="toclink" href="#core-arguments">Core arguments</a></h2>
<p>Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:</p>
<h3 id="read_only"><code>read_only</code></h3>
<h3 id="read_only"><a class="toclink" href="#read_only"><code>read_only</code></a></h3>
<p>Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.</p>
<p>Set this to <code>True</code> to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.</p>
<p>Defaults to <code>False</code></p>
<h3 id="write_only"><code>write_only</code></h3>
<h3 id="write_only"><a class="toclink" href="#write_only"><code>write_only</code></a></h3>
<p>Set this to <code>True</code> to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.</p>
<p>Defaults to <code>False</code></p>
<h3 id="required"><code>required</code></h3>
<h3 id="required"><a class="toclink" href="#required"><code>required</code></a></h3>
<p>Normally an error will be raised if a field is not supplied during deserialization.
Set to false if this field is not required to be present during deserialization.</p>
<p>Setting this to <code>False</code> also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.</p>
<p>Defaults to <code>True</code>.</p>
<h3 id="allow_null"><code>allow_null</code></h3>
<h3 id="allow_null"><a class="toclink" href="#allow_null"><code>allow_null</code></a></h3>
<p>Normally an error will be raised if <code>None</code> is passed to a serializer field. Set this keyword argument to <code>True</code> if <code>None</code> should be considered a valid value.</p>
<p>Defaults to <code>False</code></p>
<h3 id="default"><code>default</code></h3>
<h3 id="default"><a class="toclink" href="#default"><code>default</code></a></h3>
<p>If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.</p>
<p>May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a <code>set_context</code> method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for <a href="../validators/#using-set_context">validators</a>.</p>
<p>Note that setting a <code>default</code> value implies that the field is not required. Including both the <code>default</code> and <code>required</code> keyword arguments is invalid and will raise an error.</p>
<h3 id="source"><code>source</code></h3>
<h3 id="source"><a class="toclink" href="#source"><code>source</code></a></h3>
<p>The name of the attribute that will be used to populate the field. May be a method that only takes a <code>self</code> argument, such as <code>URLField(source='get_absolute_url')</code>, or may use dotted notation to traverse attributes, such as <code>EmailField(source='user.email')</code>.</p>
<p>The value <code>source='*'</code> has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.</p>
<p>Defaults to the name of the field.</p>
<h3 id="validators"><code>validators</code></h3>
<h3 id="validators"><a class="toclink" href="#validators"><code>validators</code></a></h3>
<p>A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise <code>serializers.ValidationError</code>, but Django's built-in <code>ValidationError</code> is also supported for compatibility with validators defined in the Django codebase or third party Django packages.</p>
<h3 id="error_messages"><code>error_messages</code></h3>
<h3 id="error_messages"><a class="toclink" href="#error_messages"><code>error_messages</code></a></h3>
<p>A dictionary of error codes to error messages.</p>
<h3 id="label"><code>label</code></h3>
<h3 id="label"><a class="toclink" href="#label"><code>label</code></a></h3>
<p>A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.</p>
<h3 id="help_text"><code>help_text</code></h3>
<h3 id="help_text"><a class="toclink" href="#help_text"><code>help_text</code></a></h3>
<p>A text string that may be used as a description of the field in HTML form fields or other descriptive elements.</p>
<h3 id="initial"><code>initial</code></h3>
<h3 id="initial"><a class="toclink" href="#initial"><code>initial</code></a></h3>
<p>A value that should be used for pre-populating the value of HTML form fields.</p>
<h3 id="style"><code>style</code></h3>
<h3 id="style"><a class="toclink" href="#style"><code>style</code></a></h3>
<p>A dictionary of key-value pairs that can be used to control how renderers should render the field.</p>
<p>Two examples here are <code>'input_type'</code> and <code>'base_template'</code>:</p>
<pre><code># Use &lt;input type="password"&gt; for the input.
@ -627,19 +627,19 @@ color_channel = serializers.ChoiceField(
</code></pre>
<p>For more details see the <a href="../../topics/html-and-forms/">HTML &amp; Forms</a> documentation.</p>
<hr />
<h1 id="boolean-fields">Boolean fields</h1>
<h2 id="booleanfield">BooleanField</h2>
<h1 id="boolean-fields"><a class="toclink" href="#boolean-fields">Boolean fields</a></h1>
<h2 id="booleanfield"><a class="toclink" href="#booleanfield">BooleanField</a></h2>
<p>A boolean representation.</p>
<p>When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to <code>False</code>, even if it has a <code>default=True</code> option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.</p>
<p>Corresponds to <code>django.db.models.fields.BooleanField</code>.</p>
<p><strong>Signature:</strong> <code>BooleanField()</code></p>
<h2 id="nullbooleanfield">NullBooleanField</h2>
<h2 id="nullbooleanfield"><a class="toclink" href="#nullbooleanfield">NullBooleanField</a></h2>
<p>A boolean representation that also accepts <code>None</code> as a valid value.</p>
<p>Corresponds to <code>django.db.models.fields.NullBooleanField</code>.</p>
<p><strong>Signature:</strong> <code>NullBooleanField()</code></p>
<hr />
<h1 id="string-fields">String fields</h1>
<h2 id="charfield">CharField</h2>
<h1 id="string-fields"><a class="toclink" href="#string-fields">String fields</a></h1>
<h2 id="charfield"><a class="toclink" href="#charfield">CharField</a></h2>
<p>A text representation. Optionally validates the text to be shorter than <code>max_length</code> and longer than <code>min_length</code>.</p>
<p>Corresponds to <code>django.db.models.fields.CharField</code> or <code>django.db.models.fields.TextField</code>.</p>
<p><strong>Signature:</strong> <code>CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)</code></p>
@ -650,25 +650,25 @@ color_channel = serializers.ChoiceField(
<li><code>trim_whitespace</code> - If set to <code>True</code> then leading and trailing whitespace is trimmed. Defaults to <code>True</code>.</li>
</ul>
<p>The <code>allow_null</code> option is also available for string fields, although its usage is discouraged in favor of <code>allow_blank</code>. It is valid to set both <code>allow_blank=True</code> and <code>allow_null=True</code>, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.</p>
<h2 id="emailfield">EmailField</h2>
<h2 id="emailfield"><a class="toclink" href="#emailfield">EmailField</a></h2>
<p>A text representation, validates the text to be a valid e-mail address.</p>
<p>Corresponds to <code>django.db.models.fields.EmailField</code></p>
<p><strong>Signature:</strong> <code>EmailField(max_length=None, min_length=None, allow_blank=False)</code></p>
<h2 id="regexfield">RegexField</h2>
<h2 id="regexfield"><a class="toclink" href="#regexfield">RegexField</a></h2>
<p>A text representation, that validates the given value matches against a certain regular expression.</p>
<p>Corresponds to <code>django.forms.fields.RegexField</code>.</p>
<p><strong>Signature:</strong> <code>RegexField(regex, max_length=None, min_length=None, allow_blank=False)</code></p>
<p>The mandatory <code>regex</code> argument may either be a string, or a compiled python regular expression object.</p>
<p>Uses Django's <code>django.core.validators.RegexValidator</code> for validation.</p>
<h2 id="slugfield">SlugField</h2>
<h2 id="slugfield"><a class="toclink" href="#slugfield">SlugField</a></h2>
<p>A <code>RegexField</code> that validates the input against the pattern <code>[a-zA-Z0-9_-]+</code>.</p>
<p>Corresponds to <code>django.db.models.fields.SlugField</code>.</p>
<p><strong>Signature:</strong> <code>SlugField(max_length=50, min_length=None, allow_blank=False)</code></p>
<h2 id="urlfield">URLField</h2>
<h2 id="urlfield"><a class="toclink" href="#urlfield">URLField</a></h2>
<p>A <code>RegexField</code> that validates the input against a URL matching pattern. Expects fully qualified URLs of the form <code>http://&lt;host&gt;/&lt;path&gt;</code>.</p>
<p>Corresponds to <code>django.db.models.fields.URLField</code>. Uses Django's <code>django.core.validators.URLValidator</code> for validation.</p>
<p><strong>Signature:</strong> <code>URLField(max_length=200, min_length=None, allow_blank=False)</code></p>
<h2 id="uuidfield">UUIDField</h2>
<h2 id="uuidfield"><a class="toclink" href="#uuidfield">UUIDField</a></h2>
<p>A field that ensures the input is a valid UUID string. The <code>to_internal_value</code> method will return a <code>uuid.UUID</code> instance. On output the field will return a string in the canonical hyphenated format, for example:</p>
<pre><code>"de305d54-75b4-431b-adb2-eb6b9e546013"
</code></pre>
@ -683,7 +683,7 @@ color_channel = serializers.ChoiceField(
</ul>
</li>
</ul>
<h2 id="filepathfield">FilePathField</h2>
<h2 id="filepathfield"><a class="toclink" href="#filepathfield">FilePathField</a></h2>
<p>A field whose choices are limited to the filenames in a certain directory on the filesystem</p>
<p>Corresponds to <code>django.forms.fields.FilePathField</code>.</p>
<p><strong>Signature:</strong> <code>FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)</code></p>
@ -694,7 +694,7 @@ color_channel = serializers.ChoiceField(
<li><code>allow_files</code> - Specifies whether files in the specified location should be included. Default is <code>True</code>. Either this or <code>allow_folders</code> must be <code>True</code>.</li>
<li><code>allow_folders</code> - Specifies whether folders in the specified location should be included. Default is <code>False</code>. Either this or <code>allow_files</code> must be <code>True</code>.</li>
</ul>
<h2 id="ipaddressfield">IPAddressField</h2>
<h2 id="ipaddressfield"><a class="toclink" href="#ipaddressfield">IPAddressField</a></h2>
<p>A field that ensures the input is a valid IPv4 or IPv6 string.</p>
<p>Corresponds to <code>django.forms.fields.IPAddressField</code> and <code>django.forms.fields.GenericIPAddressField</code>.</p>
<p><strong>Signature</strong>: <code>IPAddressField(protocol='both', unpack_ipv4=False, **options)</code></p>
@ -703,8 +703,8 @@ color_channel = serializers.ChoiceField(
<li><code>unpack_ipv4</code> Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.</li>
</ul>
<hr />
<h1 id="numeric-fields">Numeric fields</h1>
<h2 id="integerfield">IntegerField</h2>
<h1 id="numeric-fields"><a class="toclink" href="#numeric-fields">Numeric fields</a></h1>
<h2 id="integerfield"><a class="toclink" href="#integerfield">IntegerField</a></h2>
<p>An integer representation.</p>
<p>Corresponds to <code>django.db.models.fields.IntegerField</code>, <code>django.db.models.fields.SmallIntegerField</code>, <code>django.db.models.fields.PositiveIntegerField</code> and <code>django.db.models.fields.PositiveSmallIntegerField</code>.</p>
<p><strong>Signature</strong>: <code>IntegerField(max_value=None, min_value=None)</code></p>
@ -712,7 +712,7 @@ color_channel = serializers.ChoiceField(
<li><code>max_value</code> Validate that the number provided is no greater than this value.</li>
<li><code>min_value</code> Validate that the number provided is no less than this value.</li>
</ul>
<h2 id="floatfield">FloatField</h2>
<h2 id="floatfield"><a class="toclink" href="#floatfield">FloatField</a></h2>
<p>A floating point representation.</p>
<p>Corresponds to <code>django.db.models.fields.FloatField</code>.</p>
<p><strong>Signature</strong>: <code>FloatField(max_value=None, min_value=None)</code></p>
@ -720,7 +720,7 @@ color_channel = serializers.ChoiceField(
<li><code>max_value</code> Validate that the number provided is no greater than this value.</li>
<li><code>min_value</code> Validate that the number provided is no less than this value.</li>
</ul>
<h2 id="decimalfield">DecimalField</h2>
<h2 id="decimalfield"><a class="toclink" href="#decimalfield">DecimalField</a></h2>
<p>A decimal representation, represented in Python by a <code>Decimal</code> instance.</p>
<p>Corresponds to <code>django.db.models.fields.DecimalField</code>.</p>
<p><strong>Signature</strong>: <code>DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)</code></p>
@ -731,7 +731,7 @@ color_channel = serializers.ChoiceField(
<li><code>max_value</code> Validate that the number provided is no greater than this value.</li>
<li><code>min_value</code> Validate that the number provided is no less than this value.</li>
</ul>
<h4 id="example-usage">Example usage</h4>
<h4 id="example-usage"><a class="toclink" href="#example-usage">Example usage</a></h4>
<p>To validate numbers up to 999 with a resolution of 2 decimal places, you would use:</p>
<pre><code>serializers.DecimalField(max_digits=5, decimal_places=2)
</code></pre>
@ -741,8 +741,8 @@ color_channel = serializers.ChoiceField(
<p>This field also takes an optional argument, <code>coerce_to_string</code>. If set to <code>True</code> the representation will be output as a string. If set to <code>False</code> the representation will be left as a <code>Decimal</code> instance and the final representation will be determined by the renderer.</p>
<p>If unset, this will default to the same value as the <code>COERCE_DECIMAL_TO_STRING</code> setting, which is <code>True</code> unless set otherwise.</p>
<hr />
<h1 id="date-and-time-fields">Date and time fields</h1>
<h2 id="datetimefield">DateTimeField</h2>
<h1 id="date-and-time-fields"><a class="toclink" href="#date-and-time-fields">Date and time fields</a></h1>
<h2 id="datetimefield"><a class="toclink" href="#datetimefield">DateTimeField</a></h2>
<p>A date and time representation.</p>
<p>Corresponds to <code>django.db.models.fields.DateTimeField</code>.</p>
<p><strong>Signature:</strong> <code>DateTimeField(format=None, input_formats=None)</code></p>
@ -750,11 +750,11 @@ color_channel = serializers.ChoiceField(
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>DATETIME_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>datetime</code> objects should be returned by <code>to_representation</code>. In this case the datetime encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATETIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
</ul>
<h4 id="datetimefield-format-strings"><code>DateTimeField</code> format strings.</h4>
<h4 id="datetimefield-format-strings"><a class="toclink" href="#datetimefield-format-strings"><code>DateTimeField</code> format strings.</a></h4>
<p>Format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style datetimes should be used. (eg <code>'2013-01-29T12:34:56.000000Z'</code>)</p>
<p>When a value of <code>None</code> is used for the format <code>datetime</code> objects will be returned by <code>to_representation</code> and the final output representation will determined by the renderer class.</p>
<p>In the case of JSON this means the default datetime representation uses the <a href="http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">ECMA 262 date time string specification</a>. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: <code>2013-01-29T12:34:56.123Z</code>.</p>
<h4 id="auto_now-and-auto_now_add-model-fields"><code>auto_now</code> and <code>auto_now_add</code> model fields.</h4>
<h4 id="auto_now-and-auto_now_add-model-fields"><a class="toclink" href="#auto_now-and-auto_now_add-model-fields"><code>auto_now</code> and <code>auto_now_add</code> model fields.</a></h4>
<p>When using <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code>, note that any model fields with <code>auto_now=True</code> or <code>auto_now_add=True</code> will use serializer fields that are <code>read_only=True</code> by default.</p>
<p>If you want to override this behavior, you'll need to declare the <code>DateTimeField</code> explicitly on the serializer. For example:</p>
<pre><code>class CommentSerializer(serializers.ModelSerializer):
@ -763,7 +763,7 @@ color_channel = serializers.ChoiceField(
class Meta:
model = Comment
</code></pre>
<h2 id="datefield">DateField</h2>
<h2 id="datefield"><a class="toclink" href="#datefield">DateField</a></h2>
<p>A date representation.</p>
<p>Corresponds to <code>django.db.models.fields.DateField</code></p>
<p><strong>Signature:</strong> <code>DateField(format=None, input_formats=None)</code></p>
@ -771,9 +771,9 @@ color_channel = serializers.ChoiceField(
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>DATE_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>date</code> objects should be returned by <code>to_representation</code>. In this case the date encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATE_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
</ul>
<h4 id="datefield-format-strings"><code>DateField</code> format strings</h4>
<h4 id="datefield-format-strings"><a class="toclink" href="#datefield-format-strings"><code>DateField</code> format strings</a></h4>
<p>Format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style dates should be used. (eg <code>'2013-01-29'</code>)</p>
<h2 id="timefield">TimeField</h2>
<h2 id="timefield"><a class="toclink" href="#timefield">TimeField</a></h2>
<p>A time representation.</p>
<p>Corresponds to <code>django.db.models.fields.TimeField</code></p>
<p><strong>Signature:</strong> <code>TimeField(format=None, input_formats=None)</code></p>
@ -781,9 +781,9 @@ color_channel = serializers.ChoiceField(
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>TIME_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>time</code> objects should be returned by <code>to_representation</code>. In this case the time encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>TIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
</ul>
<h4 id="timefield-format-strings"><code>TimeField</code> format strings</h4>
<h4 id="timefield-format-strings"><a class="toclink" href="#timefield-format-strings"><code>TimeField</code> format strings</a></h4>
<p>Format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style times should be used. (eg <code>'12:34:56.000000'</code>)</p>
<h2 id="durationfield">DurationField</h2>
<h2 id="durationfield"><a class="toclink" href="#durationfield">DurationField</a></h2>
<p>A Duration representation.
Corresponds to <code>django.db.models.fields.DurationField</code></p>
<p>The <code>validated_data</code> for these fields will contain a <code>datetime.timedelta</code> instance.
@ -791,8 +791,8 @@ The representation is a string following this format <code>'[DD] [HH:[MM:]]ss[.u
<p><strong>Note:</strong> This field is only available with Django versions &gt;= 1.8.</p>
<p><strong>Signature:</strong> <code>DurationField()</code></p>
<hr />
<h1 id="choice-selection-fields">Choice selection fields</h1>
<h2 id="choicefield">ChoiceField</h2>
<h1 id="choice-selection-fields"><a class="toclink" href="#choice-selection-fields">Choice selection fields</a></h1>
<h2 id="choicefield"><a class="toclink" href="#choicefield">ChoiceField</a></h2>
<p>A field that can accept a value out of a limited set of choices.</p>
<p>Used by <code>ModelSerializer</code> to automatically generate fields if the corresponding model field includes a <code>choices=…</code> argument.</p>
<p><strong>Signature:</strong> <code>ChoiceField(choices)</code></p>
@ -803,7 +803,7 @@ The representation is a string following this format <code>'[DD] [HH:[MM:]]ss[.u
<li><code>html_cutoff_text</code> - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to <code>"More than {count} items…"</code></li>
</ul>
<p>Both the <code>allow_blank</code> and <code>allow_null</code> are valid options on <code>ChoiceField</code>, although it is highly recommended that you only use one and not both. <code>allow_blank</code> should be preferred for textual choices, and <code>allow_null</code> should be preferred for numeric or other non-textual choices.</p>
<h2 id="multiplechoicefield">MultipleChoiceField</h2>
<h2 id="multiplechoicefield"><a class="toclink" href="#multiplechoicefield">MultipleChoiceField</a></h2>
<p>A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. <code>to_internal_value</code> returns a <code>set</code> containing the selected values.</p>
<p><strong>Signature:</strong> <code>MultipleChoiceField(choices)</code></p>
<ul>
@ -814,11 +814,11 @@ The representation is a string following this format <code>'[DD] [HH:[MM:]]ss[.u
</ul>
<p>As with <code>ChoiceField</code>, both the <code>allow_blank</code> and <code>allow_null</code> options are valid, although it is highly recommended that you only use one and not both. <code>allow_blank</code> should be preferred for textual choices, and <code>allow_null</code> should be preferred for numeric or other non-textual choices.</p>
<hr />
<h1 id="file-upload-fields">File upload fields</h1>
<h4 id="parsers-and-file-uploads">Parsers and file uploads.</h4>
<h1 id="file-upload-fields"><a class="toclink" href="#file-upload-fields">File upload fields</a></h1>
<h4 id="parsers-and-file-uploads"><a class="toclink" href="#parsers-and-file-uploads">Parsers and file uploads.</a></h4>
<p>The <code>FileField</code> and <code>ImageField</code> classes are only suitable for use with <code>MultiPartParser</code> or <code>FileUploadParser</code>. Most parsers, such as e.g. JSON don't support file uploads.
Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS">FILE_UPLOAD_HANDLERS</a> are used for handling uploaded files.</p>
<h2 id="filefield">FileField</h2>
<h2 id="filefield"><a class="toclink" href="#filefield">FileField</a></h2>
<p>A file representation. Performs Django's standard FileField validation.</p>
<p>Corresponds to <code>django.forms.fields.FileField</code>.</p>
<p><strong>Signature:</strong> <code>FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)</code></p>
@ -827,7 +827,7 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
<li><code>allow_empty_file</code> - Designates if empty files are allowed.</li>
<li><code>use_url</code> - If set to <code>True</code> then URL string values will be used for the output representation. If set to <code>False</code> then filename string values will be used for the output representation. Defaults to the value of the <code>UPLOADED_FILES_USE_URL</code> settings key, which is <code>True</code> unless set otherwise.</li>
</ul>
<h2 id="imagefield">ImageField</h2>
<h2 id="imagefield"><a class="toclink" href="#imagefield">ImageField</a></h2>
<p>An image representation. Validates the uploaded file content as matching a known image format.</p>
<p>Corresponds to <code>django.forms.fields.ImageField</code>.</p>
<p><strong>Signature:</strong> <code>ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)</code></p>
@ -838,8 +838,8 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
</ul>
<p>Requires either the <code>Pillow</code> package or <code>PIL</code> package. The <code>Pillow</code> package is recommended, as <code>PIL</code> is no longer actively maintained.</p>
<hr />
<h1 id="composite-fields">Composite fields</h1>
<h2 id="listfield">ListField</h2>
<h1 id="composite-fields"><a class="toclink" href="#composite-fields">Composite fields</a></h1>
<h2 id="listfield"><a class="toclink" href="#listfield">ListField</a></h2>
<p>A field class that validates a list of objects.</p>
<p><strong>Signature</strong>: <code>ListField(child)</code></p>
<ul>
@ -855,7 +855,7 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
child = serializers.CharField()
</code></pre>
<p>We can now reuse our custom <code>StringListField</code> class throughout our application, without having to provide a <code>child</code> argument to it.</p>
<h2 id="dictfield">DictField</h2>
<h2 id="dictfield"><a class="toclink" href="#dictfield">DictField</a></h2>
<p>A field class that validates a dictionary of objects. The keys in <code>DictField</code> are always assumed to be string values.</p>
<p><strong>Signature</strong>: <code>DictField(child)</code></p>
<ul>
@ -868,15 +868,15 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
<pre><code>class DocumentField(DictField):
child = CharField()
</code></pre>
<h2 id="jsonfield">JSONField</h2>
<h2 id="jsonfield"><a class="toclink" href="#jsonfield">JSONField</a></h2>
<p>A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.</p>
<p><strong>Signature</strong>: <code>JSONField(binary)</code></p>
<ul>
<li><code>binary</code> - If set to <code>True</code> then the field will output and validate a JSON encoded string, rather that a primitive data structure. Defaults to <code>False</code>.</li>
<li><code>binary</code> - If set to <code>True</code> then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to <code>False</code>.</li>
</ul>
<hr />
<h1 id="miscellaneous-fields">Miscellaneous fields</h1>
<h2 id="readonlyfield">ReadOnlyField</h2>
<h1 id="miscellaneous-fields"><a class="toclink" href="#miscellaneous-fields">Miscellaneous fields</a></h1>
<h2 id="readonlyfield"><a class="toclink" href="#readonlyfield">ReadOnlyField</a></h2>
<p>A field class that simply returns the value of the field without modification.</p>
<p>This field is used by default with <code>ModelSerializer</code> when including field names that relate to an attribute rather than a model field.</p>
<p><strong>Signature</strong>: <code>ReadOnlyField()</code></p>
@ -886,7 +886,7 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
model = Account
fields = ('id', 'account_name', 'has_expired')
</code></pre>
<h2 id="hiddenfield">HiddenField</h2>
<h2 id="hiddenfield"><a class="toclink" href="#hiddenfield">HiddenField</a></h2>
<p>A field class that does not take a value based on user input, but instead takes its value from a default value or callable.</p>
<p><strong>Signature</strong>: <code>HiddenField()</code></p>
<p>For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:</p>
@ -894,12 +894,12 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
</code></pre>
<p>The <code>HiddenField</code> class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.</p>
<p>For further examples on <code>HiddenField</code> see the <a href="../validators/">validators</a> documentation.</p>
<h2 id="modelfield">ModelField</h2>
<h2 id="modelfield"><a class="toclink" href="#modelfield">ModelField</a></h2>
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
<p>This field is used by <code>ModelSerializer</code> to correspond to custom model field classes.</p>
<p><strong>Signature:</strong> <code>ModelField(model_field=&lt;Django ModelField instance&gt;)</code></p>
<p>The <code>ModelField</code> class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a <code>ModelField</code>, it must be passed a field that is attached to an instantiated model. For example: <code>ModelField(model_field=MyModel()._meta.get_field('custom_field'))</code></p>
<h2 id="serializermethodfield">SerializerMethodField</h2>
<h2 id="serializermethodfield"><a class="toclink" href="#serializermethodfield">SerializerMethodField</a></h2>
<p>This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.</p>
<p><strong>Signature</strong>: <code>SerializerMethodField(method_name=None)</code></p>
<ul>
@ -920,12 +920,12 @@ class UserSerializer(serializers.ModelSerializer):
return (now() - obj.date_joined).days
</code></pre>
<hr />
<h1 id="custom-fields">Custom fields</h1>
<h1 id="custom-fields"><a class="toclink" href="#custom-fields">Custom fields</a></h1>
<p>If you want to create a custom field, you'll need to subclass <code>Field</code> and then override either one or both of the <code>.to_representation()</code> and <code>.to_internal_value()</code> methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, <code>date</code>/<code>time</code>/<code>datetime</code> or <code>None</code>. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.</p>
<p>The <code>.to_representation()</code> method is called to convert the initial datatype into a primitive, serializable datatype.</p>
<p>The <code>to_internal_value()</code> method is called to restore a primitive datatype into its internal python representation. This method should raise a <code>serializers.ValidationError</code> if the data is invalid.</p>
<p>Note that the <code>WritableField</code> class that was present in version 2.x no longer exists. You should subclass <code>Field</code> and override <code>to_internal_value()</code> if the field supports data input.</p>
<h2 id="examples">Examples</h2>
<h2 id="examples"><a class="toclink" href="#examples">Examples</a></h2>
<p>Let's look at an example of serializing a class that represents an RGB color value:</p>
<pre><code>class Color(object):
"""
@ -962,7 +962,7 @@ class ColorField(serializers.Field):
"""
return obj.__class__.__name__
</code></pre>
<h4 id="raising-validation-errors">Raising validation errors</h4>
<h4 id="raising-validation-errors"><a class="toclink" href="#raising-validation-errors">Raising validation errors</a></h4>
<p>Our <code>ColorField</code> class above currently does not perform any data validation.
To indicate invalid data, we should raise a <code>serializers.ValidationError</code>, like so:</p>
<pre><code>def to_internal_value(self, data):
@ -1005,17 +1005,17 @@ def to_internal_value(self, data):
return Color(red, green, blue)
</code></pre>
<p>This style keeps you error messages more cleanly separated from your code, and should be preferred.</p>
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-compound-fields">DRF Compound Fields</h2>
<h2 id="drf-compound-fields"><a class="toclink" href="#drf-compound-fields">DRF Compound Fields</a></h2>
<p>The <a href="http://drf-compound-fields.readthedocs.org">drf-compound-fields</a> package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the <code>many=True</code> option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.</p>
<h2 id="drf-extra-fields">DRF Extra Fields</h2>
<h2 id="drf-extra-fields"><a class="toclink" href="#drf-extra-fields">DRF Extra Fields</a></h2>
<p>The <a href="https://github.com/Hipo/drf-extra-fields">drf-extra-fields</a> package provides extra serializer fields for REST framework, including <code>Base64ImageField</code> and <code>PointField</code> classes.</p>
<h2 id="djangrestframework-recursive">djangrestframework-recursive</h2>
<h2 id="djangrestframework-recursive"><a class="toclink" href="#djangrestframework-recursive">djangrestframework-recursive</a></h2>
<p>the <a href="https://github.com/heywbj/django-rest-framework-recursive">djangorestframework-recursive</a> package provides a <code>RecursiveField</code> for serializing and deserializing recursive structures</p>
<h2 id="django-rest-framework-gis">django-rest-framework-gis</h2>
<h2 id="django-rest-framework-gis"><a class="toclink" href="#django-rest-framework-gis">django-rest-framework-gis</a></h2>
<p>The <a href="https://github.com/djangonauts/django-rest-framework-gis">django-rest-framework-gis</a> package provides geographic addons for django rest framework like a <code>GeometryField</code> field and a GeoJSON serializer.</p>
<h2 id="django-rest-framework-hstore">django-rest-framework-hstore</h2>
<h2 id="django-rest-framework-hstore"><a class="toclink" href="#django-rest-framework-hstore">django-rest-framework-hstore</a></h2>
<p>The <a href="https://github.com/djangonauts/django-rest-framework-hstore">django-rest-framework-hstore</a> package provides an <code>HStoreField</code> to support <a href="https://github.com/djangonauts/django-hstore">django-hstore</a> <code>DictionaryField</code> model field.</p>

View File

@ -447,7 +447,7 @@
<h1 id="filtering">Filtering</h1>
<h1 id="filtering"><a class="toclink" href="#filtering">Filtering</a></h1>
<blockquote>
<p>The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters">Django documentation</a></p>
@ -455,7 +455,7 @@
<p>The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.</p>
<p>The simplest way to filter the queryset of any view that subclasses <code>GenericAPIView</code> is to override the <code>.get_queryset()</code> method.</p>
<p>Overriding this method allows you to customize the queryset returned by the view in a number of different ways.</p>
<h2 id="filtering-against-the-current-user">Filtering against the current user</h2>
<h2 id="filtering-against-the-current-user"><a class="toclink" href="#filtering-against-the-current-user">Filtering against the current user</a></h2>
<p>You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.</p>
<p>You can do so by filtering based on the value of <code>request.user</code>.</p>
<p>For example:</p>
@ -474,7 +474,7 @@ class PurchaseList(generics.ListAPIView):
user = self.request.user
return Purchase.objects.filter(purchaser=user)
</code></pre>
<h2 id="filtering-against-the-url">Filtering against the URL</h2>
<h2 id="filtering-against-the-url"><a class="toclink" href="#filtering-against-the-url">Filtering against the URL</a></h2>
<p>Another style of filtering might involve restricting the queryset based on some part of the URL.</p>
<p>For example if your URL config contained an entry like this:</p>
<pre><code>url('^purchases/(?P&lt;username&gt;.+)/$', PurchaseList.as_view()),
@ -491,7 +491,7 @@ class PurchaseList(generics.ListAPIView):
username = self.kwargs['username']
return Purchase.objects.filter(purchaser__username=username)
</code></pre>
<h2 id="filtering-against-query-parameters">Filtering against query parameters</h2>
<h2 id="filtering-against-query-parameters"><a class="toclink" href="#filtering-against-query-parameters">Filtering against query parameters</a></h2>
<p>A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.</p>
<p>We can override <code>.get_queryset()</code> to deal with URLs such as <code>http://example.com/api/purchases?username=denvercoder9</code>, and filter the queryset only if the <code>username</code> parameter is included in the URL:</p>
<pre><code>class PurchaseList(generics.ListAPIView):
@ -509,11 +509,11 @@ class PurchaseList(generics.ListAPIView):
return queryset
</code></pre>
<hr />
<h1 id="generic-filtering">Generic Filtering</h1>
<h1 id="generic-filtering"><a class="toclink" href="#generic-filtering">Generic Filtering</a></h1>
<p>As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.</p>
<p>Generic filters can also present themselves as HTML controls in the browsable API and admin API.</p>
<p><img alt="Filter Example" src="../../img/filter-controls.png" /></p>
<h2 id="setting-filter-backends">Setting filter backends</h2>
<h2 id="setting-filter-backends"><a class="toclink" href="#setting-filter-backends">Setting filter backends</a></h2>
<p>The default filter backends may be set globally, using the <code>DEFAULT_FILTER_BACKENDS</code> setting. For example.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
@ -531,12 +531,12 @@ class UserListView(generics.ListAPIView):
serializer = UserSerializer
filter_backends = (filters.DjangoFilterBackend,)
</code></pre>
<h2 id="filtering-and-object-lookups">Filtering and object lookups</h2>
<h2 id="filtering-and-object-lookups"><a class="toclink" href="#filtering-and-object-lookups">Filtering and object lookups</a></h2>
<p>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.</p>
<p>For instance, given the previous example, and a product with an id of <code>4675</code>, 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:</p>
<pre><code>http://example.com/api/products/4675/?category=clothing&amp;max_price=10.00
</code></pre>
<h2 id="overriding-the-initial-queryset">Overriding the initial queryset</h2>
<h2 id="overriding-the-initial-queryset"><a class="toclink" href="#overriding-the-initial-queryset">Overriding the initial queryset</a></h2>
<p>Note that you can use both an overridden <code>.get_queryset()</code> and generic filtering together, and everything will work as expected. For example, if <code>Product</code> had a many-to-many relationship with <code>User</code>, named <code>purchase</code>, you might want to write a view like this:</p>
<pre><code>class PurchasedProductsList(generics.ListAPIView):
"""
@ -552,8 +552,8 @@ class UserListView(generics.ListAPIView):
return user.purchase_set.all()
</code></pre>
<hr />
<h1 id="api-guide">API Guide</h1>
<h2 id="djangofilterbackend">DjangoFilterBackend</h2>
<h1 id="api-guide"><a class="toclink" href="#api-guide">API Guide</a></h1>
<h2 id="djangofilterbackend"><a class="toclink" href="#djangofilterbackend">DjangoFilterBackend</a></h2>
<p>The <code>DjangoFilterBackend</code> class supports highly customizable field filtering, using the <a href="https://github.com/alex/django-filter">django-filter package</a>.</p>
<p>To use REST framework's <code>DjangoFilterBackend</code>, first install <code>django-filter</code>.</p>
<pre><code>pip install django-filter
@ -562,8 +562,8 @@ class UserListView(generics.ListAPIView):
<pre><code>pip install django-crispy-forms
</code></pre>
<p>With crispy forms installed, the browsable API will present a filtering control for <code>DjangoFilterBackend</code>, like so:</p>
<p><img alt="Django Filter" src="../../../docs/img/django-filter.png" /></p>
<h4 id="specifying-filter-fields">Specifying filter fields</h4>
<p><img alt="Django Filter" src="../../img/django-filter.png" /></p>
<h4 id="specifying-filter-fields"><a class="toclink" href="#specifying-filter-fields">Specifying filter fields</a></h4>
<p>If all you need is simple equality-based filtering, you can set a <code>filter_fields</code> attribute on the view, or viewset, listing the set of fields you wish to filter against.</p>
<pre><code>class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
@ -574,7 +574,7 @@ class UserListView(generics.ListAPIView):
<p>This will automatically create a <code>FilterSet</code> class for the given fields, and will allow you to make requests such as:</p>
<pre><code>http://example.com/api/products?category=clothing&amp;in_stock=True
</code></pre>
<h4 id="specifying-a-filterset">Specifying a FilterSet</h4>
<h4 id="specifying-a-filterset"><a class="toclink" href="#specifying-a-filterset">Specifying a FilterSet</a></h4>
<p>For more advanced filtering requirements you can specify a <code>FilterSet</code> class that should be used by the view. For example:</p>
<pre><code>import django_filters
from myapp.models import Product
@ -640,10 +640,10 @@ class ProductFilter(django_filters.FilterSet):
<li>For Django 1.3 support, make sure to install <code>django-filter</code> version 0.5.4, as later versions drop support for 1.3.</li>
</ul>
<hr />
<h2 id="searchfilter">SearchFilter</h2>
<h2 id="searchfilter"><a class="toclink" href="#searchfilter">SearchFilter</a></h2>
<p>The <code>SearchFilter</code> class supports simple single query parameter based searching, and is based on the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django admin's search functionality</a>.</p>
<p>When in use, the browsable API will include a <code>SearchFilter</code> control:</p>
<p><img alt="Search Filter" src="../../../docs/img/search-filter.png" /></p>
<p><img alt="Search Filter" src="../../img/search-filter.png" /></p>
<p>The <code>SearchFilter</code> class will only be applied if the view has a <code>search_fields</code> attribute set. The <code>search_fields</code> attribute should be a list of names of text type fields on the model, such as <code>CharField</code> or <code>TextField</code>.</p>
<pre><code>class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -671,9 +671,9 @@ class ProductFilter(django_filters.FilterSet):
<p>By default, the search parameter is named <code>'search</code>', but this may be overridden with the <code>SEARCH_PARAM</code> setting.</p>
<p>For more details, see the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django documentation</a>.</p>
<hr />
<h2 id="orderingfilter">OrderingFilter</h2>
<h2 id="orderingfilter"><a class="toclink" href="#orderingfilter">OrderingFilter</a></h2>
<p>The <code>OrderingFilter</code> class supports simple query parameter controlled ordering of results.</p>
<p><img alt="Ordering Filter" src="../../../docs/img/ordering-filter.png" /></p>
<p><img alt="Ordering Filter" src="../../img/ordering-filter.png" /></p>
<p>By default, the query parameter is named <code>'ordering'</code>, but this may by overridden with the <code>ORDERING_PARAM</code> setting.</p>
<p>For example, to order users by username:</p>
<pre><code>http://example.com/api/users?ordering=username
@ -684,7 +684,7 @@ class ProductFilter(django_filters.FilterSet):
<p>Multiple orderings may also be specified:</p>
<pre><code>http://example.com/api/users?ordering=account,username
</code></pre>
<h3 id="specifying-which-fields-may-be-ordered-against">Specifying which fields may be ordered against</h3>
<h3 id="specifying-which-fields-may-be-ordered-against"><a class="toclink" href="#specifying-which-fields-may-be-ordered-against">Specifying which fields may be ordered against</a></h3>
<p>It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an <code>ordering_fields</code> attribute on the view, like so:</p>
<pre><code>class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -701,7 +701,7 @@ class ProductFilter(django_filters.FilterSet):
filter_backends = (filters.OrderingFilter,)
ordering_fields = '__all__'
</code></pre>
<h3 id="specifying-a-default-ordering">Specifying a default ordering</h3>
<h3 id="specifying-a-default-ordering"><a class="toclink" href="#specifying-a-default-ordering">Specifying a default ordering</a></h3>
<p>If an <code>ordering</code> attribute is set on the view, this will be used as the default ordering.</p>
<p>Typically you'd instead control this by setting <code>order_by</code> on the initial queryset, but using the <code>ordering</code> parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.</p>
<pre><code>class UserListView(generics.ListAPIView):
@ -713,7 +713,7 @@ class ProductFilter(django_filters.FilterSet):
</code></pre>
<p>The <code>ordering</code> attribute may be either a string or a list/tuple of strings.</p>
<hr />
<h2 id="djangoobjectpermissionsfilter">DjangoObjectPermissionsFilter</h2>
<h2 id="djangoobjectpermissionsfilter"><a class="toclink" href="#djangoobjectpermissionsfilter">DjangoObjectPermissionsFilter</a></h2>
<p>The <code>DjangoObjectPermissionsFilter</code> is intended to be used together with the <a href="https://django-guardian.readthedocs.org/"><code>django-guardian</code></a> package, with custom <code>'view'</code> permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.</p>
<p>If you're using <code>DjangoObjectPermissionsFilter</code>, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass <code>DjangoObjectPermissions</code> and add <code>'view'</code> permissions to the <code>perms_map</code> attribute.</p>
<p>A complete example using both <code>DjangoObjectPermissionsFilter</code> and <code>DjangoObjectPermissions</code> might look something like this.</p>
@ -746,11 +746,11 @@ class ProductFilter(django_filters.FilterSet):
</code></pre>
<p>For more information on adding <code>'view'</code> permissions for models, see the <a href="https://django-guardian.readthedocs.org/en/latest/userguide/assign.html">relevant section</a> of the <code>django-guardian</code> documentation, and <a href="http://blog.nyaruka.com/adding-a-view-permission-to-django-models">this blogpost</a>.</p>
<hr />
<h1 id="custom-generic-filtering">Custom generic filtering</h1>
<h1 id="custom-generic-filtering"><a class="toclink" href="#custom-generic-filtering">Custom generic filtering</a></h1>
<p>You can also provide your own generic filtering backend, or write an installable app for other developers to use.</p>
<p>To do so override <code>BaseFilterBackend</code>, and override the <code>.filter_queryset(self, request, queryset, view)</code> method. The method should return a new, filtered queryset.</p>
<p>As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>For example, you might need to restrict users to only being able to see objects they created.</p>
<pre><code>class IsOwnerFilterBackend(filters.BaseFilterBackend):
"""
@ -760,17 +760,17 @@ class ProductFilter(django_filters.FilterSet):
return queryset.filter(owner=request.user)
</code></pre>
<p>We could achieve the same behavior by overriding <code>get_queryset()</code> on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.</p>
<h2 id="customizing-the-interface">Customizing the interface</h2>
<h2 id="customizing-the-interface"><a class="toclink" href="#customizing-the-interface">Customizing the interface</a></h2>
<p>Generic filters may also present an interface in the browsable API. To do so you should implement a <code>to_html()</code> method which returns a rendered HTML representation of the filter. This method should have the following signature:</p>
<p><code>to_html(self, request, queryset, view)</code></p>
<p>The method should return a rendered HTML string.</p>
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages provide additional filter implementations.</p>
<h2 id="django-rest-framework-filters-package">Django REST framework filters package</h2>
<h2 id="django-rest-framework-filters-package"><a class="toclink" href="#django-rest-framework-filters-package">Django REST framework filters package</a></h2>
<p>The <a href="https://github.com/philipn/django-rest-framework-filters">django-rest-framework-filters package</a> works together with the <code>DjangoFilterBackend</code> class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.</p>
<h2 id="django-rest-framework-full-word-search-filter">Django REST framework full word search filter</h2>
<h2 id="django-rest-framework-full-word-search-filter"><a class="toclink" href="#django-rest-framework-full-word-search-filter">Django REST framework full word search filter</a></h2>
<p>The <a href="https://github.com/trollknurr/django-rest-framework-word-search-filter">djangorestframework-word-filter</a> developed as alternative to <code>filters.SearchFilter</code> which will search full word in text, or exact match.</p>
<h2 id="django-url-filter">Django URL Filter</h2>
<h2 id="django-url-filter"><a class="toclink" href="#django-url-filter">Django URL Filter</a></h2>
<p><a href="https://github.com/miki725/django-url-filter">django-url-filter</a> provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django <code>QuerySet</code>s.</p>

View File

@ -375,7 +375,7 @@
<h1 id="format-suffixes">Format suffixes</h1>
<h1 id="format-suffixes"><a class="toclink" href="#format-suffixes">Format suffixes</a></h1>
<blockquote>
<p>Section 6.2.1 does not say that content negotiation should be
used all the time.</p>
@ -383,7 +383,7 @@ used all the time.</p>
</blockquote>
<p>A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.</p>
<p>Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.</p>
<h2 id="format_suffix_patterns">format_suffix_patterns</h2>
<h2 id="format_suffix_patterns"><a class="toclink" href="#format_suffix_patterns">format_suffix_patterns</a></h2>
<p><strong>Signature</strong>: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None)</p>
<p>Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided.</p>
<p>Arguments:</p>
@ -419,7 +419,7 @@ def comment_list(request, format=None):
</code></pre>
<p>The name of the kwarg used may be modified by using the <code>FORMAT_SUFFIX_KWARG</code> setting.</p>
<p>Also note that <code>format_suffix_patterns</code> does not support descending into <code>include</code> URL patterns.</p>
<h3 id="using-with-i18n_patterns">Using with <code>i18n_patterns</code></h3>
<h3 id="using-with-i18n_patterns"><a class="toclink" href="#using-with-i18n_patterns">Using with <code>i18n_patterns</code></a></h3>
<p>If using the <code>i18n_patterns</code> function provided by Django, as well as <code>format_suffix_patterns</code> you should make sure that the <code>i18n_patterns</code> function is applied as the final, or outermost function. For example:</p>
<pre><code>url patterns = [
@ -430,12 +430,12 @@ urlpatterns = i18n_patterns(
)
</code></pre>
<hr />
<h2 id="query-parameter-formats">Query parameter formats</h2>
<h2 id="query-parameter-formats"><a class="toclink" href="#query-parameter-formats">Query parameter formats</a></h2>
<p>An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations.</p>
<p>To select a representation using its short format, use the <code>format</code> query parameter. For example: <code>http://example.com/organizations/?format=csv</code>.</p>
<p>The name of this query parameter can be modified using the <code>URL_FORMAT_OVERRIDE</code> setting. Set the value to <code>None</code> to disable this behavior.</p>
<hr />
<h2 id="accept-headers-vs-format-suffixes">Accept headers vs. format suffixes</h2>
<h2 id="accept-headers-vs-format-suffixes"><a class="toclink" href="#accept-headers-vs-format-suffixes">Accept headers vs. format suffixes</a></h2>
<p>There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that <code>HTTP Accept</code> headers should always be used instead.</p>
<p>It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:</p>
<p>&ldquo;That's why I always prefer extensions. Neither choice has anything to do with REST.&rdquo; &mdash; Roy Fielding, <a href="http://tech.groups.yahoo.com/group/rest-discuss/message/14844">REST discuss mailing list</a></p>

View File

@ -483,7 +483,7 @@
<h1 id="generic-views">Generic views</h1>
<h1 id="generic-views"><a class="toclink" href="#generic-views">Generic views</a></h1>
<blockquote>
<p>Djangos generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views">Django Documentation</a></p>
@ -491,7 +491,7 @@
<p>One of the key benefits of class based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.</p>
<p>The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.</p>
<p>If the generic views don't suit the needs of your API, you can drop down to using the regular <code>APIView</code> class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.</p>
<h2 id="examples">Examples</h2>
<h2 id="examples"><a class="toclink" href="#examples">Examples</a></h2>
<p>Typically when using the generic views, you'll override the view, and set several class attributes.</p>
<pre><code>from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
@ -528,11 +528,11 @@ class UserList(generics.ListCreateAPIView):
<pre><code>url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="genericapiview">GenericAPIView</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="genericapiview"><a class="toclink" href="#genericapiview">GenericAPIView</a></h2>
<p>This class extends REST framework's <code>APIView</code> class, adding commonly required behavior for standard list and detail views.</p>
<p>Each of the concrete generic views provided is built by combining <code>GenericAPIView</code>, with one or more mixin classes.</p>
<h3 id="attributes">Attributes</h3>
<h3 id="attributes"><a class="toclink" href="#attributes">Attributes</a></h3>
<p><strong>Basic settings</strong>:</p>
<p>The following attributes control the basic view behavior.</p>
<ul>
@ -551,9 +551,9 @@ class UserList(generics.ListCreateAPIView):
<ul>
<li><code>filter_backends</code> - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the <code>DEFAULT_FILTER_BACKENDS</code> setting.</li>
</ul>
<h3 id="methods">Methods</h3>
<h3 id="methods"><a class="toclink" href="#methods">Methods</a></h3>
<p><strong>Base methods</strong>:</p>
<h4 id="get_querysetself"><code>get_queryset(self)</code></h4>
<h4 id="get_querysetself"><a class="toclink" href="#get_querysetself"><code>get_queryset(self)</code></a></h4>
<p>Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the <code>queryset</code> attribute.</p>
<p>This method should always be used rather than accessing <code>self.queryset</code> directly, as <code>self.queryset</code> gets evaluated only once, and those results are cached for all subsequent requests.</p>
<p>May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.</p>
@ -562,7 +562,7 @@ class UserList(generics.ListCreateAPIView):
user = self.request.user
return user.accounts.all()
</code></pre>
<h4 id="get_objectself"><code>get_object(self)</code></h4>
<h4 id="get_objectself"><a class="toclink" href="#get_objectself"><code>get_object(self)</code></a></h4>
<p>Returns an object instance that should be used for detail views. Defaults to using the <code>lookup_field</code> parameter to filter the base queryset.</p>
<p>May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.</p>
<p>For example:</p>
@ -577,7 +577,7 @@ class UserList(generics.ListCreateAPIView):
return obj
</code></pre>
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>self.check_object_permissions</code>, and simply return the object from the <code>get_object_or_404</code> lookup.</p>
<h4 id="filter_querysetself-queryset"><code>filter_queryset(self, queryset)</code></h4>
<h4 id="filter_querysetself-queryset"><a class="toclink" href="#filter_querysetself-queryset"><code>filter_queryset(self, queryset)</code></a></h4>
<p>Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. </p>
<p>For example: </p>
<pre><code>def filter_queryset(self, queryset):
@ -593,7 +593,7 @@ class UserList(generics.ListCreateAPIView):
return queryset
</code></pre>
<h4 id="get_serializer_classself"><code>get_serializer_class(self)</code></h4>
<h4 id="get_serializer_classself"><a class="toclink" href="#get_serializer_classself"><code>get_serializer_class(self)</code></a></h4>
<p>Returns the class that should be used for the serializer. Defaults to returning the <code>serializer_class</code> attribute.</p>
<p>May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.</p>
<p>For example:</p>
@ -602,7 +602,7 @@ class UserList(generics.ListCreateAPIView):
return FullAccountSerializer
return BasicAccountSerializer
</code></pre>
<h4 id="get_paginate_byself"><code>get_paginate_by(self)</code></h4>
<h4 id="get_paginate_byself"><a class="toclink" href="#get_paginate_byself"><code>get_paginate_by(self)</code></a></h4>
<p>Returns the page size to use with pagination. By default this uses the <code>paginate_by</code> attribute, and may be overridden by the client if the <code>paginate_by_param</code> attribute is set.</p>
<p>You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.</p>
<p>For example:</p>
@ -645,72 +645,72 @@ class UserList(generics.ListCreateAPIView):
<li><code>filter_queryset(self, queryset)</code> - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.</li>
</ul>
<hr />
<h1 id="mixins">Mixins</h1>
<h1 id="mixins"><a class="toclink" href="#mixins">Mixins</a></h1>
<p>The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as <code>.get()</code> and <code>.post()</code>, directly. This allows for more flexible composition of behavior.</p>
<p>The mixin classes can be imported from <code>rest_framework.mixins</code>.</p>
<h2 id="listmodelmixin">ListModelMixin</h2>
<h2 id="listmodelmixin"><a class="toclink" href="#listmodelmixin">ListModelMixin</a></h2>
<p>Provides a <code>.list(request, *args, **kwargs)</code> method, that implements listing a queryset.</p>
<p>If the queryset is populated, this returns a <code>200 OK</code> response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.</p>
<h2 id="createmodelmixin">CreateModelMixin</h2>
<h2 id="createmodelmixin"><a class="toclink" href="#createmodelmixin">CreateModelMixin</a></h2>
<p>Provides a <code>.create(request, *args, **kwargs)</code> method, that implements creating and saving a new model instance.</p>
<p>If an object is created this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response. If the representation contains a key named <code>url</code>, then the <code>Location</code> header of the response will be populated with that value.</p>
<p>If the request data provided for creating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<h2 id="retrievemodelmixin">RetrieveModelMixin</h2>
<h2 id="retrievemodelmixin"><a class="toclink" href="#retrievemodelmixin">RetrieveModelMixin</a></h2>
<p>Provides a <code>.retrieve(request, *args, **kwargs)</code> method, that implements returning an existing model instance in a response.</p>
<p>If an object can be retrieved this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response. Otherwise it will return a <code>404 Not Found</code>.</p>
<h2 id="updatemodelmixin">UpdateModelMixin</h2>
<h2 id="updatemodelmixin"><a class="toclink" href="#updatemodelmixin">UpdateModelMixin</a></h2>
<p>Provides a <code>.update(request, *args, **kwargs)</code> method, that implements updating and saving an existing model instance.</p>
<p>Also provides a <code>.partial_update(request, *args, **kwargs)</code> method, which is similar to the <code>update</code> method, except that all fields for the update will be optional. This allows support for HTTP <code>PATCH</code> requests.</p>
<p>If an object is updated this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If an object is created, for example when making a <code>DELETE</code> request followed by a <code>PUT</code> request to the same URL, this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If the request data provided for updating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<h2 id="destroymodelmixin">DestroyModelMixin</h2>
<h2 id="destroymodelmixin"><a class="toclink" href="#destroymodelmixin">DestroyModelMixin</a></h2>
<p>Provides a <code>.destroy(request, *args, **kwargs)</code> method, that implements deletion of an existing model instance.</p>
<p>If an object is deleted this returns a <code>204 No Content</code> response, otherwise it will return a <code>404 Not Found</code>.</p>
<hr />
<h1 id="concrete-view-classes">Concrete View Classes</h1>
<h1 id="concrete-view-classes"><a class="toclink" href="#concrete-view-classes">Concrete View Classes</a></h1>
<p>The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.</p>
<p>The view classes can be imported from <code>rest_framework.generics</code>.</p>
<h2 id="createapiview">CreateAPIView</h2>
<h2 id="createapiview"><a class="toclink" href="#createapiview">CreateAPIView</a></h2>
<p>Used for <strong>create-only</strong> endpoints.</p>
<p>Provides a <code>post</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
<h2 id="listapiview">ListAPIView</h2>
<h2 id="listapiview"><a class="toclink" href="#listapiview">ListAPIView</a></h2>
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
<p>Provides a <code>get</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a></p>
<h2 id="retrieveapiview">RetrieveAPIView</h2>
<h2 id="retrieveapiview"><a class="toclink" href="#retrieveapiview">RetrieveAPIView</a></h2>
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides a <code>get</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a></p>
<h2 id="destroyapiview">DestroyAPIView</h2>
<h2 id="destroyapiview"><a class="toclink" href="#destroyapiview">DestroyAPIView</a></h2>
<p>Used for <strong>delete-only</strong> endpoints for a <strong>single model instance</strong>.</p>
<p>Provides a <code>delete</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<h2 id="updateapiview">UpdateAPIView</h2>
<h2 id="updateapiview"><a class="toclink" href="#updateapiview">UpdateAPIView</a></h2>
<p>Used for <strong>update-only</strong> endpoints for a <strong>single model instance</strong>.</p>
<p>Provides <code>put</code> and <code>patch</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
<h2 id="listcreateapiview">ListCreateAPIView</h2>
<h2 id="listcreateapiview"><a class="toclink" href="#listcreateapiview">ListCreateAPIView</a></h2>
<p>Used for <strong>read-write</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
<p>Provides <code>get</code> and <code>post</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
<h2 id="retrieveupdateapiview">RetrieveUpdateAPIView</h2>
<h2 id="retrieveupdateapiview"><a class="toclink" href="#retrieveupdateapiview">RetrieveUpdateAPIView</a></h2>
<p>Used for <strong>read or update</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code>, <code>put</code> and <code>patch</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
<h2 id="retrievedestroyapiview">RetrieveDestroyAPIView</h2>
<h2 id="retrievedestroyapiview"><a class="toclink" href="#retrievedestroyapiview">RetrieveDestroyAPIView</a></h2>
<p>Used for <strong>read or delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code> and <code>delete</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<h2 id="retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</h2>
<h2 id="retrieveupdatedestroyapiview"><a class="toclink" href="#retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</a></h2>
<p>Used for <strong>read-write-delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code>, <code>put</code>, <code>patch</code> and <code>delete</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<hr />
<h1 id="customizing-the-generic-views">Customizing the generic views</h1>
<h1 id="customizing-the-generic-views"><a class="toclink" href="#customizing-the-generic-views">Customizing the generic views</a></h1>
<p>Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.</p>
<h2 id="creating-custom-mixins">Creating custom mixins</h2>
<h2 id="creating-custom-mixins"><a class="toclink" href="#creating-custom-mixins">Creating custom mixins</a></h2>
<p>For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:</p>
<pre><code>class MultipleFieldLookupMixin(object):
"""
@ -732,7 +732,7 @@ class UserList(generics.ListCreateAPIView):
lookup_fields = ('account', 'username')
</code></pre>
<p>Using custom mixins is a good option if you have custom behavior that needs to be used.</p>
<h2 id="creating-custom-base-classes">Creating custom base classes</h2>
<h2 id="creating-custom-base-classes"><a class="toclink" href="#creating-custom-base-classes">Creating custom base classes</a></h2>
<p>If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:</p>
<pre><code>class BaseRetrieveView(MultipleFieldLookupMixin,
generics.RetrieveAPIView):
@ -744,17 +744,17 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
</code></pre>
<p>Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.</p>
<hr />
<h1 id="put-as-create">PUT as create</h1>
<h1 id="put-as-create"><a class="toclink" href="#put-as-create">PUT as create</a></h1>
<p>Prior to version 3.0 the REST framework mixins treated <code>PUT</code> as either an update or a create operation, depending on if the object already existed or not.</p>
<p>Allowing <code>PUT</code> as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning <code>404</code> responses.</p>
<p>Both styles "<code>PUT</code> as 404" and "<code>PUT</code> as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.</p>
<p>If you need to generic PUT-as-create behavior you may want to include something like <a href="https://gist.github.com/tomchristie/a2ace4577eff2c603b1b">this <code>AllowPUTAsCreateMixin</code> class</a> as a mixin to your views.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages provide additional generic view implementations.</p>
<h2 id="django-rest-framework-bulk">Django REST Framework bulk</h2>
<h2 id="django-rest-framework-bulk"><a class="toclink" href="#django-rest-framework-bulk">Django REST Framework bulk</a></h2>
<p>The <a href="https://github.com/miki725/django-rest-framework-bulk">django-rest-framework-bulk package</a> implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.</p>
<h2 id="django-rest-multiple-models">Django Rest Multiple Models</h2>
<h2 id="django-rest-multiple-models"><a class="toclink" href="#django-rest-multiple-models">Django Rest Multiple Models</a></h2>
<p><a href="https://github.com/Axiologue/DjangoRestMultipleModels">Django Rest Multiple Models</a> provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.</p>

View File

@ -381,7 +381,7 @@
<h1 id="metadata">Metadata</h1>
<h1 id="metadata"><a class="toclink" href="#metadata">Metadata</a></h1>
<blockquote>
<p>[The <code>OPTIONS</code>] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.</p>
<p>&mdash; <a href="http://tools.ietf.org/html/rfc7231#section-4.3.7">RFC7231, Section 4.3.7.</a></p>
@ -418,7 +418,7 @@ Content-Type: application/json
}
}
</code></pre>
<h2 id="setting-the-metadata-scheme">Setting the metadata scheme</h2>
<h2 id="setting-the-metadata-scheme"><a class="toclink" href="#setting-the-metadata-scheme">Setting the metadata scheme</a></h2>
<p>You can set the metadata class globally using the <code>'DEFAULT_METADATA_CLASS'</code> settings key:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
@ -434,7 +434,7 @@ Content-Type: application/json
})
</code></pre>
<p>The REST framework package only includes a single metadata class implementation, named <code>SimpleMetadata</code>. If you want to use an alternative style you'll need to implement a custom metadata class.</p>
<h2 id="creating-schema-endpoints">Creating schema endpoints</h2>
<h2 id="creating-schema-endpoints"><a class="toclink" href="#creating-schema-endpoints">Creating schema endpoints</a></h2>
<p>If you have specific requirements for creating schema endpoints that are accessed with regular <code>GET</code> requests, you might consider re-using the metadata API for doing so.</p>
<p>For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.</p>
<pre><code>@list_route(methods=['GET'])
@ -445,10 +445,10 @@ def schema(self, request):
</code></pre>
<p>There are a couple of reasons that you might choose to take this approach, including that <code>OPTIONS</code> responses <a href="https://www.mnot.net/blog/2012/10/29/NO_OPTIONS">are not cacheable</a>.</p>
<hr />
<h1 id="custom-metadata-classes">Custom metadata classes</h1>
<h1 id="custom-metadata-classes"><a class="toclink" href="#custom-metadata-classes">Custom metadata classes</a></h1>
<p>If you want to provide a custom metadata class you should override <code>BaseMetadata</code> and implement the <code>determine_metadata(self, request, view)</code> method.</p>
<p>Useful things that you might want to do could include returning schema information, using a format such as <a href="http://json-schema.org/">JSON schema</a>, or returning debug information to admin users.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following class could be used to limit the information that is returned to <code>OPTIONS</code> requests.</p>
<pre><code>class MinimalMetadata(BaseMetadata):
"""

View File

@ -427,7 +427,7 @@
<h1 id="pagination">Pagination</h1>
<h1 id="pagination"><a class="toclink" href="#pagination">Pagination</a></h1>
<blockquote>
<p>Django provides a few classes that help you manage paginated data that is, data thats split across several pages, with “Previous/Next” links.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/topics/pagination/">Django documentation</a></p>
@ -440,14 +440,14 @@
</ul>
<p>The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.</p>
<p>Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular <code>APIView</code>, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the <code>mixins.ListModelMixin</code> and <code>generics.GenericAPIView</code> classes for an example.</p>
<h2 id="setting-the-pagination-style">Setting the pagination style</h2>
<h2 id="setting-the-pagination-style"><a class="toclink" href="#setting-the-pagination-style">Setting the pagination style</a></h2>
<p>The default pagination style may be set globally, using the <code>DEFAULT_PAGINATION_CLASS</code> settings key. For example, to use the built-in limit/offset pagination, you would do:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}
</code></pre>
<p>You can also set the pagination class on an individual view by using the <code>pagination_class</code> attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.</p>
<h2 id="modifying-the-pagination-style">Modifying the pagination style</h2>
<h2 id="modifying-the-pagination-style"><a class="toclink" href="#modifying-the-pagination-style">Modifying the pagination style</a></h2>
<p>If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change.</p>
<pre><code>class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
@ -471,8 +471,8 @@ class StandardResultsSetPagination(PageNumberPagination):
}
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="pagenumberpagination">PageNumberPagination</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="pagenumberpagination"><a class="toclink" href="#pagenumberpagination">PageNumberPagination</a></h2>
<p>This pagination style accepts a single number page number in the request query parameters.</p>
<p><strong>Request</strong>:</p>
<pre><code>GET https://api.example.org/accounts/?page=4
@ -488,7 +488,7 @@ class StandardResultsSetPagination(PageNumberPagination):
]
}
</code></pre>
<h4 id="setup">Setup</h4>
<h4 id="setup"><a class="toclink" href="#setup">Setup</a></h4>
<p>To enable the <code>PageNumberPagination</code> style globally, use the following configuration, modifying the <code>PAGE_SIZE</code> as desired:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
@ -496,7 +496,7 @@ class StandardResultsSetPagination(PageNumberPagination):
}
</code></pre>
<p>On <code>GenericAPIView</code> subclasses you may also set the <code>pagination_class</code> attribute to select <code>PageNumberPagination</code> on a per-view basis.</p>
<h4 id="configuration">Configuration</h4>
<h4 id="configuration"><a class="toclink" href="#configuration">Configuration</a></h4>
<p>The <code>PageNumberPagination</code> class includes a number of attributes that may be overridden to modify the pagination style.</p>
<p>To set these attributes you should override the <code>PageNumberPagination</code> class, and then enable your custom pagination class as above.</p>
<ul>
@ -508,7 +508,7 @@ class StandardResultsSetPagination(PageNumberPagination):
<li><code>template</code> - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to <code>None</code> to disable HTML pagination controls completely. Defaults to <code>"rest_framework/pagination/numbers.html"</code>.</li>
</ul>
<hr />
<h2 id="limitoffsetpagination">LimitOffsetPagination</h2>
<h2 id="limitoffsetpagination"><a class="toclink" href="#limitoffsetpagination">LimitOffsetPagination</a></h2>
<p>This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the <code>page_size</code> in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.</p>
<p><strong>Request</strong>:</p>
@ -525,7 +525,7 @@ class StandardResultsSetPagination(PageNumberPagination):
]
}
</code></pre>
<h4 id="setup_1">Setup</h4>
<h4 id="setup_1"><a class="toclink" href="#setup_1">Setup</a></h4>
<p>To enable the <code>LimitOffsetPagination</code> style globally, use the following configuration:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
@ -533,7 +533,7 @@ class StandardResultsSetPagination(PageNumberPagination):
</code></pre>
<p>Optionally, you may also set a <code>PAGE_SIZE</code> key. If the <code>PAGE_SIZE</code> parameter is also used then the <code>limit</code> query parameter will be optional, and may be omitted by the client.</p>
<p>On <code>GenericAPIView</code> subclasses you may also set the <code>pagination_class</code> attribute to select <code>LimitOffsetPagination</code> on a per-view basis.</p>
<h4 id="configuration_1">Configuration</h4>
<h4 id="configuration_1"><a class="toclink" href="#configuration_1">Configuration</a></h4>
<p>The <code>LimitOffsetPagination</code> class includes a number of attributes that may be overridden to modify the pagination style.</p>
<p>To set these attributes you should override the <code>LimitOffsetPagination</code> class, and then enable your custom pagination class as above.</p>
<ul>
@ -544,7 +544,7 @@ class StandardResultsSetPagination(PageNumberPagination):
<li><code>template</code> - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to <code>None</code> to disable HTML pagination controls completely. Defaults to <code>"rest_framework/pagination/numbers.html"</code>.</li>
</ul>
<hr />
<h2 id="cursorpagination">CursorPagination</h2>
<h2 id="cursorpagination"><a class="toclink" href="#cursorpagination">CursorPagination</a></h2>
<p>The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.</p>
<p>Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.</p>
<p>Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits:</p>
@ -552,7 +552,7 @@ class StandardResultsSetPagination(PageNumberPagination):
<li>Provides a consistent pagination view. When used properly <code>CursorPagination</code> ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process.</li>
<li>Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.</li>
</ul>
<h4 id="details-and-limitations">Details and limitations</h4>
<h4 id="details-and-limitations"><a class="toclink" href="#details-and-limitations">Details and limitations</a></h4>
<p>Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by <code>"-created"</code>. This assumes that <strong>there must be a 'created' timestamp field</strong> on the model instances, and will present a "timeline" style paginated view, with the most recently added items first.</p>
<p>You can modify the ordering by overriding the <code>'ordering'</code> attribute on the pagination class, or by using the <code>OrderingFilter</code> filter class together with <code>CursorPagination</code>. When used with <code>OrderingFilter</code> you should strongly consider restricting the fields that the user may order by.</p>
<p>Proper usage of cursor pagination should have an ordering field that satisfies the following:</p>
@ -564,7 +564,7 @@ class StandardResultsSetPagination(PageNumberPagination):
</ul>
<p>Using an ordering field that does not satisfy these constraints will generally still work, but you'll be loosing some of the benefits of cursor pagination.</p>
<p>For more technical details on the implementation we use for cursor pagination, the <a href="http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/">"Building cursors for the Disqus API"</a> blog post gives a good overview of the basic approach.</p>
<h4 id="setup_2">Setup</h4>
<h4 id="setup_2"><a class="toclink" href="#setup_2">Setup</a></h4>
<p>To enable the <code>CursorPagination</code> style globally, use the following configuration, modifying the <code>PAGE_SIZE</code> as desired:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
@ -572,7 +572,7 @@ class StandardResultsSetPagination(PageNumberPagination):
}
</code></pre>
<p>On <code>GenericAPIView</code> subclasses you may also set the <code>pagination_class</code> attribute to select <code>CursorPagination</code> on a per-view basis.</p>
<h4 id="configuration_2">Configuration</h4>
<h4 id="configuration_2"><a class="toclink" href="#configuration_2">Configuration</a></h4>
<p>The <code>CursorPagination</code> class includes a number of attributes that may be overridden to modify the pagination style.</p>
<p>To set these attributes you should override the <code>CursorPagination</code> class, and then enable your custom pagination class as above.</p>
<ul>
@ -582,14 +582,14 @@ class StandardResultsSetPagination(PageNumberPagination):
<li><code>template</code> = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to <code>None</code> to disable HTML pagination controls completely. Defaults to <code>"rest_framework/pagination/previous_and_next.html"</code>.</li>
</ul>
<hr />
<h1 id="custom-pagination-styles">Custom pagination styles</h1>
<h1 id="custom-pagination-styles"><a class="toclink" href="#custom-pagination-styles">Custom pagination styles</a></h1>
<p>To create a custom pagination serializer class you should subclass <code>pagination.BasePagination</code> and override the <code>paginate_queryset(self, queryset, request, view=None)</code> and <code>get_paginated_response(self, data)</code> methods:</p>
<ul>
<li>The <code>paginate_queryset</code> method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.</li>
<li>The <code>get_paginated_response</code> method is passed the serialized page data and should return a <code>Response</code> instance.</li>
</ul>
<p>Note that the <code>paginate_queryset</code> method may set state on the pagination instance, that may later be used by the <code>get_paginated_response</code> method.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:</p>
<pre><code>class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
@ -609,7 +609,7 @@ class StandardResultsSetPagination(PageNumberPagination):
}
</code></pre>
<p>Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an <code>OrderedDict</code> when constructing the body of paginated responses, but this is optional.</p>
<h2 id="header-based-pagination">Header based pagination</h2>
<h2 id="header-based-pagination"><a class="toclink" href="#header-based-pagination">Header based pagination</a></h2>
<p>Let's modify the built-in <code>PageNumberPagination</code> style, so that instead of include the pagination links in the body of the response, we'll instead include a <code>Link</code> header, in a <a href="https://developer.github.com/guides/traversing-with-pagination/">similar style to the GitHub API</a>.</p>
<pre><code>class LinkHeaderPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
@ -630,7 +630,7 @@ class StandardResultsSetPagination(PageNumberPagination):
return Response(data, headers=headers)
</code></pre>
<h2 id="using-your-custom-pagination-class">Using your custom pagination class</h2>
<h2 id="using-your-custom-pagination-class"><a class="toclink" href="#using-your-custom-pagination-class">Using your custom pagination class</a></h2>
<p>To have your custom pagination class be used by default, use the <code>DEFAULT_PAGINATION_CLASS</code> setting:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',
@ -642,9 +642,9 @@ class StandardResultsSetPagination(PageNumberPagination):
<p><img alt="Link Header" src="../../img/link-header-pagination.png" /></p>
<p><em>A custom pagination style, using the 'Link' header'</em></p>
<hr />
<h1 id="html-pagination-controls">HTML pagination controls</h1>
<h1 id="html-pagination-controls"><a class="toclink" href="#html-pagination-controls">HTML pagination controls</a></h1>
<p>By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The <code>PageNumberPagination</code> and <code>LimitOffsetPagination</code> classes display a list of page numbers with previous and next controls. The <code>CursorPagination</code> class displays a simpler style that only displays a previous and next control.</p>
<h2 id="customizing-the-controls">Customizing the controls</h2>
<h2 id="customizing-the-controls"><a class="toclink" href="#customizing-the-controls">Customizing the controls</a></h2>
<p>You can override the templates that render the HTML pagination controls. The two built-in styles are:</p>
<ul>
<li><code>rest_framework/pagination/numbers.html</code></li>
@ -652,13 +652,13 @@ class StandardResultsSetPagination(PageNumberPagination):
</ul>
<p>Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.</p>
<p>Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting <code>template = None</code> as an attribute on the class. You'll then need to configure your <code>DEFAULT_PAGINATION_CLASS</code> settings key to use your custom class as the default pagination style.</p>
<h4 id="low-level-api">Low-level API</h4>
<h4 id="low-level-api"><a class="toclink" href="#low-level-api">Low-level API</a></h4>
<p>The low-level API for determining if a pagination class should display the controls or not is exposed as a <code>display_page_controls</code> attribute on the pagination instance. Custom pagination classes should be set to <code>True</code> in the <code>paginate_queryset</code> method if they require the HTML pagination controls to be displayed.</p>
<p>The <code>.to_html()</code> and <code>.get_html_context()</code> methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-extensions">DRF-extensions</h2>
<h2 id="drf-extensions"><a class="toclink" href="#drf-extensions">DRF-extensions</a></h2>
<p>The <a href="http://chibisov.github.io/drf-extensions/docs/"><code>DRF-extensions</code> package</a> includes a <a href="http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin"><code>PaginateByMaxMixin</code> mixin class</a> that allows your API clients to specify <code>?page_size=max</code> to obtain the maximum allowed page size.</p>

View File

@ -437,7 +437,7 @@
<h1 id="parsers">Parsers</h1>
<h1 id="parsers"><a class="toclink" href="#parsers">Parsers</a></h1>
<blockquote>
<p>Machine interacting web services tend to use more
structured formats for sending data than form-encoded, since they're
@ -445,14 +445,14 @@ sending more complex data than simple forms</p>
<p>&mdash; Malcom Tredinnick, <a href="https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion">Django developers group</a></p>
</blockquote>
<p>REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.</p>
<h2 id="how-the-parser-is-determined">How the parser is determined</h2>
<h2 id="how-the-parser-is-determined"><a class="toclink" href="#how-the-parser-is-determined">How the parser is determined</a></h2>
<p>The set of valid parsers for a view is always defined as a list of classes. When <code>request.data</code> is accessed, REST framework will examine the <code>Content-Type</code> header on the incoming request, and determine which parser to use to parse the request content.</p>
<hr />
<p><strong>Note</strong>: When developing client applications always remember to make sure you're setting the <code>Content-Type</code> header when sending data in an HTTP request.</p>
<p>If you don't set the content type, most clients will default to using <code>'application/x-www-form-urlencoded'</code>, which may not be what you wanted.</p>
<p>As an example, if you are sending <code>json</code> encoded data using jQuery with the <a href="http://api.jquery.com/jQuery.ajax/">.ajax() method</a>, you should make sure to include the <code>contentType: 'application/json'</code> setting.</p>
<hr />
<h2 id="setting-the-parsers">Setting the parsers</h2>
<h2 id="setting-the-parsers"><a class="toclink" href="#setting-the-parsers">Setting the parsers</a></h2>
<p>The default set of parsers may be set globally, using the <code>DEFAULT_PARSER_CLASSES</code> setting. For example, the following settings would allow only requests with <code>JSON</code> content, instead of the default of JSON or form data.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
@ -485,29 +485,29 @@ def example_view(request, format=None):
return Response({'received data': request.data})
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="jsonparser">JSONParser</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="jsonparser"><a class="toclink" href="#jsonparser">JSONParser</a></h2>
<p>Parses <code>JSON</code> request content.</p>
<p><strong>.media_type</strong>: <code>application/json</code></p>
<h2 id="formparser">FormParser</h2>
<h2 id="formparser"><a class="toclink" href="#formparser">FormParser</a></h2>
<p>Parses HTML form content. <code>request.data</code> will be populated with a <code>QueryDict</code> of data.</p>
<p>You will typically want to use both <code>FormParser</code> and <code>MultiPartParser</code> together in order to fully support HTML form data.</p>
<p><strong>.media_type</strong>: <code>application/x-www-form-urlencoded</code></p>
<h2 id="multipartparser">MultiPartParser</h2>
<h2 id="multipartparser"><a class="toclink" href="#multipartparser">MultiPartParser</a></h2>
<p>Parses multipart HTML form content, which supports file uploads. Both <code>request.data</code> will be populated with a <code>QueryDict</code>.</p>
<p>You will typically want to use both <code>FormParser</code> and <code>MultiPartParser</code> together in order to fully support HTML form data.</p>
<p><strong>.media_type</strong>: <code>multipart/form-data</code></p>
<h2 id="fileuploadparser">FileUploadParser</h2>
<h2 id="fileuploadparser"><a class="toclink" href="#fileuploadparser">FileUploadParser</a></h2>
<p>Parses raw file upload content. The <code>request.data</code> property will be a dictionary with a single key <code>'file'</code> containing the uploaded file.</p>
<p>If the view used with <code>FileUploadParser</code> is called with a <code>filename</code> URL keyword argument, then that argument will be used as the filename. If it is called without a <code>filename</code> URL keyword argument, then the client must set the filename in the <code>Content-Disposition</code> HTTP header. For example <code>Content-Disposition: attachment; filename=upload.jpg</code>.</p>
<p><strong>.media_type</strong>: <code>*/*</code></p>
<h5 id="notes">Notes:</h5>
<h5 id="notes"><a class="toclink" href="#notes">Notes:</a></h5>
<ul>
<li>The <code>FileUploadParser</code> is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the <code>MultiPartParser</code> parser instead.</li>
<li>Since this parser's <code>media_type</code> matches any content type, <code>FileUploadParser</code> should generally be the only parser set on an API view.</li>
<li><code>FileUploadParser</code> respects Django's standard <code>FILE_UPLOAD_HANDLERS</code> setting, and the <code>request.upload_handlers</code> attribute. See the <a href="https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers">Django documentation</a> for more details.</li>
</ul>
<h5 id="basic-usage-example">Basic usage example:</h5>
<h5 id="basic-usage-example"><a class="toclink" href="#basic-usage-example">Basic usage example:</a></h5>
<pre><code>class FileUploadView(views.APIView):
parser_classes = (FileUploadParser,)
@ -519,19 +519,19 @@ def example_view(request, format=None):
return Response(status=204)
</code></pre>
<hr />
<h1 id="custom-parsers">Custom parsers</h1>
<h1 id="custom-parsers"><a class="toclink" href="#custom-parsers">Custom parsers</a></h1>
<p>To implement a custom parser, you should override <code>BaseParser</code>, set the <code>.media_type</code> property, and implement the <code>.parse(self, stream, media_type, parser_context)</code> method.</p>
<p>The method should return the data that will be used to populate the <code>request.data</code> property.</p>
<p>The arguments passed to <code>.parse()</code> are:</p>
<h3 id="stream">stream</h3>
<h3 id="stream"><a class="toclink" href="#stream">stream</a></h3>
<p>A stream-like object representing the body of the request.</p>
<h3 id="media_type">media_type</h3>
<h3 id="media_type"><a class="toclink" href="#media_type">media_type</a></h3>
<p>Optional. If provided, this is the media type of the incoming request content.</p>
<p>Depending on the request's <code>Content-Type:</code> header, this may be more specific than the renderer's <code>media_type</code> attribute, and may include media type parameters. For example <code>"text/plain; charset=utf-8"</code>.</p>
<h3 id="parser_context">parser_context</h3>
<h3 id="parser_context"><a class="toclink" href="#parser_context">parser_context</a></h3>
<p>Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.</p>
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>args</code>, <code>kwargs</code>.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following is an example plaintext parser that will populate the <code>request.data</code> property with a string representing the body of the request.</p>
<pre><code>class PlainTextParser(BaseParser):
"""
@ -546,11 +546,11 @@ def example_view(request, format=None):
return stream.read()
</code></pre>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="yaml">YAML</h2>
<h2 id="yaml"><a class="toclink" href="#yaml">YAML</a></h2>
<p><a href="http://jpadilla.github.io/django-rest-framework-yaml/">REST framework YAML</a> provides <a href="http://www.yaml.org/">YAML</a> parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<h4 id="installation-configuration">Installation &amp; configuration</h4>
<h4 id="installation-configuration"><a class="toclink" href="#installation-configuration">Installation &amp; configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install djangorestframework-yaml
</code></pre>
@ -564,9 +564,9 @@ def example_view(request, format=None):
),
}
</code></pre>
<h2 id="xml">XML</h2>
<h2 id="xml"><a class="toclink" href="#xml">XML</a></h2>
<p><a href="http://jpadilla.github.io/django-rest-framework-xml/">REST Framework XML</a> provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<h4 id="installation-configuration_1">Installation &amp; configuration</h4>
<h4 id="installation-configuration_1"><a class="toclink" href="#installation-configuration_1">Installation &amp; configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install djangorestframework-xml
</code></pre>
@ -580,9 +580,9 @@ def example_view(request, format=None):
),
}
</code></pre>
<h2 id="messagepack">MessagePack</h2>
<h2 id="messagepack"><a class="toclink" href="#messagepack">MessagePack</a></h2>
<p><a href="https://github.com/juanriaza/django-rest-framework-msgpack">MessagePack</a> is a fast, efficient binary serialization format. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> package which provides MessagePack renderer and parser support for REST framework.</p>
<h2 id="camelcase-json">CamelCase JSON</h2>
<h2 id="camelcase-json"><a class="toclink" href="#camelcase-json">CamelCase JSON</a></h2>
<p><a href="https://github.com/vbabiy/djangorestframework-camel-case">djangorestframework-camel-case</a> provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by <a href="https://github.com/vbabiy">Vitaly Babiy</a>.</p>

View File

@ -437,7 +437,7 @@
<h1 id="permissions">Permissions</h1>
<h1 id="permissions"><a class="toclink" href="#permissions">Permissions</a></h1>
<blockquote>
<p>Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.</p>
<p>&mdash; <a href="https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html">Apple Developer Documentation</a></p>
@ -447,7 +447,7 @@
<p>Permissions are used to grant or deny access different classes of users to different parts of the API.</p>
<p>The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the <code>IsAuthenticated</code> class in REST framework.</p>
<p>A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the <code>IsAuthenticatedOrReadOnly</code> class in REST framework.</p>
<h2 id="how-permissions-are-determined">How permissions are determined</h2>
<h2 id="how-permissions-are-determined"><a class="toclink" href="#how-permissions-are-determined">How permissions are determined</a></h2>
<p>Permissions in REST framework are always defined as a list of permission classes.</p>
<p>Before running the main body of the view each permission in the list is checked.
If any permission check fails an <code>exceptions.PermissionDenied</code> or <code>exceptions.NotAuthenticated</code> exception will be raised, and the main body of the view will not run.</p>
@ -457,7 +457,7 @@ If any permission check fails an <code>exceptions.PermissionDenied</code> or <co
<li>The request was not successfully authenticated, and the highest priority authentication class <em>does not</em> use <code>WWW-Authenticate</code> headers. <em>&mdash; An HTTP 403 Forbidden response will be returned.</em></li>
<li>The request was not successfully authenticated, and the highest priority authentication class <em>does</em> use <code>WWW-Authenticate</code> headers. <em>&mdash; An HTTP 401 Unauthorized response, with an appropriate <code>WWW-Authenticate</code> header will be returned.</em></li>
</ul>
<h2 id="object-level-permissions">Object level permissions</h2>
<h2 id="object-level-permissions"><a class="toclink" href="#object-level-permissions">Object level permissions</a></h2>
<p>REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.</p>
<p>Object level permissions are run by REST framework's generic views when <code>.get_object()</code> is called.
As with view level permissions, an <code>exceptions.PermissionDenied</code> exception will be raised if the user is not allowed to act on the given object.</p>
@ -470,10 +470,10 @@ or if you override the <code>get_object</code> method on a generic view, then yo
self.check_object_permissions(self.request, obj)
return obj
</code></pre>
<h4 id="limitations-of-object-level-permissions">Limitations of object level permissions</h4>
<h4 id="limitations-of-object-level-permissions"><a class="toclink" href="#limitations-of-object-level-permissions">Limitations of object level permissions</a></h4>
<p>For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.</p>
<p>Often when you're using object level permissions you'll also want to <a href="../filtering/">filter the queryset</a> appropriately, to ensure that users only have visibility onto instances that they are permitted to view.</p>
<h2 id="setting-the-permission-policy">Setting the permission policy</h2>
<h2 id="setting-the-permission-policy"><a class="toclink" href="#setting-the-permission-policy">Setting the permission policy</a></h2>
<p>The default permission policy may be set globally, using the <code>DEFAULT_PERMISSION_CLASSES</code> setting. For example.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
@ -515,20 +515,20 @@ def example_view(request, format=None):
return Response(content)
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="allowany">AllowAny</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="allowany"><a class="toclink" href="#allowany">AllowAny</a></h2>
<p>The <code>AllowAny</code> permission class will allow unrestricted access, <strong>regardless of if the request was authenticated or unauthenticated</strong>.</p>
<p>This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.</p>
<h2 id="isauthenticated">IsAuthenticated</h2>
<h2 id="isauthenticated"><a class="toclink" href="#isauthenticated">IsAuthenticated</a></h2>
<p>The <code>IsAuthenticated</code> permission class will deny permission to any unauthenticated user, and allow permission otherwise.</p>
<p>This permission is suitable if you want your API to only be accessible to registered users.</p>
<h2 id="isadminuser">IsAdminUser</h2>
<h2 id="isadminuser"><a class="toclink" href="#isadminuser">IsAdminUser</a></h2>
<p>The <code>IsAdminUser</code> permission class will deny permission to any user, unless <code>user.is_staff</code> is <code>True</code> in which case permission will be allowed.</p>
<p>This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.</p>
<h2 id="isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</h2>
<h2 id="isauthenticatedorreadonly"><a class="toclink" href="#isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</a></h2>
<p>The <code>IsAuthenticatedOrReadOnly</code> will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; <code>GET</code>, <code>HEAD</code> or <code>OPTIONS</code>.</p>
<p>This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.</p>
<h2 id="djangomodelpermissions">DjangoModelPermissions</h2>
<h2 id="djangomodelpermissions"><a class="toclink" href="#djangomodelpermissions">DjangoModelPermissions</a></h2>
<p>This permission class ties into Django's standard <code>django.contrib.auth</code> <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions">model permissions</a>. This permission must only be applied to views that has a <code>.queryset</code> property set. Authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant model permissions</em> assigned.</p>
<ul>
<li><code>POST</code> requests require the user to have the <code>add</code> permission on the model.</li>
@ -537,13 +537,13 @@ def example_view(request, format=None):
</ul>
<p>The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a <code>view</code> model permission for <code>GET</code> requests.</p>
<p>To use custom model permissions, override <code>DjangoModelPermissions</code> and set the <code>.perms_map</code> property. Refer to the source code for details.</p>
<h4 id="using-with-views-that-do-not-include-a-queryset-attribute">Using with views that do not include a <code>queryset</code> attribute.</h4>
<h4 id="using-with-views-that-do-not-include-a-queryset-attribute"><a class="toclink" href="#using-with-views-that-do-not-include-a-queryset-attribute">Using with views that do not include a <code>queryset</code> attribute.</a></h4>
<p>If you're using this permission with a view that uses an overridden <code>get_queryset()</code> method there may not be a <code>queryset</code> attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example:</p>
<pre><code>queryset = User.objects.none() # Required for DjangoModelPermissions
</code></pre>
<h2 id="djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</h2>
<h2 id="djangomodelpermissionsoranonreadonly"><a class="toclink" href="#djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</a></h2>
<p>Similar to <code>DjangoModelPermissions</code>, but also allows unauthenticated users to have read-only access to the API.</p>
<h2 id="djangoobjectpermissions">DjangoObjectPermissions</h2>
<h2 id="djangoobjectpermissions"><a class="toclink" href="#djangoobjectpermissions">DjangoObjectPermissions</a></h2>
<p>This permission class ties into Django's standard <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions">object permissions framework</a> that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as <a href="https://github.com/lukaszb/django-guardian">django-guardian</a>.</p>
<p>As with <code>DjangoModelPermissions</code>, this permission must only be applied to views that have a <code>.queryset</code> property or <code>.get_queryset()</code> method. Authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant per-object permissions</em> and <em>relevant model permissions</em> assigned.</p>
<ul>
@ -557,7 +557,7 @@ def example_view(request, format=None):
<p><strong>Note</strong>: If you need object level <code>view</code> permissions for <code>GET</code>, <code>HEAD</code> and <code>OPTIONS</code> requests, you'll want to consider also adding the <code>DjangoObjectPermissionsFilter</code> class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.</p>
<hr />
<hr />
<h1 id="custom-permissions">Custom permissions</h1>
<h1 id="custom-permissions"><a class="toclink" href="#custom-permissions">Custom permissions</a></h1>
<p>To implement a custom permission, override <code>BasePermission</code> and implement either, or both, of the following methods:</p>
<ul>
<li><code>.has_permission(self, request, view)</code></li>
@ -582,7 +582,7 @@ class CustomerAccessPermission(permissions.BasePermission):
def has_permission(self, request, view):
...
</code></pre>
<h2 id="examples">Examples</h2>
<h2 id="examples"><a class="toclink" href="#examples">Examples</a></h2>
<p>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.</p>
<pre><code>from rest_framework import permissions
@ -615,13 +615,13 @@ class BlacklistPermission(permissions.BasePermission):
<p>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 <code>self.check_object_permissions(request, obj)</code> from the view once you have the object instance. This call will raise an appropriate <code>APIException</code> if any object-level permission checks fail, and will otherwise simply return.</p>
<p>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 <a href="../filtering/">filtering documentation</a> for more details.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="composed-permissions">Composed Permissions</h2>
<h2 id="composed-permissions"><a class="toclink" href="#composed-permissions">Composed Permissions</a></h2>
<p>The <a href="https://github.com/niwibe/djangorestframework-composed-permissions">Composed Permissions</a> package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.</p>
<h2 id="rest-condition">REST Condition</h2>
<h2 id="rest-condition"><a class="toclink" href="#rest-condition">REST Condition</a></h2>
<p>The <a href="https://github.com/caxap/rest_condition">REST Condition</a> package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.</p>
<h2 id="dry-rest-permissions">DRY Rest Permissions</h2>
<h2 id="dry-rest-permissions"><a class="toclink" href="#dry-rest-permissions">DRY Rest Permissions</a></h2>
<p>The <a href="https://github.com/Helioscene/dry-rest-permissions">DRY Rest Permissions</a> package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrive per user.</p>

View File

@ -469,7 +469,7 @@
<h1 id="serializer-relations">Serializer relations</h1>
<h1 id="serializer-relations"><a class="toclink" href="#serializer-relations">Serializer relations</a></h1>
<blockquote>
<p>Bad programmers worry about the code.
Good programmers worry about data structures and their relationships.</p>
@ -479,7 +479,7 @@ Good programmers worry about data structures and their relationships.</p>
<hr />
<p><strong>Note:</strong> The relational fields are declared in <code>relations.py</code>, but by convention you should import them from the <code>serializers</code> module, using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.&lt;FieldName&gt;</code>.</p>
<hr />
<h4 id="inspecting-relationships">Inspecting relationships.</h4>
<h4 id="inspecting-relationships"><a class="toclink" href="#inspecting-relationships">Inspecting relationships.</a></h4>
<p>When using the <code>ModelSerializer</code> class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.</p>
<p>To do so, open the Django shell, using <code>python manage.py shell</code>, then import the serializer class, instantiate it, and print the object representation…</p>
<pre><code>&gt;&gt;&gt; from myapp.serializers import AccountSerializer
@ -490,7 +490,7 @@ AccountSerializer():
name = CharField(allow_blank=True, max_length=100, required=False)
owner = PrimaryKeyRelatedField(queryset=User.objects.all())
</code></pre>
<h1 id="api-reference">API Reference</h1>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<p>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.</p>
<pre><code>class Album(models.Model):
album_name = models.CharField(max_length=100)
@ -509,7 +509,7 @@ class Track(models.Model):
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
</code></pre>
<h2 id="stringrelatedfield">StringRelatedField</h2>
<h2 id="stringrelatedfield"><a class="toclink" href="#stringrelatedfield">StringRelatedField</a></h2>
<p><code>StringRelatedField</code> may be used to represent the target of the relationship using its <code>__unicode__</code> method.</p>
<p>For example, the following serializer.</p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
@ -536,7 +536,7 @@ class Track(models.Model):
<ul>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
</ul>
<h2 id="primarykeyrelatedfield">PrimaryKeyRelatedField</h2>
<h2 id="primarykeyrelatedfield"><a class="toclink" href="#primarykeyrelatedfield">PrimaryKeyRelatedField</a></h2>
<p><code>PrimaryKeyRelatedField</code> may be used to represent the target of the relationship using its primary key.</p>
<p>For example, the following serializer:</p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
@ -566,7 +566,7 @@ class Track(models.Model):
<li><code>allow_null</code> - If set to <code>True</code>, the field will accept values of <code>None</code> or the empty string for nullable relationships. Defaults to <code>False</code>.</li>
<li><code>pk_field</code> - Set to a field to control serialization/deserialization of the primary key's value. For example, <code>pk_field=UUIDField(format='hex')</code> would serialize a UUID primary key into its compact hex representation.</li>
</ul>
<h2 id="hyperlinkedrelatedfield">HyperlinkedRelatedField</h2>
<h2 id="hyperlinkedrelatedfield"><a class="toclink" href="#hyperlinkedrelatedfield">HyperlinkedRelatedField</a></h2>
<p><code>HyperlinkedRelatedField</code> may be used to represent the target of the relationship using a hyperlink.</p>
<p>For example, the following serializer:</p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
@ -608,7 +608,7 @@ class Track(models.Model):
<li><code>lookup_url_kwarg</code> - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as <code>lookup_field</code>.</li>
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
</ul>
<h2 id="slugrelatedfield">SlugRelatedField</h2>
<h2 id="slugrelatedfield"><a class="toclink" href="#slugrelatedfield">SlugRelatedField</a></h2>
<p><code>SlugRelatedField</code> may be used to represent the target of the relationship using a field on the target.</p>
<p>For example, the following serializer:</p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
@ -643,7 +643,7 @@ class Track(models.Model):
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>allow_null</code> - If set to <code>True</code>, the field will accept values of <code>None</code> or the empty string for nullable relationships. Defaults to <code>False</code>.</li>
</ul>
<h2 id="hyperlinkedidentityfield">HyperlinkedIdentityField</h2>
<h2 id="hyperlinkedidentityfield"><a class="toclink" href="#hyperlinkedidentityfield">HyperlinkedIdentityField</a></h2>
<p>This field can be applied as an identity relationship, such as the <code>'url'</code> field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:</p>
<pre><code>class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
@ -668,10 +668,10 @@ class Track(models.Model):
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
</ul>
<hr />
<h1 id="nested-relationships">Nested relationships</h1>
<h1 id="nested-relationships"><a class="toclink" href="#nested-relationships">Nested relationships</a></h1>
<p>Nested relationships can be expressed by using serializers as fields.</p>
<p>If the field is used to represent a to-many relationship, you should add the <code>many=True</code> flag to the serializer field.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>For example, the following serializer:</p>
<pre><code>class TrackSerializer(serializers.ModelSerializer):
class Meta:
@ -706,7 +706,7 @@ class AlbumSerializer(serializers.ModelSerializer):
],
}
</code></pre>
<h1 id="writable-nested-serializers">Writable nested serializers</h1>
<h1 id="writable-nested-serializers"><a class="toclink" href="#writable-nested-serializers">Writable nested serializers</a></h1>
<p>By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create <code>create()</code> and/or <code>update()</code> methods in order to explicitly specify how the child relationships should be saved.</p>
<pre><code>class TrackSerializer(serializers.ModelSerializer):
class Meta:
@ -742,10 +742,10 @@ True
&gt;&gt;&gt; serializer.save()
&lt;Album: Album object&gt;
</code></pre>
<h1 id="custom-relational-fields">Custom relational fields</h1>
<h1 id="custom-relational-fields"><a class="toclink" href="#custom-relational-fields">Custom relational fields</a></h1>
<p>To implement a custom relational field, you should override <code>RelatedField</code>, and implement the <code>.to_representation(self, value)</code> method. This method takes the target of the field as the <code>value</code> argument, and should return the representation that should be used to serialize the target. The <code>value</code> argument will typically be a model instance.</p>
<p>If you want to implement a read-write relational field, you must also implement the <code>.to_internal_value(self, data)</code> method.</p>
<h2 id="example_1">Example</h2>
<h2 id="example_1"><a class="toclink" href="#example_1">Example</a></h2>
<p>For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.</p>
<pre><code>import time
@ -774,7 +774,7 @@ class AlbumSerializer(serializers.ModelSerializer):
}
</code></pre>
<hr />
<h1 id="custom-hyperlinked-fields">Custom hyperlinked fields</h1>
<h1 id="custom-hyperlinked-fields"><a class="toclink" href="#custom-hyperlinked-fields">Custom hyperlinked fields</a></h1>
<p>In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.</p>
<p>You can achieve this by overriding <code>HyperlinkedRelatedField</code>. There are two methods that may be overridden:</p>
<p><strong>get_url(self, obj, view_name, request, format)</strong></p>
@ -785,7 +785,7 @@ attributes are not configured to correctly match the URL conf.</p>
<p>If you want to support a writable hyperlinked field then you'll also want to override <code>get_object</code>, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.</p>
<p>The return value of this method should the object that corresponds to the matched URL conf arguments.</p>
<p>May raise an <code>ObjectDoesNotExist</code> exception.</p>
<h2 id="example_2">Example</h2>
<h2 id="example_2"><a class="toclink" href="#example_2">Example</a></h2>
<p>Say we have a URL for a customer object that takes two keyword arguments, like so:</p>
<pre><code>/api/&lt;organization_slug&gt;/customers/&lt;customer_pk&gt;/
</code></pre>
@ -804,7 +804,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):
'organization_slug': obj.organization.slug,
'customer_pk': obj.pk
}
return reverse(view_name, url_kwargs, request=request, format=format)
return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
def get_object(self, view_name, view_args, view_kwargs):
lookup_kwargs = {
@ -816,20 +816,20 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):
<p>Note that if you wanted to use this style together with the generic views then you'd also need to override <code>.get_object</code> on the view in order to get the correct lookup behavior.</p>
<p>Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.</p>
<hr />
<h1 id="further-notes">Further notes</h1>
<h2 id="the-queryset-argument">The <code>queryset</code> argument</h2>
<h1 id="further-notes"><a class="toclink" href="#further-notes">Further notes</a></h1>
<h2 id="the-queryset-argument"><a class="toclink" href="#the-queryset-argument">The <code>queryset</code> argument</a></h2>
<p>The <code>queryset</code> argument is only ever required for <em>writable</em> relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.</p>
<p>In version 2.x a serializer class could <em>sometimes</em> automatically determine the <code>queryset</code> argument <em>if</em> a <code>ModelSerializer</code> class was being used.</p>
<p>This behavior is now replaced with <em>always</em> using an explicit <code>queryset</code> argument for writable relational fields.</p>
<p>Doing so reduces the amount of hidden 'magic' that <code>ModelSerializer</code> provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the <code>ModelSerializer</code> shortcut, or using fully explicit <code>Serializer</code> classes.</p>
<h2 id="customizing-the-html-display">Customizing the HTML display</h2>
<h2 id="customizing-the-html-display"><a class="toclink" href="#customizing-the-html-display">Customizing the HTML display</a></h2>
<p>The built-in <code>__str__</code> method of the model will be used to generate string representations of the objects used to populate the <code>choices</code> property. These choices are used to populate select HTML inputs in the browsable API.</p>
<p>To provide customized representations for such inputs, override <code>display_value()</code> of a <code>RelatedField</code> subclass. This method will receive a model object, and should return a string suitable for representing it. For example:</p>
<pre><code>class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
return 'Track: %s' % (instance.title)
</code></pre>
<h2 id="select-field-cutoffs">Select field cutoffs</h2>
<h2 id="select-field-cutoffs"><a class="toclink" href="#select-field-cutoffs">Select field cutoffs</a></h2>
<p>When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.</p>
<p>This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.</p>
<p>There are two keyword arguments you can use to control this behavior:</p>
@ -844,7 +844,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):
style={'base_template': 'input.html'}
)
</code></pre>
<h2 id="reverse-relations">Reverse relations</h2>
<h2 id="reverse-relations"><a class="toclink" href="#reverse-relations">Reverse relations</a></h2>
<p>Note that reverse relationships are not automatically included by the <code>ModelSerializer</code> and <code>HyperlinkedModelSerializer</code> classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:</p>
<pre><code>class AlbumSerializer(serializers.ModelSerializer):
class Meta:
@ -861,7 +861,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):
fields = ('track_set', ...)
</code></pre>
<p>See the Django documentation on <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">reverse relationships</a> for more details.</p>
<h2 id="generic-relationships">Generic relationships</h2>
<h2 id="generic-relationships"><a class="toclink" href="#generic-relationships">Generic relationships</a></h2>
<p>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.</p>
<p>For example, given the following model for a tag, which has a generic relationship with other arbitrary models:</p>
<pre><code>class TaggedItem(models.Model):
@ -927,16 +927,16 @@ class Note(models.Model):
</code></pre>
<p>Note that reverse generic keys, expressed using the <code>GenericRelation</code> field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.</p>
<p>For more information see <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1">the Django documentation on generic relations</a>.</p>
<h2 id="manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</h2>
<h2 id="manytomanyfields-with-a-through-model"><a class="toclink" href="#manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</a></h2>
<p>By default, relational fields that target a <code>ManyToManyField</code> with a
<code>through</code> model specified are set to read-only.</p>
<p>If you explicitly specify a relational field pointing to a
<code>ManyToManyField</code> with a through model, be sure to set <code>read_only</code>
to <code>True</code>.</p>
<hr />
<h1 id="third-party-packages">Third Party Packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third Party Packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers">DRF Nested Routers</h2>
<h2 id="drf-nested-routers"><a class="toclink" href="#drf-nested-routers">DRF Nested Routers</a></h2>
<p>The <a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>

View File

@ -495,17 +495,17 @@
<h1 id="renderers">Renderers</h1>
<h1 id="renderers"><a class="toclink" href="#renderers">Renderers</a></h1>
<blockquote>
<p>Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process">Django documentation</a></p>
</blockquote>
<p>REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.</p>
<h2 id="how-the-renderer-is-determined">How the renderer is determined</h2>
<h2 id="how-the-renderer-is-determined"><a class="toclink" href="#how-the-renderer-is-determined">How the renderer is determined</a></h2>
<p>The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.</p>
<p>The basic process of content negotiation involves examining the request's <code>Accept</code> header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL <code>http://example.com/api/users_count.json</code> might be an endpoint that always returns JSON data.</p>
<p>For more information see the documentation on <a href="../content-negotiation/">content negotiation</a>.</p>
<h2 id="setting-the-renderers">Setting the renderers</h2>
<h2 id="setting-the-renderers"><a class="toclink" href="#setting-the-renderers">Setting the renderers</a></h2>
<p>The default set of renderers may be set globally, using the <code>DEFAULT_RENDERER_CLASSES</code> setting. For example, the following settings would use <code>JSON</code> as the main media type and also include the self describing API.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
@ -543,13 +543,13 @@ def user_count_view(request, format=None):
content = {'user_count': user_count}
return Response(content)
</code></pre>
<h2 id="ordering-of-renderer-classes">Ordering of renderer classes</h2>
<h2 id="ordering-of-renderer-classes"><a class="toclink" href="#ordering-of-renderer-classes">Ordering of renderer classes</a></h2>
<p>It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an <code>Accept: */*</code> header, or not including an <code>Accept</code> header at all, then REST framework will select the first renderer in the list to use for the response.</p>
<p>For example if your API serves JSON responses and the HTML browsable API, you might want to make <code>JSONRenderer</code> your default renderer, in order to send <code>JSON</code> responses to clients that do not specify an <code>Accept</code> header.</p>
<p>If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making <code>TemplateHTMLRenderer</code> your default renderer, in order to play nicely with older browsers that send <a href="http://www.gethifi.com/blog/browser-rest-http-accept-headers">broken accept headers</a>.</p>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="jsonrenderer">JSONRenderer</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="jsonrenderer"><a class="toclink" href="#jsonrenderer">JSONRenderer</a></h2>
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
<p>Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:</p>
<pre><code>{"unicode black star":"★","value":999}
@ -564,7 +564,7 @@ def user_count_view(request, format=None):
<p><strong>.media_type</strong>: <code>application/json</code></p>
<p><strong>.format</strong>: <code>'.json'</code></p>
<p><strong>.charset</strong>: <code>None</code></p>
<h2 id="templatehtmlrenderer">TemplateHTMLRenderer</h2>
<h2 id="templatehtmlrenderer"><a class="toclink" href="#templatehtmlrenderer">TemplateHTMLRenderer</a></h2>
<p>Renders data to HTML, using Django's standard template rendering.
Unlike other renderers, the data passed to the <code>Response</code> does not need to be serialized. Also, unlike other renderers, you may want to include a <code>template_name</code> argument when creating the <code>Response</code>.</p>
<p>The TemplateHTMLRenderer will create a <code>RequestContext</code>, using the <code>response.data</code> as the context dict, and determine a template name to use to render the context.</p>
@ -592,7 +592,7 @@ Unlike other renderers, the data passed to the <code>Response</code> does not ne
<p><strong>.format</strong>: <code>'.html'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<p>See also: <code>StaticHTMLRenderer</code></p>
<h2 id="statichtmlrenderer">StaticHTMLRenderer</h2>
<h2 id="statichtmlrenderer"><a class="toclink" href="#statichtmlrenderer">StaticHTMLRenderer</a></h2>
<p>A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.</p>
<p>An example of a view that uses <code>StaticHTMLRenderer</code>:</p>
<pre><code>@api_view(('GET',))
@ -606,7 +606,7 @@ def simple_html_view(request):
<p><strong>.format</strong>: <code>'.html'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<p>See also: <code>TemplateHTMLRenderer</code></p>
<h2 id="browsableapirenderer">BrowsableAPIRenderer</h2>
<h2 id="browsableapirenderer"><a class="toclink" href="#browsableapirenderer">BrowsableAPIRenderer</a></h2>
<p>Renders data into HTML for the Browsable API:</p>
<p><img alt="The BrowsableAPIRenderer" src="../../img/quickstart.png" /></p>
<p>This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.</p>
@ -614,13 +614,13 @@ def simple_html_view(request):
<p><strong>.format</strong>: <code>'.api'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<p><strong>.template</strong>: <code>'rest_framework/api.html'</code></p>
<h4 id="customizing-browsableapirenderer">Customizing BrowsableAPIRenderer</h4>
<h4 id="customizing-browsableapirenderer"><a class="toclink" href="#customizing-browsableapirenderer">Customizing BrowsableAPIRenderer</a></h4>
<p>By default the response content will be rendered with the highest priority renderer apart from <code>BrowsableAPIRenderer</code>. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the <code>get_default_renderer()</code> method. For example:</p>
<pre><code>class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_default_renderer(self, view):
return JSONRenderer()
</code></pre>
<h2 id="adminrenderer">AdminRenderer</h2>
<h2 id="adminrenderer"><a class="toclink" href="#adminrenderer">AdminRenderer</a></h2>
<p>Renders data into HTML for an admin-like display:</p>
<p><img alt="The AdminRender view" src="../../img/admin.png" /></p>
<p>This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.</p>
@ -629,7 +629,7 @@ def simple_html_view(request):
<p><strong>.format</strong>: <code>'.admin'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<p><strong>.template</strong>: <code>'rest_framework/admin.html'</code></p>
<h2 id="htmlformrenderer">HTMLFormRenderer</h2>
<h2 id="htmlformrenderer"><a class="toclink" href="#htmlformrenderer">HTMLFormRenderer</a></h2>
<p>Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <code>&lt;form&gt;</code> tags, a hidden CSRF input or any submit buttons.</p>
<p>This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the <code>render_form</code> template tag.</p>
<pre><code>{% load rest_framework %}
@ -645,25 +645,25 @@ def simple_html_view(request):
<p><strong>.format</strong>: <code>'.form'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<p><strong>.template</strong>: <code>'rest_framework/horizontal/form.html'</code></p>
<h2 id="multipartrenderer">MultiPartRenderer</h2>
<h2 id="multipartrenderer"><a class="toclink" href="#multipartrenderer">MultiPartRenderer</a></h2>
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <a href="../testing/">test client and test request factory</a>.</p>
<p><strong>.media_type</strong>: <code>multipart/form-data; boundary=BoUnDaRyStRiNg</code></p>
<p><strong>.format</strong>: <code>'.multipart'</code></p>
<p><strong>.charset</strong>: <code>utf-8</code></p>
<hr />
<h1 id="custom-renderers">Custom renderers</h1>
<h1 id="custom-renderers"><a class="toclink" href="#custom-renderers">Custom renderers</a></h1>
<p>To implement a custom renderer, you should override <code>BaseRenderer</code>, set the <code>.media_type</code> and <code>.format</code> properties, and implement the <code>.render(self, data, media_type=None, renderer_context=None)</code> method.</p>
<p>The method should return a bytestring, which will be used as the body of the HTTP response.</p>
<p>The arguments passed to the <code>.render()</code> method are:</p>
<h3 id="data"><code>data</code></h3>
<h3 id="data"><a class="toclink" href="#data"><code>data</code></a></h3>
<p>The request data, as set by the <code>Response()</code> instantiation.</p>
<h3 id="media_typenone"><code>media_type=None</code></h3>
<h3 id="media_typenone"><a class="toclink" href="#media_typenone"><code>media_type=None</code></a></h3>
<p>Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.</p>
<p>Depending on the client's <code>Accept:</code> header, this may be more specific than the renderer's <code>media_type</code> attribute, and may include media type parameters. For example <code>"application/json; nested=true"</code>.</p>
<h3 id="renderer_contextnone"><code>renderer_context=None</code></h3>
<h3 id="renderer_contextnone"><a class="toclink" href="#renderer_contextnone"><code>renderer_context=None</code></a></h3>
<p>Optional. If provided, this is a dictionary of contextual information provided by the view.</p>
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>response</code>, <code>args</code>, <code>kwargs</code>.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following is an example plaintext renderer that will return a response with the <code>data</code> parameter as the content of the response.</p>
<pre><code>from django.utils.encoding import smart_unicode
from rest_framework import renderers
@ -676,7 +676,7 @@ class PlainTextRenderer(renderers.BaseRenderer):
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
</code></pre>
<h2 id="setting-the-character-set">Setting the character set</h2>
<h2 id="setting-the-character-set"><a class="toclink" href="#setting-the-character-set">Setting the character set</a></h2>
<p>By default renderer classes are assumed to be using the <code>UTF-8</code> encoding. To use a different encoding, set the <code>charset</code> attribute on the renderer.</p>
<pre><code>class PlainTextRenderer(renderers.BaseRenderer):
media_type = 'text/plain'
@ -699,7 +699,7 @@ class PlainTextRenderer(renderers.BaseRenderer):
return data
</code></pre>
<hr />
<h1 id="advanced-renderer-usage">Advanced renderer usage</h1>
<h1 id="advanced-renderer-usage"><a class="toclink" href="#advanced-renderer-usage">Advanced renderer usage</a></h1>
<p>You can do some pretty flexible things using REST framework's renderers. Some examples...</p>
<ul>
<li>Provide either flat or nested representations from the same endpoint, depending on the requested media type.</li>
@ -707,7 +707,7 @@ class PlainTextRenderer(renderers.BaseRenderer):
<li>Specify multiple types of HTML representation for API clients to use.</li>
<li>Underspecify a renderer's media type, such as using <code>media_type = 'image/*'</code>, and use the <code>Accept</code> header to vary the encoding of the response.</li>
</ul>
<h2 id="varying-behaviour-by-media-type">Varying behaviour by media type</h2>
<h2 id="varying-behaviour-by-media-type"><a class="toclink" href="#varying-behaviour-by-media-type">Varying behaviour by media type</a></h2>
<p>In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access <code>request.accepted_renderer</code> to determine the negotiated renderer that will be used for the response.</p>
<p>For example:</p>
<pre><code>@api_view(('GET',))
@ -731,17 +731,17 @@ def list_users(request):
data = serializer.data
return Response(data)
</code></pre>
<h2 id="underspecifying-the-media-type">Underspecifying the media type</h2>
<h2 id="underspecifying-the-media-type"><a class="toclink" href="#underspecifying-the-media-type">Underspecifying the media type</a></h2>
<p>In some cases you might want a renderer to serve a range of media types.
In this case you can underspecify the media types it should respond to, by using a <code>media_type</code> value such as <code>image/*</code>, or <code>*/*</code>.</p>
<p>If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the <code>content_type</code> attribute. For example:</p>
<pre><code>return Response(data, content_type='image/png')
</code></pre>
<h2 id="designing-your-media-types">Designing your media types</h2>
<h2 id="designing-your-media-types"><a class="toclink" href="#designing-your-media-types">Designing your media types</a></h2>
<p>For the purposes of many Web APIs, simple <code>JSON</code> responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and <a href="http://timelessrepo.com/haters-gonna-hateoas">HATEOAS</a> you'll need to consider the design and usage of your media types in more detail.</p>
<p>In <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">the words of Roy Fielding</a>, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".</p>
<p>For good examples of custom media types, see GitHub's use of a custom <a href="http://developer.github.com/v3/media/">application/vnd.github+json</a> media type, and Mike Amundsen's IANA approved <a href="http://www.amundsen.com/media-types/collection/">application/vnd.collection+json</a> JSON-based hypermedia.</p>
<h2 id="html-error-views">HTML error views</h2>
<h2 id="html-error-views"><a class="toclink" href="#html-error-views">HTML error views</a></h2>
<p>Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an <code>Http404</code> or <code>PermissionDenied</code> exception, or a subclass of <code>APIException</code>.</p>
<p>If you're using either the <code>TemplateHTMLRenderer</code> or the <code>StaticHTMLRenderer</code> and an exception is raised, the behavior is slightly different, and mirrors <a href="https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views">Django's default handling of error views</a>.</p>
<p>Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.</p>
@ -753,11 +753,11 @@ In this case you can underspecify the media types it should respond to, by using
<p>Templates will render with a <code>RequestContext</code> which includes the <code>status_code</code> and <code>details</code> keys.</p>
<p><strong>Note</strong>: If <code>DEBUG=True</code>, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="yaml">YAML</h2>
<h2 id="yaml"><a class="toclink" href="#yaml">YAML</a></h2>
<p><a href="http://jpadilla.github.io/django-rest-framework-yaml/">REST framework YAML</a> provides <a href="http://www.yaml.org/">YAML</a> parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<h4 id="installation-configuration">Installation &amp; configuration</h4>
<h4 id="installation-configuration"><a class="toclink" href="#installation-configuration">Installation &amp; configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install djangorestframework-yaml
</code></pre>
@ -771,9 +771,9 @@ In this case you can underspecify the media types it should respond to, by using
),
}
</code></pre>
<h2 id="xml">XML</h2>
<h2 id="xml"><a class="toclink" href="#xml">XML</a></h2>
<p><a href="http://jpadilla.github.io/django-rest-framework-xml/">REST Framework XML</a> provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<h4 id="installation-configuration_1">Installation &amp; configuration</h4>
<h4 id="installation-configuration_1"><a class="toclink" href="#installation-configuration_1">Installation &amp; configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install djangorestframework-xml
</code></pre>
@ -787,13 +787,13 @@ In this case you can underspecify the media types it should respond to, by using
),
}
</code></pre>
<h2 id="jsonp">JSONP</h2>
<h2 id="jsonp"><a class="toclink" href="#jsonp">JSONP</a></h2>
<p><a href="http://jpadilla.github.io/django-rest-framework-jsonp/">REST framework JSONP</a> provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<hr />
<p><strong>Warning</strong>: If you require cross-domain AJAX requests, you should generally be using the more modern approach of <a href="http://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors/">CORS documentation</a> for more details.</p>
<p>The <code>jsonp</code> approach is essentially a browser hack, and is <a href="http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use">only appropriate for globally readable API endpoints</a>, where <code>GET</code> requests are unauthenticated and do not require any user permissions.</p>
<hr />
<h4 id="installation-configuration_2">Installation &amp; configuration</h4>
<h4 id="installation-configuration_2"><a class="toclink" href="#installation-configuration_2">Installation &amp; configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install djangorestframework-jsonp
</code></pre>
@ -804,15 +804,15 @@ In this case you can underspecify the media types it should respond to, by using
),
}
</code></pre>
<h2 id="messagepack">MessagePack</h2>
<h2 id="messagepack"><a class="toclink" href="#messagepack">MessagePack</a></h2>
<p><a href="http://msgpack.org/">MessagePack</a> is a fast, efficient binary serialization format. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> package which provides MessagePack renderer and parser support for REST framework.</p>
<h2 id="csv">CSV</h2>
<h2 id="csv"><a class="toclink" href="#csv">CSV</a></h2>
<p>Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. <a href="https://github.com/mjumbewu">Mjumbe Poe</a> maintains the <a href="https://github.com/mjumbewu/django-rest-framework-csv">djangorestframework-csv</a> package which provides CSV renderer support for REST framework.</p>
<h2 id="ultrajson">UltraJSON</h2>
<h2 id="ultrajson"><a class="toclink" href="#ultrajson">UltraJSON</a></h2>
<p><a href="https://github.com/esnme/ultrajson">UltraJSON</a> is an optimized C JSON encoder which can give significantly faster JSON rendering. <a href="https://github.com/hzy">Jacob Haslehurst</a> maintains the <a href="https://github.com/gizmag/drf-ujson-renderer">drf-ujson-renderer</a> package which implements JSON rendering using the UJSON package.</p>
<h2 id="camelcase-json">CamelCase JSON</h2>
<h2 id="camelcase-json"><a class="toclink" href="#camelcase-json">CamelCase JSON</a></h2>
<p><a href="https://github.com/vbabiy/djangorestframework-camel-case">djangorestframework-camel-case</a> provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by <a href="https://github.com/vbabiy">Vitaly Babiy</a>.</p>
<h2 id="pandas-csv-excel-png">Pandas (CSV, Excel, PNG)</h2>
<h2 id="pandas-csv-excel-png"><a class="toclink" href="#pandas-csv-excel-png">Pandas (CSV, Excel, PNG)</a></h2>
<p><a href="https://github.com/wq/django-rest-pandas">Django REST Pandas</a> provides a serializer and renderers that support additional data processing and output via the <a href="http://pandas.pydata.org/">Pandas</a> DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both <code>.xls</code> and <code>.xlsx</code>), and a number of <a href="https://github.com/wq/django-rest-pandas#supported-formats">other formats</a>. It is maintained by <a href="https://github.com/sheppard">S. Andrew Sheppard</a> as part of the <a href="https://github.com/wq">wq Project</a>.</p>

View File

@ -437,16 +437,16 @@
<h1 id="requests">Requests</h1>
<h1 id="requests"><a class="toclink" href="#requests">Requests</a></h1>
<blockquote>
<p>If you're doing REST-based web service stuff ... you should ignore request.POST.</p>
<p>&mdash; Malcom Tredinnick, <a href="https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion">Django developers group</a></p>
</blockquote>
<p>REST framework's <code>Request</code> class extends the standard <code>HttpRequest</code>, adding support for REST framework's flexible request parsing and request authentication.</p>
<hr />
<h1 id="request-parsing">Request parsing</h1>
<h1 id="request-parsing"><a class="toclink" href="#request-parsing">Request parsing</a></h1>
<p>REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.</p>
<h2 id="data">.data</h2>
<h2 id="data"><a class="toclink" href="#data">.data</a></h2>
<p><code>request.data</code> returns the parsed content of the request body. This is similar to the standard <code>request.POST</code> and <code>request.FILES</code> attributes except that:</p>
<ul>
<li>It includes all parsed content, including <em>file and non-file</em> inputs.</li>
@ -454,60 +454,60 @@
<li>It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.</li>
</ul>
<p>For more details see the <a href="../parsers/">parsers documentation</a>.</p>
<h2 id="query_params">.query_params</h2>
<h2 id="query_params"><a class="toclink" href="#query_params">.query_params</a></h2>
<p><code>request.query_params</code> is a more correctly named synonym for <code>request.GET</code>.</p>
<p>For clarity inside your code, we recommend using <code>request.query_params</code> instead of the Django's standard <code>request.GET</code>. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just <code>GET</code> requests.</p>
<h2 id="parsers">.parsers</h2>
<h2 id="parsers"><a class="toclink" href="#parsers">.parsers</a></h2>
<p>The <code>APIView</code> class or <code>@api_view</code> decorator will ensure that this property is automatically set to a list of <code>Parser</code> instances, based on the <code>parser_classes</code> set on the view or based on the <code>DEFAULT_PARSER_CLASSES</code> setting.</p>
<p>You won't typically need to access this property.</p>
<hr />
<p><strong>Note:</strong> If a client sends malformed content, then accessing <code>request.data</code> may raise a <code>ParseError</code>. By default REST framework's <code>APIView</code> class or <code>@api_view</code> decorator will catch the error and return a <code>400 Bad Request</code> response.</p>
<p>If a client sends a request with a content-type that cannot be parsed then a <code>UnsupportedMediaType</code> exception will be raised, which by default will be caught and return a <code>415 Unsupported Media Type</code> response.</p>
<hr />
<h1 id="content-negotiation">Content negotiation</h1>
<h1 id="content-negotiation"><a class="toclink" href="#content-negotiation">Content negotiation</a></h1>
<p>The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.</p>
<h2 id="accepted_renderer">.accepted_renderer</h2>
<h2 id="accepted_renderer"><a class="toclink" href="#accepted_renderer">.accepted_renderer</a></h2>
<p>The renderer instance what was selected by the content negotiation stage.</p>
<h2 id="accepted_media_type">.accepted_media_type</h2>
<h2 id="accepted_media_type"><a class="toclink" href="#accepted_media_type">.accepted_media_type</a></h2>
<p>A string representing the media type that was accepted by the content negotiation stage.</p>
<hr />
<h1 id="authentication">Authentication</h1>
<h1 id="authentication"><a class="toclink" href="#authentication">Authentication</a></h1>
<p>REST framework provides flexible, per-request authentication, that gives you the ability to:</p>
<ul>
<li>Use different authentication policies for different parts of your API.</li>
<li>Support the use of multiple authentication policies.</li>
<li>Provide both user and token information associated with the incoming request.</li>
</ul>
<h2 id="user">.user</h2>
<h2 id="user"><a class="toclink" href="#user">.user</a></h2>
<p><code>request.user</code> typically returns an instance of <code>django.contrib.auth.models.User</code>, although the behavior depends on the authentication policy being used.</p>
<p>If the request is unauthenticated the default value of <code>request.user</code> is an instance of <code>django.contrib.auth.models.AnonymousUser</code>.</p>
<p>For more details see the <a href="../authentication/">authentication documentation</a>.</p>
<h2 id="auth">.auth</h2>
<h2 id="auth"><a class="toclink" href="#auth">.auth</a></h2>
<p><code>request.auth</code> returns any additional authentication context. The exact behavior of <code>request.auth</code> depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.</p>
<p>If the request is unauthenticated, or if no additional context is present, the default value of <code>request.auth</code> is <code>None</code>.</p>
<p>For more details see the <a href="../authentication/">authentication documentation</a>.</p>
<h2 id="authenticators">.authenticators</h2>
<h2 id="authenticators"><a class="toclink" href="#authenticators">.authenticators</a></h2>
<p>The <code>APIView</code> class or <code>@api_view</code> decorator will ensure that this property is automatically set to a list of <code>Authentication</code> instances, based on the <code>authentication_classes</code> set on the view or based on the <code>DEFAULT_AUTHENTICATORS</code> setting.</p>
<p>You won't typically need to access this property.</p>
<hr />
<h1 id="browser-enhancements">Browser enhancements</h1>
<h1 id="browser-enhancements"><a class="toclink" href="#browser-enhancements">Browser enhancements</a></h1>
<p>REST framework supports a few browser enhancements such as browser-based <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> forms.</p>
<h2 id="method">.method</h2>
<h2 id="method"><a class="toclink" href="#method">.method</a></h2>
<p><code>request.method</code> returns the <strong>uppercased</strong> string representation of the request's HTTP method.</p>
<p>Browser-based <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> forms are transparently supported.</p>
<p>For more information see the <a href="../../topics/browser-enhancements/">browser enhancements documentation</a>.</p>
<h2 id="content_type">.content_type</h2>
<h2 id="content_type"><a class="toclink" href="#content_type">.content_type</a></h2>
<p><code>request.content_type</code>, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.</p>
<p>You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.</p>
<p>If you do need to access the content type of the request you should use the <code>.content_type</code> property in preference to using <code>request.META.get('HTTP_CONTENT_TYPE')</code>, as it provides transparent support for browser-based non-form content.</p>
<p>For more information see the <a href="../../topics/browser-enhancements/">browser enhancements documentation</a>.</p>
<h2 id="stream">.stream</h2>
<h2 id="stream"><a class="toclink" href="#stream">.stream</a></h2>
<p><code>request.stream</code> returns a stream representing the content of the request body.</p>
<p>You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.</p>
<p>If you do need to access the raw content directly, you should use the <code>.stream</code> property in preference to using <code>request.content</code>, as it provides transparent support for browser-based non-form content.</p>
<p>For more information see the <a href="../../topics/browser-enhancements/">browser enhancements documentation</a>.</p>
<hr />
<h1 id="standard-httprequest-attributes">Standard HttpRequest attributes</h1>
<h1 id="standard-httprequest-attributes"><a class="toclink" href="#standard-httprequest-attributes">Standard HttpRequest attributes</a></h1>
<p>As REST framework's <code>Request</code> extends Django's <code>HttpRequest</code>, all the other standard attributes and methods are also available. For example the <code>request.META</code> and <code>request.session</code> dictionaries are available as normal.</p>
<p>Note that due to implementation reasons the <code>Request</code> class does not inherit from <code>HttpRequest</code> class, but instead extends the class using composition.</p>

View File

@ -417,7 +417,7 @@
<h1 id="responses">Responses</h1>
<h1 id="responses"><a class="toclink" href="#responses">Responses</a></h1>
<blockquote>
<p>Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/ref/template-response/">Django documentation</a></p>
@ -427,8 +427,8 @@
<p>There's no requirement for you to use the <code>Response</code> class, you can also return regular <code>HttpResponse</code> or <code>StreamingHttpResponse</code> objects from your views if required. Using the <code>Response</code> class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.</p>
<p>Unless you want to heavily customize REST framework for some reason, you should always use an <code>APIView</code> class or <code>@api_view</code> function for views that return <code>Response</code> objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.</p>
<hr />
<h1 id="creating-responses">Creating responses</h1>
<h2 id="response">Response()</h2>
<h1 id="creating-responses"><a class="toclink" href="#creating-responses">Creating responses</a></h1>
<h2 id="response"><a class="toclink" href="#response">Response()</a></h2>
<p><strong>Signature:</strong> <code>Response(data, status=None, template_name=None, headers=None, content_type=None)</code></p>
<p>Unlike regular <code>HttpResponse</code> objects, you do not instantiate <code>Response</code> objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.</p>
<p>The renderers used by the <code>Response</code> class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the <code>Response</code> object.</p>
@ -442,31 +442,31 @@
<li><code>content_type</code>: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.</li>
</ul>
<hr />
<h1 id="attributes">Attributes</h1>
<h2 id="data">.data</h2>
<h1 id="attributes"><a class="toclink" href="#attributes">Attributes</a></h1>
<h2 id="data"><a class="toclink" href="#data">.data</a></h2>
<p>The unrendered content of a <code>Request</code> object.</p>
<h2 id="status_code">.status_code</h2>
<h2 id="status_code"><a class="toclink" href="#status_code">.status_code</a></h2>
<p>The numeric status code of the HTTP response.</p>
<h2 id="content">.content</h2>
<h2 id="content"><a class="toclink" href="#content">.content</a></h2>
<p>The rendered content of the response. The <code>.render()</code> method must have been called before <code>.content</code> can be accessed.</p>
<h2 id="template_name">.template_name</h2>
<h2 id="template_name"><a class="toclink" href="#template_name">.template_name</a></h2>
<p>The <code>template_name</code>, if supplied. Only required if <code>HTMLRenderer</code> or some other custom template renderer is the accepted renderer for the response.</p>
<h2 id="accepted_renderer">.accepted_renderer</h2>
<h2 id="accepted_renderer"><a class="toclink" href="#accepted_renderer">.accepted_renderer</a></h2>
<p>The renderer instance that will be used to render the response.</p>
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
<h2 id="accepted_media_type">.accepted_media_type</h2>
<h2 id="accepted_media_type"><a class="toclink" href="#accepted_media_type">.accepted_media_type</a></h2>
<p>The media type that was selected by the content negotiation stage.</p>
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
<h2 id="renderer_context">.renderer_context</h2>
<h2 id="renderer_context"><a class="toclink" href="#renderer_context">.renderer_context</a></h2>
<p>A dictionary of additional context information that will be passed to the renderer's <code>.render()</code> method.</p>
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
<hr />
<h1 id="standard-httpresponse-attributes">Standard HttpResponse attributes</h1>
<h1 id="standard-httpresponse-attributes"><a class="toclink" href="#standard-httpresponse-attributes">Standard HttpResponse attributes</a></h1>
<p>The <code>Response</code> class extends <code>SimpleTemplateResponse</code>, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:</p>
<pre><code>response = Response()
response['Cache-Control'] = 'no-cache'
</code></pre>
<h2 id="render">.render()</h2>
<h2 id="render"><a class="toclink" href="#render">.render()</a></h2>
<p><strong>Signature:</strong> <code>.render()</code></p>
<p>As with any other <code>TemplateResponse</code>, this method is called to render the serialized data of the response into the final response content. When <code>.render()</code> is called, the response content will be set to the result of calling the <code>.render(data, accepted_media_type, renderer_context)</code> method on the <code>accepted_renderer</code> instance.</p>
<p>You won't typically need to call <code>.render()</code> yourself, as it's handled by Django's standard response cycle.</p>

View File

@ -371,7 +371,7 @@
<h1 id="returning-urls">Returning URLs</h1>
<h1 id="returning-urls"><a class="toclink" href="#returning-urls">Returning URLs</a></h1>
<blockquote>
<p>The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.</p>
<p>&mdash; Roy Fielding, <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">Architectural Styles and the Design of Network-based Software Architectures</a></p>
@ -386,7 +386,7 @@
</ul>
<p>REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.</p>
<p>There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.</p>
<h2 id="reverse">reverse</h2>
<h2 id="reverse"><a class="toclink" href="#reverse">reverse</a></h2>
<p><strong>Signature:</strong> <code>reverse(viewname, *args, **kwargs)</code></p>
<p>Has the same behavior as <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse"><code>django.core.urlresolvers.reverse</code></a>, except that it returns a fully qualified URL, using the request to determine the host and port.</p>
<p>You should <strong>include the request as a keyword argument</strong> to the function, for example:</p>
@ -403,7 +403,7 @@ class APIRootView(APIView):
}
return Response(data)
</code></pre>
<h2 id="reverse_lazy">reverse_lazy</h2>
<h2 id="reverse_lazy"><a class="toclink" href="#reverse_lazy">reverse_lazy</a></h2>
<p><strong>Signature:</strong> <code>reverse_lazy(viewname, *args, **kwargs)</code></p>
<p>Has the same behavior as <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy"><code>django.core.urlresolvers.reverse_lazy</code></a>, except that it returns a fully qualified URL, using the request to determine the host and port.</p>
<p>As with the <code>reverse</code> function, you should <strong>include the request as a keyword argument</strong> to the function, for example:</p>

View File

@ -417,14 +417,14 @@
<h1 id="routers">Routers</h1>
<h1 id="routers"><a class="toclink" href="#routers">Routers</a></h1>
<blockquote>
<p>Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.</p>
<p>&mdash; <a href="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
</blockquote>
<p>Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.</p>
<p>REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.</p>
<h2 id="usage">Usage</h2>
<h2 id="usage"><a class="toclink" href="#usage">Usage</a></h2>
<p>Here's an example of a simple URL conf, that uses <code>SimpleRouter</code>.</p>
<pre><code>from rest_framework import routers
@ -456,7 +456,7 @@ urlpatterns = router.urls
</code></pre>
<p>This means you'll need to explicitly set the <code>base_name</code> argument when registering the viewset, as it could not be automatically determined from the model name.</p>
<hr />
<h3 id="using-include-with-routers">Using <code>include</code> with routers</h3>
<h3 id="using-include-with-routers"><a class="toclink" href="#using-include-with-routers">Using <code>include</code> with routers</a></h3>
<p>The <code>.urls</code> attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.</p>
<p>For example, you can append <code>router.urls</code> to a list of existing views…</p>
<pre><code>router = routers.SimpleRouter()
@ -482,7 +482,7 @@ urlpatterns += router.urls
]
</code></pre>
<p>If using namespacing with hyperlinked serializers you'll also need to ensure that any <code>view_name</code> parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as <code>view_name='api:user-detail'</code> for serializer fields hyperlinked to the user detail view.</p>
<h3 id="extra-link-and-actions">Extra link and actions</h3>
<h3 id="extra-link-and-actions"><a class="toclink" href="#extra-link-and-actions">Extra link and actions</a></h3>
<p>Any methods on the viewset decorated with <code>@detail_route</code> or <code>@list_route</code> will also be routed.
For example, given a method like this on the <code>UserViewSet</code> class:</p>
<pre><code>from myapp.permissions import IsAdminOrIsSelf
@ -516,8 +516,8 @@ class UserViewSet(ModelViewSet):
<li>URL pattern: <code>^users/{pk}/change-password/$</code> Name: <code>'user-change-password'</code></li>
</ul>
<p>For more information see the viewset documentation on <a href="../viewsets/#marking-extra-actions-for-routing">marking extra actions for routing</a>.</p>
<h1 id="api-guide">API Guide</h1>
<h2 id="simplerouter">SimpleRouter</h2>
<h1 id="api-guide"><a class="toclink" href="#api-guide">API Guide</a></h1>
<h2 id="simplerouter"><a class="toclink" href="#simplerouter">SimpleRouter</a></h2>
<p>This router includes routes for the standard set of <code>list</code>, <code>create</code>, <code>retrieve</code>, <code>update</code>, <code>partial_update</code> and <code>destroy</code> actions. The viewset can also mark additional methods to be routed, using the <code>@detail_route</code> or <code>@list_route</code> decorators.</p>
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
@ -541,7 +541,7 @@ This behavior can be modified by setting the <code>trailing_slash</code> argumen
lookup_field = 'my_model_id'
lookup_value_regex = '[0-9a-f]{32}'
</code></pre>
<h2 id="defaultrouter">DefaultRouter</h2>
<h2 id="defaultrouter"><a class="toclink" href="#defaultrouter">DefaultRouter</a></h2>
<p>This router is similar to <code>SimpleRouter</code> as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional <code>.json</code> style format suffixes.</p>
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
@ -559,7 +559,7 @@ This behavior can be modified by setting the <code>trailing_slash</code> argumen
<p>As with <code>SimpleRouter</code> the trailing slashes on the URL routes can be removed by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router.</p>
<pre><code>router = DefaultRouter(trailing_slash=False)
</code></pre>
<h1 id="custom-routers">Custom Routers</h1>
<h1 id="custom-routers"><a class="toclink" href="#custom-routers">Custom Routers</a></h1>
<p>Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.</p>
<p>The simplest way to implement a custom router is to subclass one of the existing router classes. The <code>.routes</code> attribute is used to template the URL patterns that will be mapped to each viewset. The <code>.routes</code> attribute is a list of <code>Route</code> named tuples.</p>
<p>The arguments to the <code>Route</code> named tuple are:</p>
@ -575,14 +575,14 @@ This behavior can be modified by setting the <code>trailing_slash</code> argumen
<li><code>{basename}</code> - The base to use for the URL names that are created.</li>
</ul>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the <code>suffix</code> argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.</p>
<h2 id="customizing-dynamic-routes">Customizing dynamic routes</h2>
<h2 id="customizing-dynamic-routes"><a class="toclink" href="#customizing-dynamic-routes">Customizing dynamic routes</a></h2>
<p>You can also customize how the <code>@list_route</code> and <code>@detail_route</code> decorators are routed.
To route either or both of these decorators, include a <code>DynamicListRoute</code> and/or <code>DynamicDetailRoute</code> named tuple in the <code>.routes</code> list.</p>
<p>The arguments to <code>DynamicListRoute</code> and <code>DynamicDetailRoute</code> are:</p>
<p><strong>url</strong>: A string representing the URL to be routed. May include the same format strings as <code>Route</code>, and additionally accepts the <code>{methodname}</code> and <code>{methodnamehyphen}</code> format strings.</p>
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format strings: <code>{basename}</code>, <code>{methodname}</code> and <code>{methodnamehyphen}</code>.</p>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following example will only route to the <code>list</code> and <code>retrieve</code> actions, and does not use the trailing slash convention.</p>
<pre><code>from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter
@ -644,21 +644,21 @@ urlpatterns = router.urls
</table>
<p>For another example of setting the <code>.routes</code> attribute, see the source code for the <code>SimpleRouter</code> class.</p>
<h2 id="advanced-custom-routers">Advanced custom routers</h2>
<h2 id="advanced-custom-routers"><a class="toclink" href="#advanced-custom-routers">Advanced custom routers</a></h2>
<p>If you want to provide totally custom behavior, you can override <code>BaseRouter</code> and override the <code>get_urls(self)</code> method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the <code>self.registry</code> attribute.</p>
<p>You may also want to override the <code>get_default_base_name(self, viewset)</code> method, or else always explicitly set the <code>base_name</code> argument when registering your viewsets with the router.</p>
<h1 id="third-party-packages">Third Party Packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third Party Packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers">DRF Nested Routers</h2>
<h2 id="drf-nested-routers"><a class="toclink" href="#drf-nested-routers">DRF Nested Routers</a></h2>
<p>The <a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>
<h2 id="modelrouter-wqdbrest">ModelRouter (wq.db.rest)</h2>
<h2 id="modelrouter-wqdbrest"><a class="toclink" href="#modelrouter-wqdbrest">ModelRouter (wq.db.rest)</a></h2>
<p>The <a href="http://wq.io/wq.db">wq.db package</a> provides an advanced <a href="http://wq.io/docs/router">ModelRouter</a> class (and singleton instance) that extends <code>DefaultRouter</code> with a <code>register_model()</code> API. Much like Django's <code>admin.site.register</code>, the only required argument to <code>rest.router.register_model</code> is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.</p>
<pre><code>from wq.db import rest
from myapp.models import MyModel
rest.router.register_model(MyModel)
</code></pre>
<h2 id="drf-extensions">DRF-extensions</h2>
<h2 id="drf-extensions"><a class="toclink" href="#drf-extensions">DRF-extensions</a></h2>
<p>The <a href="http://chibisov.github.io/drf-extensions/docs/"><code>DRF-extensions</code> package</a> provides <a href="http://chibisov.github.io/drf-extensions/docs/#routers">routers</a> for creating <a href="http://chibisov.github.io/drf-extensions/docs/#nested-routes">nested viewsets</a>, <a href="http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers">collection level controllers</a> with <a href="http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name">customizable endpoint names</a>.</p>

View File

@ -543,7 +543,7 @@
<h1 id="serializers">Serializers</h1>
<h1 id="serializers"><a class="toclink" href="#serializers">Serializers</a></h1>
<blockquote>
<p>Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
@ -552,7 +552,7 @@ will take some serious design work.</p>
</blockquote>
<p>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into <code>JSON</code>, <code>XML</code> or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</p>
<p>The serializers in REST framework work very similarly to Django's <code>Form</code> and <code>ModelForm</code> classes. We provide a <code>Serializer</code> class which gives you a powerful, generic way to control the output of your responses, as well as a <code>ModelSerializer</code> class which provides a useful shortcut for creating serializers that deal with model instances and querysets.</p>
<h2 id="declaring-serializers">Declaring Serializers</h2>
<h2 id="declaring-serializers"><a class="toclink" href="#declaring-serializers">Declaring Serializers</a></h2>
<p>Let's start by creating a simple object we can use for example purposes:</p>
<pre><code>from datetime import datetime
@ -573,7 +573,7 @@ class CommentSerializer(serializers.Serializer):
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
</code></pre>
<h2 id="serializing-objects">Serializing objects</h2>
<h2 id="serializing-objects"><a class="toclink" href="#serializing-objects">Serializing objects</a></h2>
<p>We can now use <code>CommentSerializer</code> to serialize a comment, or list of comments. Again, using the <code>Serializer</code> class looks a lot like using a <code>Form</code> class.</p>
<pre><code>serializer = CommentSerializer(comment)
serializer.data
@ -586,7 +586,7 @@ json = JSONRenderer().render(serializer.data)
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
</code></pre>
<h2 id="deserializing-objects">Deserializing objects</h2>
<h2 id="deserializing-objects"><a class="toclink" href="#deserializing-objects">Deserializing objects</a></h2>
<p>Deserialization is similar. First we parse a stream into Python native datatypes...</p>
<pre><code>from django.utils.six import BytesIO
from rest_framework.parsers import JSONParser
@ -601,7 +601,7 @@ serializer.is_valid()
serializer.validated_data
# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
</code></pre>
<h2 id="saving-instances">Saving instances</h2>
<h2 id="saving-instances"><a class="toclink" href="#saving-instances">Saving instances</a></h2>
<p>If we want to be able to return complete object instances based on the validated data we need to implement one or both of the <code>.create()</code> and <code>update()</code> methods. For example:</p>
<pre><code>class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
@ -639,13 +639,13 @@ serializer = CommentSerializer(data=data)
serializer = CommentSerializer(comment, data=data)
</code></pre>
<p>Both the <code>.create()</code> and <code>.update()</code> methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.</p>
<h4 id="passing-additional-attributes-to-save">Passing additional attributes to <code>.save()</code></h4>
<h4 id="passing-additional-attributes-to-save"><a class="toclink" href="#passing-additional-attributes-to-save">Passing additional attributes to <code>.save()</code></a></h4>
<p>Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.</p>
<p>You can do so by including additional keyword arguments when calling <code>.save()</code>. For example:</p>
<pre><code>serializer.save(owner=request.user)
</code></pre>
<p>Any additional keyword arguments will be included in the <code>validated_data</code> argument when <code>.create()</code> or <code>.update()</code> are called.</p>
<h4 id="overriding-save-directly">Overriding <code>.save()</code> directly.</h4>
<h4 id="overriding-save-directly"><a class="toclink" href="#overriding-save-directly">Overriding <code>.save()</code> directly.</a></h4>
<p>In some cases the <code>.create()</code> and <code>.update()</code> method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.</p>
<p>In these cases you might instead choose to override <code>.save()</code> directly, as being more readable and meaningful.</p>
<p>For example:</p>
@ -659,7 +659,7 @@ serializer = CommentSerializer(comment, data=data)
send_email(from=email, message=message)
</code></pre>
<p>Note that in the case above we're now having to access the serializer <code>.validated_data</code> property directly.</p>
<h2 id="validation">Validation</h2>
<h2 id="validation"><a class="toclink" href="#validation">Validation</a></h2>
<p>When deserializing data, you always need to call <code>is_valid()</code> before attempting to access the validated data, or save an object instance. If any validation errors occur, the <code>.errors</code> property will contain a dictionary representing the resulting error messages. For example:</p>
<pre><code>serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
serializer.is_valid()
@ -669,13 +669,13 @@ serializer.errors
</code></pre>
<p>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 <code>non_field_errors</code> key may also be present, and will list any general validation errors. The name of the <code>non_field_errors</code> key may be customized using the <code>NON_FIELD_ERRORS_KEY</code> REST framework setting.</p>
<p>When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.</p>
<h4 id="raising-an-exception-on-invalid-data">Raising an exception on invalid data</h4>
<h4 id="raising-an-exception-on-invalid-data"><a class="toclink" href="#raising-an-exception-on-invalid-data">Raising an exception on invalid data</a></h4>
<p>The <code>.is_valid()</code> method takes an optional <code>raise_exception</code> flag that will cause it to raise a <code>serializers.ValidationError</code> exception if there are validation errors.</p>
<p>These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return <code>HTTP 400 Bad Request</code> responses by default.</p>
<pre><code># Return a 400 response if the data was invalid.
serializer.is_valid(raise_exception=True)
</code></pre>
<h4 id="field-level-validation">Field-level validation</h4>
<h4 id="field-level-validation"><a class="toclink" href="#field-level-validation">Field-level validation</a></h4>
<p>You can specify custom field-level validation by adding <code>.validate_&lt;field_name&gt;</code> methods to your <code>Serializer</code> subclass. These are similar to the <code>.clean_&lt;field_name&gt;</code> methods on Django forms.</p>
<p>These methods take a single argument, which is the field value that requires validation.</p>
<p>Your <code>validate_&lt;field_name&gt;</code> methods should return the validated value or raise a <code>serializers.ValidationError</code>. For example:</p>
@ -696,7 +696,7 @@ class BlogPostSerializer(serializers.Serializer):
<hr />
<p><strong>Note:</strong> If your <code>&lt;field_name&gt;</code> is declared on your serializer with the parameter <code>required=False</code> then this validation step will not take place if the field is not included.</p>
<hr />
<h4 id="object-level-validation">Object-level validation</h4>
<h4 id="object-level-validation"><a class="toclink" href="#object-level-validation">Object-level validation</a></h4>
<p>To do any other validation that requires access to multiple fields, add a method called <code>.validate()</code> to your <code>Serializer</code> subclass. This method takes a single argument, which is a dictionary of field values. It should raise a <code>ValidationError</code> if necessary, or just return the validated values. For example:</p>
<pre><code>from rest_framework import serializers
@ -713,7 +713,7 @@ class EventSerializer(serializers.Serializer):
raise serializers.ValidationError("finish must occur after start")
return data
</code></pre>
<h4 id="validators">Validators</h4>
<h4 id="validators"><a class="toclink" href="#validators">Validators</a></h4>
<p>Individual fields on a serializer can include validators, by declaring them on the field instance, for example:</p>
<pre><code>def multiple_of_ten(value):
if value % 10 != 0:
@ -737,15 +737,15 @@ class GameRecord(serializers.Serializer):
)
</code></pre>
<p>For more information see the <a href="../validators/">validators documentation</a>.</p>
<h2 id="accessing-the-initial-data-and-instance">Accessing the initial data and instance</h2>
<h2 id="accessing-the-initial-data-and-instance"><a class="toclink" href="#accessing-the-initial-data-and-instance">Accessing the initial data and instance</a></h2>
<p>When passing an initial object or queryset to a serializer instance, the object will be made available as <code>.instance</code>. If no initial object is passed then the <code>.instance</code> attribute will be <code>None</code>.</p>
<p>When passing data to a serializer instance, the unmodified data will be made available as <code>.initial_data</code>. If the data keyword argument is not passed then the <code>.initial_data</code> attribute will not exist.</p>
<h2 id="partial-updates">Partial updates</h2>
<h2 id="partial-updates"><a class="toclink" href="#partial-updates">Partial updates</a></h2>
<p>By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the <code>partial</code> argument in order to allow partial updates.</p>
<pre><code># Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
</code></pre>
<h2 id="dealing-with-nested-objects">Dealing with nested objects</h2>
<h2 id="dealing-with-nested-objects"><a class="toclink" href="#dealing-with-nested-objects">Dealing with nested objects</a></h2>
<p>The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.</p>
<p>The <code>Serializer</code> class is itself a type of <code>Field</code>, and can be used to represent relationships where one object type is nested inside another.</p>
<pre><code>class UserSerializer(serializers.Serializer):
@ -770,7 +770,7 @@ class CommentSerializer(serializers.Serializer):
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
</code></pre>
<h2 id="writable-nested-representations">Writable nested representations</h2>
<h2 id="writable-nested-representations"><a class="toclink" href="#writable-nested-representations">Writable nested representations</a></h2>
<p>When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.</p>
<pre><code>serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
serializer.is_valid()
@ -779,7 +779,7 @@ serializer.errors
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
</code></pre>
<p>Similarly, the <code>.validated_data</code> property will include nested data structures.</p>
<h4 id="writing-create-methods-for-nested-representations">Writing <code>.create()</code> methods for nested representations</h4>
<h4 id="writing-create-methods-for-nested-representations"><a class="toclink" href="#writing-create-methods-for-nested-representations">Writing <code>.create()</code> methods for nested representations</a></h4>
<p>If you're supporting writable nested representations you'll need to write <code>.create()</code> or <code>.update()</code> methods that handle saving multiple objects.</p>
<p>The following example demonstrates how you might handle creating a user with a nested profile object.</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
@ -795,7 +795,7 @@ serializer.errors
Profile.objects.create(user=user, **profile_data)
return user
</code></pre>
<h4 id="writing-update-methods-for-nested-representations">Writing <code>.update()</code> methods for nested representations</h4>
<h4 id="writing-update-methods-for-nested-representations"><a class="toclink" href="#writing-update-methods-for-nested-representations">Writing <code>.update()</code> methods for nested representations</a></h4>
<p>For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is <code>None</code>, or not provided, which of the following should occur?</p>
<ul>
<li>Set the relationship to <code>NULL</code> in the database.</li>
@ -829,7 +829,7 @@ serializer.errors
</code></pre>
<p>Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default <code>ModelSerializer</code> <code>.create()</code> and <code>.update()</code> methods do not include support for writable nested representations.</p>
<p>It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.</p>
<h4 id="handling-saving-related-instances-in-model-manager-classes">Handling saving related instances in model manager classes</h4>
<h4 id="handling-saving-related-instances-in-model-manager-classes"><a class="toclink" href="#handling-saving-related-instances-in-model-manager-classes">Handling saving related instances in model manager classes</a></h4>
<p>An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.</p>
<p>For example, suppose we wanted to ensure that <code>User</code> instances and <code>Profile</code> instances are always created together as a pair. We might write a custom manager class that looks something like this:</p>
<pre><code>class UserManager(models.Manager):
@ -856,9 +856,9 @@ serializer.errors
)
</code></pre>
<p>For more details on this approach see the Django documentation on <a href="../model-managers">model managers</a>, and <a href="../encapsulation-blogpost">this blogpost on using model and manager classes</a>.</p>
<h2 id="dealing-with-multiple-objects">Dealing with multiple objects</h2>
<h2 id="dealing-with-multiple-objects"><a class="toclink" href="#dealing-with-multiple-objects">Dealing with multiple objects</a></h2>
<p>The <code>Serializer</code> class can also handle serializing or deserializing lists of objects.</p>
<h4 id="serializing-multiple-objects">Serializing multiple objects</h4>
<h4 id="serializing-multiple-objects"><a class="toclink" href="#serializing-multiple-objects">Serializing multiple objects</a></h4>
<p>To serialize a queryset or list of objects instead of a single object instance, you should pass the <code>many=True</code> flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.</p>
<pre><code>queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
@ -869,9 +869,9 @@ serializer.data
# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
# ]
</code></pre>
<h4 id="deserializing-multiple-objects">Deserializing multiple objects</h4>
<h4 id="deserializing-multiple-objects"><a class="toclink" href="#deserializing-multiple-objects">Deserializing multiple objects</a></h4>
<p>The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the <a href="#listserializer">ListSerializer</a> documentation below.</p>
<h2 id="including-extra-context">Including extra context</h2>
<h2 id="including-extra-context"><a class="toclink" href="#including-extra-context">Including extra context</a></h2>
<p>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.</p>
<p>You can provide arbitrary additional context by passing a <code>context</code> argument when instantiating the serializer. For example:</p>
<pre><code>serializer = AccountSerializer(account, context={'request': request})
@ -880,7 +880,7 @@ serializer.data
</code></pre>
<p>The context dictionary can be used within any serializer field logic, such as a custom <code>.to_representation()</code> method, by accessing the <code>self.context</code> attribute.</p>
<hr />
<h1 id="modelserializer">ModelSerializer</h1>
<h1 id="modelserializer"><a class="toclink" href="#modelserializer">ModelSerializer</a></h1>
<p>Often you'll want serializer classes that map closely to Django model definitions.</p>
<p>The <code>ModelSerializer</code> class provides a shortcut that lets you automatically create a <code>Serializer</code> class with fields that correspond to the Model fields.</p>
<p><strong>The <code>ModelSerializer</code> class is the same as a regular <code>Serializer</code> class, except that</strong>:</p>
@ -897,7 +897,7 @@ serializer.data
</code></pre>
<p>By default, all the model fields on the class will be mapped to a corresponding serializer fields.</p>
<p>Any relationships such as foreign keys on the model will be mapped to <code>PrimaryKeyRelatedField</code>. Reverse relationships are not included by default unless explicitly included as described below.</p>
<h4 id="inspecting-a-modelserializer">Inspecting a <code>ModelSerializer</code></h4>
<h4 id="inspecting-a-modelserializer"><a class="toclink" href="#inspecting-a-modelserializer">Inspecting a <code>ModelSerializer</code></a></h4>
<p>Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with <code>ModelSerializers</code> where you want to determine what set of fields and validators are being automatically created for you.</p>
<p>To do so, open the Django shell, using <code>python manage.py shell</code>, then import the serializer class, instantiate it, and print the object representation…</p>
<pre><code>&gt;&gt;&gt; from myapp.serializers import AccountSerializer
@ -908,7 +908,7 @@ AccountSerializer():
name = CharField(allow_blank=True, max_length=100, required=False)
owner = PrimaryKeyRelatedField(queryset=User.objects.all())
</code></pre>
<h2 id="specifying-which-fields-to-include">Specifying which fields to include</h2>
<h2 id="specifying-which-fields-to-include"><a class="toclink" href="#specifying-which-fields-to-include">Specifying which fields to include</a></h2>
<p>If you only want a subset of the default fields to be used in a model serializer, you can do so using <code>fields</code> or <code>exclude</code> options, just as you would with a <code>ModelForm</code>. It is strongly recommended that you explicitly set all fields that should be serialized using the <code>fields</code> attribute. This will make it less likely to result in unintentionally exposing data when your models change.</p>
<p>For example:</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
@ -933,7 +933,7 @@ AccountSerializer():
<p>In the example above, if the <code>Account</code> model had 3 fields <code>account_name</code>, <code>users</code>, and <code>created</code>, this will result in the fields <code>account_name</code> and <code>created</code> to be serialized.</p>
<p>The names in the <code>fields</code> and <code>exclude</code> attributes will normally map to model fields on the model class.</p>
<p>Alternatively names in the <code>fields</code> options can map to properties or methods which take no arguments that exist on the model class.</p>
<h2 id="specifying-nested-serialization">Specifying nested serialization</h2>
<h2 id="specifying-nested-serialization"><a class="toclink" href="#specifying-nested-serialization">Specifying nested serialization</a></h2>
<p>The default <code>ModelSerializer</code> uses primary keys for relationships, but you can also easily generate nested representations using the <code>depth</code> option:</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
class Meta:
@ -943,7 +943,7 @@ AccountSerializer():
</code></pre>
<p>The <code>depth</code> option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.</p>
<p>If you want to customize the way the serialization is done you'll need to define the field yourself.</p>
<h2 id="specifying-fields-explicitly">Specifying fields explicitly</h2>
<h2 id="specifying-fields-explicitly"><a class="toclink" href="#specifying-fields-explicitly">Specifying fields explicitly</a></h2>
<p>You can add extra fields to a <code>ModelSerializer</code> or override the default fields by declaring fields on the class, just as you would for a <code>Serializer</code> class.</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
@ -953,7 +953,7 @@ AccountSerializer():
model = Account
</code></pre>
<p>Extra fields can correspond to any property or callable on the model.</p>
<h2 id="specifying-read-only-fields">Specifying read only fields</h2>
<h2 id="specifying-read-only-fields"><a class="toclink" href="#specifying-read-only-fields">Specifying read only fields</a></h2>
<p>You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the <code>read_only=True</code> attribute, you may use the shortcut Meta option, <code>read_only_fields</code>.</p>
<p>This option should be a list or tuple of field names, and is declared as follows:</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
@ -971,7 +971,7 @@ AccountSerializer():
</code></pre>
<p>Please review the <a href="../../api-guide/validators/">Validators Documentation</a> for details on the <a href="../../api-guide/validators/#uniquetogethervalidator">UniqueTogetherValidator</a> and <a href="../../api-guide/validators/#currentuserdefault">CurrentUserDefault</a> classes.</p>
<hr />
<h2 id="additional-keyword-arguments">Additional keyword arguments</h2>
<h2 id="additional-keyword-arguments"><a class="toclink" href="#additional-keyword-arguments">Additional keyword arguments</a></h2>
<p>There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the <code>extra_kwargs</code> option. As in the case of <code>read_only_fields</code>, this means you do not need to explicitly declare the field on the serializer.</p>
<p>This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:</p>
<pre><code>class CreateUserSerializer(serializers.ModelSerializer):
@ -989,56 +989,56 @@ AccountSerializer():
user.save()
return user
</code></pre>
<h2 id="relational-fields">Relational fields</h2>
<h2 id="relational-fields"><a class="toclink" href="#relational-fields">Relational fields</a></h2>
<p>When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for <code>ModelSerializer</code> is to use the primary keys of the related instances.</p>
<p>Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.</p>
<p>For full details see the <a href="../relations/">serializer relations</a> documentation.</p>
<h2 id="inheritance-of-the-meta-class">Inheritance of the 'Meta' class</h2>
<h2 id="inheritance-of-the-meta-class"><a class="toclink" href="#inheritance-of-the-meta-class">Inheritance of the 'Meta' class</a></h2>
<p>The inner <code>Meta</code> class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's <code>Model</code> and <code>ModelForm</code> classes. If you want the <code>Meta</code> class to inherit from a parent class you must do so explicitly. For example:</p>
<pre><code>class AccountSerializer(MyBaseSerializer):
class Meta(MyBaseSerializer.Meta):
model = Account
</code></pre>
<p>Typically we would recommend <em>not</em> using inheritance on inner Meta classes, but instead declaring all options explicitly.</p>
<h2 id="customizing-field-mappings">Customizing field mappings</h2>
<h2 id="customizing-field-mappings"><a class="toclink" href="#customizing-field-mappings">Customizing field mappings</a></h2>
<p>The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.</p>
<p>Normally if a <code>ModelSerializer</code> does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular <code>Serializer</code> class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.</p>
<h3 id="serializer_field_mapping"><code>.serializer_field_mapping</code></h3>
<h3 id="serializer_field_mapping"><a class="toclink" href="#serializer_field_mapping"><code>.serializer_field_mapping</code></a></h3>
<p>A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.</p>
<h3 id="serializer_related_field"><code>.serializer_related_field</code></h3>
<h3 id="serializer_related_field"><a class="toclink" href="#serializer_related_field"><code>.serializer_related_field</code></a></h3>
<p>This property should be the serializer field class, that is used for relational fields by default.</p>
<p>For <code>ModelSerializer</code> this defaults to <code>PrimaryKeyRelatedField</code>.</p>
<p>For <code>HyperlinkedModelSerializer</code> this defaults to <code>serializers.HyperlinkedRelatedField</code>.</p>
<h3 id="serializer_url_field"><code>serializer_url_field</code></h3>
<h3 id="serializer_url_field"><a class="toclink" href="#serializer_url_field"><code>serializer_url_field</code></a></h3>
<p>The serializer field class that should be used for any <code>url</code> field on the serializer.</p>
<p>Defaults to <code>serializers.HyperlinkedIdentityField</code></p>
<h3 id="serializer_choice_field"><code>serializer_choice_field</code></h3>
<h3 id="serializer_choice_field"><a class="toclink" href="#serializer_choice_field"><code>serializer_choice_field</code></a></h3>
<p>The serializer field class that should be used for any choice fields on the serializer.</p>
<p>Defaults to <code>serializers.ChoiceField</code></p>
<h3 id="the-field_class-and-field_kwargs-api">The field_class and field_kwargs API</h3>
<h3 id="the-field_class-and-field_kwargs-api"><a class="toclink" href="#the-field_class-and-field_kwargs-api">The field_class and field_kwargs API</a></h3>
<p>The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of <code>(field_class, field_kwargs)</code>.</p>
<h3 id="build_standard_fieldself-field_name-model_field"><code>.build_standard_field(self, field_name, model_field)</code></h3>
<h3 id="build_standard_fieldself-field_name-model_field"><a class="toclink" href="#build_standard_fieldself-field_name-model_field"><code>.build_standard_field(self, field_name, model_field)</code></a></h3>
<p>Called to generate a serializer field that maps to a standard model field.</p>
<p>The default implementation returns a serializer class based on the <code>serializer_field_mapping</code> attribute.</p>
<h3 id="build_relational_fieldself-field_name-relation_info"><code>.build_relational_field(self, field_name, relation_info)</code></h3>
<h3 id="build_relational_fieldself-field_name-relation_info"><a class="toclink" href="#build_relational_fieldself-field_name-relation_info"><code>.build_relational_field(self, field_name, relation_info)</code></a></h3>
<p>Called to generate a serializer field that maps to a relational model field.</p>
<p>The default implementation returns a serializer class based on the <code>serializer_relational_field</code> attribute.</p>
<p>The <code>relation_info</code> argument is a named tuple, that contains <code>model_field</code>, <code>related_model</code>, <code>to_many</code> and <code>has_through_model</code> properties.</p>
<h3 id="build_nested_fieldself-field_name-relation_info-nested_depth"><code>.build_nested_field(self, field_name, relation_info, nested_depth)</code></h3>
<h3 id="build_nested_fieldself-field_name-relation_info-nested_depth"><a class="toclink" href="#build_nested_fieldself-field_name-relation_info-nested_depth"><code>.build_nested_field(self, field_name, relation_info, nested_depth)</code></a></h3>
<p>Called to generate a serializer field that maps to a relational model field, when the <code>depth</code> option has been set.</p>
<p>The default implementation dynamically creates a nested serializer class based on either <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code>.</p>
<p>The <code>nested_depth</code> will be the value of the <code>depth</code> option, minus one.</p>
<p>The <code>relation_info</code> argument is a named tuple, that contains <code>model_field</code>, <code>related_model</code>, <code>to_many</code> and <code>has_through_model</code> properties.</p>
<h3 id="build_property_fieldself-field_name-model_class"><code>.build_property_field(self, field_name, model_class)</code></h3>
<h3 id="build_property_fieldself-field_name-model_class"><a class="toclink" href="#build_property_fieldself-field_name-model_class"><code>.build_property_field(self, field_name, model_class)</code></a></h3>
<p>Called to generate a serializer field that maps to a property or zero-argument method on the model class.</p>
<p>The default implementation returns a <code>ReadOnlyField</code> class.</p>
<h3 id="build_url_fieldself-field_name-model_class"><code>.build_url_field(self, field_name, model_class)</code></h3>
<h3 id="build_url_fieldself-field_name-model_class"><a class="toclink" href="#build_url_fieldself-field_name-model_class"><code>.build_url_field(self, field_name, model_class)</code></a></h3>
<p>Called to generate a serializer field for the serializer's own <code>url</code> field. The default implementation returns a <code>HyperlinkedIdentityField</code> class.</p>
<h3 id="build_unknown_fieldself-field_name-model_class"><code>.build_unknown_field(self, field_name, model_class)</code></h3>
<h3 id="build_unknown_fieldself-field_name-model_class"><a class="toclink" href="#build_unknown_fieldself-field_name-model_class"><code>.build_unknown_field(self, field_name, model_class)</code></a></h3>
<p>Called when the field name did not map to any model field or model property.
The default implementation raises an error, although subclasses may customize this behavior.</p>
<hr />
<h1 id="hyperlinkedmodelserializer">HyperlinkedModelSerializer</h1>
<h1 id="hyperlinkedmodelserializer"><a class="toclink" href="#hyperlinkedmodelserializer">HyperlinkedModelSerializer</a></h1>
<p>The <code>HyperlinkedModelSerializer</code> class is similar to the <code>ModelSerializer</code> class except that it uses hyperlinks to represent relationships, rather than primary keys.</p>
<p>By default the serializer will include a <code>url</code> field instead of a primary key field.</p>
<p>The url field will be represented using a <code>HyperlinkedIdentityField</code> serializer field, and any relationships on the model will be represented using a <code>HyperlinkedRelatedField</code> serializer field.</p>
@ -1048,7 +1048,7 @@ The default implementation raises an error, although subclasses may customize th
model = Account
fields = ('url', 'id', 'account_name', 'users', 'created')
</code></pre>
<h2 id="how-hyperlinked-views-are-determined">How hyperlinked views are determined</h2>
<h2 id="how-hyperlinked-views-are-determined"><a class="toclink" href="#how-hyperlinked-views-are-determined">How hyperlinked views are determined</a></h2>
<p>There needs to be a way of determining which views should be used for hyperlinking to model instances.</p>
<p>By default hyperlinks are expected to correspond to a view name that matches the style <code>'{model_name}-detail'</code>, and looks up the instance by a <code>pk</code> keyword argument.</p>
<p>You can override a URL field view name and lookup field by using either, or both of, the <code>view_name</code> and <code>lookup_field</code> options in the <code>extra_kwargs</code> setting, like so:</p>
@ -1081,10 +1081,10 @@ The default implementation raises an error, although subclasses may customize th
<hr />
<p><strong>Tip</strong>: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the <code>repr</code> of a <code>HyperlinkedModelSerializer</code> instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.</p>
<hr />
<h2 id="changing-the-url-field-name">Changing the URL field name</h2>
<h2 id="changing-the-url-field-name"><a class="toclink" href="#changing-the-url-field-name">Changing the URL field name</a></h2>
<p>The name of the URL field defaults to 'url'. You can override this globally, by using the <code>URL_FIELD_NAME</code> setting.</p>
<hr />
<h1 id="listserializer">ListSerializer</h1>
<h1 id="listserializer"><a class="toclink" href="#listserializer">ListSerializer</a></h1>
<p>The <code>ListSerializer</code> class provides the behavior for serializing and validating multiple objects at once. You won't <em>typically</em> need to use <code>ListSerializer</code> directly, but should instead simply pass <code>many=True</code> when instantiating a serializer.</p>
<p>When a serializer is instantiated and <code>many=True</code> is passed, a <code>ListSerializer</code> instance will be created. The serializer class then becomes a child of the parent <code>ListSerializer</code></p>
<p>There <em>are</em> a few use cases when you might want to customize the <code>ListSerializer</code> behavior. For example:</p>
@ -1102,7 +1102,7 @@ class CustomSerializer(serializers.Serializer):
class Meta:
list_serializer_class = CustomListSerializer
</code></pre>
<h4 id="customizing-multiple-create">Customizing multiple create</h4>
<h4 id="customizing-multiple-create"><a class="toclink" href="#customizing-multiple-create">Customizing multiple create</a></h4>
<p>The default implementation for multiple object creation is to simply call <code>.create()</code> for each item in the list. If you want to customize this behavior, you'll need to customize the <code>.create()</code> method on <code>ListSerializer</code> class that is used when <code>many=True</code> is passed.</p>
<p>For example:</p>
<pre><code>class BookListSerializer(serializers.ListSerializer):
@ -1115,7 +1115,7 @@ class BookSerializer(serializers.Serializer):
class Meta:
list_serializer_class = BookListSerializer
</code></pre>
<h4 id="customizing-multiple-update">Customizing multiple update</h4>
<h4 id="customizing-multiple-update"><a class="toclink" href="#customizing-multiple-update">Customizing multiple update</a></h4>
<p>By default the <code>ListSerializer</code> class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.</p>
<p>To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:</p>
<ul>
@ -1153,7 +1153,7 @@ class BookSerializer(serializers.Serializer):
list_serializer_class = BookListSerializer
</code></pre>
<p>It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the <code>allow_add_remove</code> behavior that was present in REST framework 2.</p>
<h4 id="customizing-listserializer-initialization">Customizing ListSerializer initialization</h4>
<h4 id="customizing-listserializer-initialization"><a class="toclink" href="#customizing-listserializer-initialization">Customizing ListSerializer initialization</a></h4>
<p>When a serializer with <code>many=True</code> is instantiated, we need to determine which arguments and keyword arguments should be passed to the <code>.__init__()</code> method for both the child <code>Serializer</code> class, and for the parent <code>ListSerializer</code> class.</p>
<p>The default implementation is to pass all arguments to both classes, except for <code>validators</code>, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.</p>
<p>Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when <code>many=True</code> is passed. You can do so by using the <code>many_init</code> class method.</p>
@ -1165,7 +1165,7 @@ class BookSerializer(serializers.Serializer):
return CustomListSerializer(*args, **kwargs)
</code></pre>
<hr />
<h1 id="baseserializer">BaseSerializer</h1>
<h1 id="baseserializer"><a class="toclink" href="#baseserializer">BaseSerializer</a></h1>
<p><code>BaseSerializer</code> class that can be used to easily support alternative serialization and deserialization styles.</p>
<p>This class implements the same basic API as the <code>Serializer</code> class:</p>
<ul>
@ -1183,7 +1183,7 @@ class BookSerializer(serializers.Serializer):
</ul>
<p>Because this class provides the same interface as the <code>Serializer</code> class, you can use it with the existing generic class based views exactly as you would for a regular <code>Serializer</code> or <code>ModelSerializer</code>.</p>
<p>The only difference you'll notice when doing so is the <code>BaseSerializer</code> classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.</p>
<h5 id="read-only-baseserializer-classes">Read-only <code>BaseSerializer</code> classes</h5>
<h5 id="read-only-baseserializer-classes"><a class="toclink" href="#read-only-baseserializer-classes">Read-only <code>BaseSerializer</code> classes</a></h5>
<p>To implement a read-only serializer using the <code>BaseSerializer</code> class, we just need to override the <code>.to_representation()</code> method. Let's take a look at an example using a simple Django model:</p>
<pre><code>class HighScore(models.Model):
created = models.DateTimeField(auto_now_add=True)
@ -1212,7 +1212,7 @@ def all_high_scores(request):
serializer = HighScoreSerializer(queryset, many=True)
return Response(serializer.data)
</code></pre>
<h5 id="read-write-baseserializer-classes">Read-write <code>BaseSerializer</code> classes</h5>
<h5 id="read-write-baseserializer-classes"><a class="toclink" href="#read-write-baseserializer-classes">Read-write <code>BaseSerializer</code> classes</a></h5>
<p>To create a read-write serializer we first need to implement a <code>.to_internal_value()</code> method. This method returns the validated values that will be used to construct the object instance, and may raise a <code>ValidationError</code> if the supplied data is in an incorrect format.</p>
<p>Once you've implemented <code>.to_internal_value()</code>, the basic validation API will be available on the serializer, and you will be able to use <code>.is_valid()</code>, <code>.validated_data</code> and <code>.errors</code>.</p>
<p>If you want to also support <code>.save()</code> you'll need to also implement either or both of the <code>.create()</code> and <code>.update()</code> methods.</p>
@ -1252,7 +1252,7 @@ def all_high_scores(request):
def create(self, validated_data):
return HighScore.objects.create(**validated_data)
</code></pre>
<h4 id="creating-new-base-classes">Creating new base classes</h4>
<h4 id="creating-new-base-classes"><a class="toclink" href="#creating-new-base-classes">Creating new base classes</a></h4>
<p>The <code>BaseSerializer</code> class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.</p>
<p>The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.</p>
<pre><code>class ObjectSerializer(serializers.BaseSerializer):
@ -1288,8 +1288,8 @@ def all_high_scores(request):
output[attribute_name] = str(attribute)
</code></pre>
<hr />
<h1 id="advanced-serializer-usage">Advanced serializer usage</h1>
<h2 id="overriding-serialization-and-deserialization-behavior">Overriding serialization and deserialization behavior</h2>
<h1 id="advanced-serializer-usage"><a class="toclink" href="#advanced-serializer-usage">Advanced serializer usage</a></h1>
<h2 id="overriding-serialization-and-deserialization-behavior"><a class="toclink" href="#overriding-serialization-and-deserialization-behavior">Overriding serialization and deserialization behavior</a></h2>
<p>If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the <code>.to_representation()</code> or <code>.to_internal_value()</code> methods.</p>
<p>Some reasons this might be useful include...</p>
<ul>
@ -1298,16 +1298,16 @@ def all_high_scores(request):
<li>Improving serialization performance for a frequently accessed API endpoint that returns lots of data.</li>
</ul>
<p>The signatures for these methods are as follows:</p>
<h4 id="to_representationself-obj"><code>.to_representation(self, obj)</code></h4>
<h4 id="to_representationself-obj"><a class="toclink" href="#to_representationself-obj"><code>.to_representation(self, obj)</code></a></h4>
<p>Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.</p>
<h4 id="to_internal_valueself-data"><code>.to_internal_value(self, data)</code></h4>
<h4 id="to_internal_valueself-data"><a class="toclink" href="#to_internal_valueself-data"><code>.to_internal_value(self, data)</code></a></h4>
<p>Takes the unvalidated incoming data as input and should return the validated data that will be made available as <code>serializer.validated_data</code>. The return value will also be passed to the <code>.create()</code> or <code>.update()</code> methods if <code>.save()</code> is called on the serializer class.</p>
<p>If any of the validation fails, then the method should raise a <code>serializers.ValidationError(errors)</code>. Typically the <code>errors</code> argument here will be a dictionary mapping field names to error messages.</p>
<p>The <code>data</code> argument passed to this method will normally be the value of <code>request.data</code>, so the datatype it provides will depend on the parser classes you have configured for your API.</p>
<h2 id="dynamically-modifying-fields">Dynamically modifying fields</h2>
<h2 id="dynamically-modifying-fields"><a class="toclink" href="#dynamically-modifying-fields">Dynamically modifying fields</a></h2>
<p>Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the <code>.fields</code> attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.</p>
<p>Modifying the <code>fields</code> argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.</p>
<h3 id="example">Example</h3>
<h3 id="example"><a class="toclink" href="#example">Example</a></h3>
<p>For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:</p>
<pre><code>class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
@ -1341,23 +1341,23 @@ def all_high_scores(request):
&gt;&gt;&gt; print UserSerializer(user, fields=('id', 'email'))
{'id': 2, 'email': 'jon@example.com'}
</code></pre>
<h2 id="customizing-the-default-fields">Customizing the default fields</h2>
<h2 id="customizing-the-default-fields"><a class="toclink" href="#customizing-the-default-fields">Customizing the default fields</a></h2>
<p>REST framework 2 provided an API to allow developers to override how a <code>ModelSerializer</code> class would automatically generate the default set of fields.</p>
<p>This API included the <code>.get_field()</code>, <code>.get_pk_field()</code> and other methods.</p>
<p>Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.</p>
<p>A new interface for controlling this behavior is currently planned for REST framework 3.1.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="django-rest-marshmallow">Django REST marshmallow</h2>
<h2 id="django-rest-marshmallow"><a class="toclink" href="#django-rest-marshmallow">Django REST marshmallow</a></h2>
<p>The <a href="http://tomchristie.github.io/django-rest-marshmallow/">django-rest-marshmallow</a> package provides an alternative implementation for serializers, using the python <a href="https://marshmallow.readthedocs.org/en/latest/">marshmallow</a> library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.</p>
<h2 id="serpy">Serpy</h2>
<h2 id="serpy"><a class="toclink" href="#serpy">Serpy</a></h2>
<p>The <a href="https://github.com/clarkduvall/serpy">serpy</a> package is an alternative implementation for serializers that is built for speed. <a href="https://github.com/clarkduvall/serpy">Serpy</a> serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.</p>
<h2 id="mongoenginemodelserializer">MongoengineModelSerializer</h2>
<h2 id="mongoenginemodelserializer"><a class="toclink" href="#mongoenginemodelserializer">MongoengineModelSerializer</a></h2>
<p>The <a href="https://github.com/umutbozkurt/django-rest-framework-mongoengine">django-rest-framework-mongoengine</a> package provides a <code>MongoEngineModelSerializer</code> serializer class that supports using MongoDB as the storage layer for Django REST framework.</p>
<h2 id="geofeaturemodelserializer">GeoFeatureModelSerializer</h2>
<h2 id="geofeaturemodelserializer"><a class="toclink" href="#geofeaturemodelserializer">GeoFeatureModelSerializer</a></h2>
<p>The <a href="https://github.com/djangonauts/django-rest-framework-gis">django-rest-framework-gis</a> package provides a <code>GeoFeatureModelSerializer</code> serializer class that supports GeoJSON both for read and write operations.</p>
<h2 id="hstoreserializer">HStoreSerializer</h2>
<h2 id="hstoreserializer"><a class="toclink" href="#hstoreserializer">HStoreSerializer</a></h2>
<p>The <a href="https://github.com/djangonauts/django-rest-framework-hstore">django-rest-framework-hstore</a> package provides an <code>HStoreSerializer</code> to support <a href="https://github.com/djangonauts/django-hstore">django-hstore</a> <code>DictionaryField</code> model field and its <code>schema-mode</code> feature.</p>

View File

@ -413,7 +413,7 @@
<h1 id="settings">Settings</h1>
<h1 id="settings"><a class="toclink" href="#settings">Settings</a></h1>
<blockquote>
<p>Namespaces are one honking great idea - let's do more of those!</p>
<p>&mdash; <a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a></p>
@ -429,7 +429,7 @@
)
}
</code></pre>
<h2 id="accessing-settings">Accessing settings</h2>
<h2 id="accessing-settings"><a class="toclink" href="#accessing-settings">Accessing settings</a></h2>
<p>If you need to access the values of REST framework's API settings in your project,
you should use the <code>api_settings</code> object. For example.</p>
<pre><code>from rest_framework.settings import api_settings
@ -438,10 +438,10 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
</code></pre>
<p>The <code>api_settings</code> object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.</p>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="api-policy-settings">API policy settings</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="api-policy-settings"><a class="toclink" href="#api-policy-settings">API policy settings</a></h2>
<p><em>The following settings control the basic API policies, and are applied to every <code>APIView</code> class based view, or <code>@api_view</code> function based view.</em></p>
<h4 id="default_renderer_classes">DEFAULT_RENDERER_CLASSES</h4>
<h4 id="default_renderer_classes"><a class="toclink" href="#default_renderer_classes">DEFAULT_RENDERER_CLASSES</a></h4>
<p>A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a <code>Response</code> object.</p>
<p>Default:</p>
<pre><code>(
@ -449,7 +449,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
'rest_framework.renderers.BrowsableAPIRenderer',
)
</code></pre>
<h4 id="default_parser_classes">DEFAULT_PARSER_CLASSES</h4>
<h4 id="default_parser_classes"><a class="toclink" href="#default_parser_classes">DEFAULT_PARSER_CLASSES</a></h4>
<p>A list or tuple of parser classes, that determines the default set of parsers used when accessing the <code>request.data</code> property.</p>
<p>Default:</p>
<pre><code>(
@ -458,7 +458,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
'rest_framework.parsers.MultiPartParser'
)
</code></pre>
<h4 id="default_authentication_classes">DEFAULT_AUTHENTICATION_CLASSES</h4>
<h4 id="default_authentication_classes"><a class="toclink" href="#default_authentication_classes">DEFAULT_AUTHENTICATION_CLASSES</a></h4>
<p>A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the <code>request.user</code> or <code>request.auth</code> properties.</p>
<p>Default:</p>
<pre><code>(
@ -466,32 +466,32 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
'rest_framework.authentication.BasicAuthentication'
)
</code></pre>
<h4 id="default_permission_classes">DEFAULT_PERMISSION_CLASSES</h4>
<h4 id="default_permission_classes"><a class="toclink" href="#default_permission_classes">DEFAULT_PERMISSION_CLASSES</a></h4>
<p>A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.</p>
<p>Default:</p>
<pre><code>(
'rest_framework.permissions.AllowAny',
)
</code></pre>
<h4 id="default_throttle_classes">DEFAULT_THROTTLE_CLASSES</h4>
<h4 id="default_throttle_classes"><a class="toclink" href="#default_throttle_classes">DEFAULT_THROTTLE_CLASSES</a></h4>
<p>A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.</p>
<p>Default: <code>()</code></p>
<h4 id="default_content_negotiation_class">DEFAULT_CONTENT_NEGOTIATION_CLASS</h4>
<h4 id="default_content_negotiation_class"><a class="toclink" href="#default_content_negotiation_class">DEFAULT_CONTENT_NEGOTIATION_CLASS</a></h4>
<p>A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.</p>
<p>Default: <code>'rest_framework.negotiation.DefaultContentNegotiation'</code></p>
<hr />
<h2 id="generic-view-settings">Generic view settings</h2>
<h2 id="generic-view-settings"><a class="toclink" href="#generic-view-settings">Generic view settings</a></h2>
<p><em>The following settings control the behavior of the generic class based views.</em></p>
<h4 id="default_pagination_serializer_class">DEFAULT_PAGINATION_SERIALIZER_CLASS</h4>
<h4 id="default_pagination_serializer_class"><a class="toclink" href="#default_pagination_serializer_class">DEFAULT_PAGINATION_SERIALIZER_CLASS</a></h4>
<p>A class the determines the default serialization style for paginated responses.</p>
<p>Default: <code>rest_framework.pagination.PaginationSerializer</code></p>
<h4 id="default_filter_backends">DEFAULT_FILTER_BACKENDS</h4>
<h4 id="default_filter_backends"><a class="toclink" href="#default_filter_backends">DEFAULT_FILTER_BACKENDS</a></h4>
<p>A list of filter backend classes that should be used for generic filtering.
If set to <code>None</code> then generic filtering is disabled.</p>
<h4 id="paginate_by">PAGINATE_BY</h4>
<h4 id="paginate_by"><a class="toclink" href="#paginate_by">PAGINATE_BY</a></h4>
<p>The default page size to use for pagination. If set to <code>None</code>, pagination is disabled by default.</p>
<p>Default: <code>None</code></p>
<h4 id="paginate_by_param">PAGINATE_BY_PARAM</h4>
<h4 id="paginate_by_param"><a class="toclink" href="#paginate_by_param">PAGINATE_BY_PARAM</a></h4>
<hr />
<p><strong>This setting is pending deprecation.</strong></p>
<p>See the pagination documentation for further guidance on <a href="../pagination/#modifying-the-pagination-style">setting the pagination style</a>.</p>
@ -507,7 +507,7 @@ If set to <code>None</code> then generic filtering is disabled.</p>
<pre><code>GET http://example.com/api/accounts?page_size=25
</code></pre>
<p>Default: <code>None</code></p>
<h4 id="max_paginate_by">MAX_PAGINATE_BY</h4>
<h4 id="max_paginate_by"><a class="toclink" href="#max_paginate_by">MAX_PAGINATE_BY</a></h4>
<hr />
<p><strong>This setting is pending deprecation.</strong></p>
<p>See the pagination documentation for further guidance on <a href="../pagination/#modifying-the-pagination-style">setting the pagination style</a>.</p>
@ -524,40 +524,40 @@ If set to <code>None</code> then generic filtering is disabled.</p>
<pre><code>GET http://example.com/api/accounts?page_size=999
</code></pre>
<p>Default: <code>None</code></p>
<h3 id="search_param">SEARCH_PARAM</h3>
<h3 id="search_param"><a class="toclink" href="#search_param">SEARCH_PARAM</a></h3>
<p>The name of a query parameter, which can be used to specify the search term used by <code>SearchFilter</code>.</p>
<p>Default: <code>search</code></p>
<h4 id="ordering_param">ORDERING_PARAM</h4>
<h4 id="ordering_param"><a class="toclink" href="#ordering_param">ORDERING_PARAM</a></h4>
<p>The name of a query parameter, which can be used to specify the ordering of results returned by <code>OrderingFilter</code>.</p>
<p>Default: <code>ordering</code></p>
<hr />
<h2 id="versioning-settings">Versioning settings</h2>
<h4 id="default_version">DEFAULT_VERSION</h4>
<h2 id="versioning-settings"><a class="toclink" href="#versioning-settings">Versioning settings</a></h2>
<h4 id="default_version"><a class="toclink" href="#default_version">DEFAULT_VERSION</a></h4>
<p>The value that should be used for <code>request.version</code> when no versioning information is present.</p>
<p>Default: <code>None</code></p>
<h4 id="allowed_versions">ALLOWED_VERSIONS</h4>
<h4 id="allowed_versions"><a class="toclink" href="#allowed_versions">ALLOWED_VERSIONS</a></h4>
<p>If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.</p>
<p>Default: <code>None</code></p>
<h4 id="version_parameter">VERSION_PARAMETER</h4>
<h4 id="version_parameter"><a class="toclink" href="#version_parameter">VERSION_PARAMETER</a></h4>
<p>The string that should used for any versioning parameters, such as in the media type or URL query parameters.</p>
<p>Default: <code>'version'</code></p>
<hr />
<h2 id="authentication-settings">Authentication settings</h2>
<h2 id="authentication-settings"><a class="toclink" href="#authentication-settings">Authentication settings</a></h2>
<p><em>The following settings control the behavior of unauthenticated requests.</em></p>
<h4 id="unauthenticated_user">UNAUTHENTICATED_USER</h4>
<h4 id="unauthenticated_user"><a class="toclink" href="#unauthenticated_user">UNAUTHENTICATED_USER</a></h4>
<p>The class that should be used to initialize <code>request.user</code> for unauthenticated requests.</p>
<p>Default: <code>django.contrib.auth.models.AnonymousUser</code></p>
<h4 id="unauthenticated_token">UNAUTHENTICATED_TOKEN</h4>
<h4 id="unauthenticated_token"><a class="toclink" href="#unauthenticated_token">UNAUTHENTICATED_TOKEN</a></h4>
<p>The class that should be used to initialize <code>request.auth</code> for unauthenticated requests.</p>
<p>Default: <code>None</code></p>
<hr />
<h2 id="test-settings">Test settings</h2>
<h2 id="test-settings"><a class="toclink" href="#test-settings">Test settings</a></h2>
<p><em>The following settings control the behavior of APIRequestFactory and APIClient</em></p>
<h4 id="test_request_default_format">TEST_REQUEST_DEFAULT_FORMAT</h4>
<h4 id="test_request_default_format"><a class="toclink" href="#test_request_default_format">TEST_REQUEST_DEFAULT_FORMAT</a></h4>
<p>The default format that should be used when making test requests.</p>
<p>This should match up with the format of one of the renderer classes in the <code>TEST_REQUEST_RENDERER_CLASSES</code> setting.</p>
<p>Default: <code>'multipart'</code></p>
<h4 id="test_request_renderer_classes">TEST_REQUEST_RENDERER_CLASSES</h4>
<h4 id="test_request_renderer_classes"><a class="toclink" href="#test_request_renderer_classes">TEST_REQUEST_RENDERER_CLASSES</a></h4>
<p>The renderer classes that are supported when building test requests.</p>
<p>The format of any of these renderer classes may be used when constructing a test request, for example: <code>client.post('/users', {'username': 'jamie'}, format='json')</code></p>
<p>Default:</p>
@ -567,46 +567,46 @@ If set to <code>None</code> then generic filtering is disabled.</p>
)
</code></pre>
<hr />
<h2 id="content-type-controls">Content type controls</h2>
<h4 id="url_format_override">URL_FORMAT_OVERRIDE</h4>
<h2 id="content-type-controls"><a class="toclink" href="#content-type-controls">Content type controls</a></h2>
<h4 id="url_format_override"><a class="toclink" href="#url_format_override">URL_FORMAT_OVERRIDE</a></h4>
<p>The name of a URL parameter that may be used to override the default content negotiation <code>Accept</code> header behavior, by using a <code>format=…</code> query parameter in the request URL.</p>
<p>For example: <code>http://example.com/organizations/?format=csv</code></p>
<p>If the value of this setting is <code>None</code> then URL format overrides will be disabled.</p>
<p>Default: <code>'format'</code></p>
<h4 id="format_suffix_kwarg">FORMAT_SUFFIX_KWARG</h4>
<h4 id="format_suffix_kwarg"><a class="toclink" href="#format_suffix_kwarg">FORMAT_SUFFIX_KWARG</a></h4>
<p>The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using <code>format_suffix_patterns</code> to include suffixed URL patterns.</p>
<p>For example: <code>http://example.com/organizations.csv/</code></p>
<p>Default: <code>'format'</code></p>
<hr />
<h2 id="date-and-time-formatting">Date and time formatting</h2>
<h2 id="date-and-time-formatting"><a class="toclink" href="#date-and-time-formatting">Date and time formatting</a></h2>
<p><em>The following settings are used to control how date and time representations may be parsed and rendered.</em></p>
<h4 id="datetime_format">DATETIME_FORMAT</h4>
<h4 id="datetime_format"><a class="toclink" href="#datetime_format">DATETIME_FORMAT</a></h4>
<p>A format string that should be used by default for rendering the output of <code>DateTimeField</code> serializer fields. If <code>None</code>, then <code>DateTimeField</code> serializer fields will return Python <code>datetime</code> objects, and the datetime encoding will be determined by the renderer.</p>
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
<p>Default: <code>'iso-8601'</code></p>
<h4 id="datetime_input_formats">DATETIME_INPUT_FORMATS</h4>
<h4 id="datetime_input_formats"><a class="toclink" href="#datetime_input_formats">DATETIME_INPUT_FORMATS</a></h4>
<p>A list of format strings that should be used by default for parsing inputs to <code>DateTimeField</code> serializer fields.</p>
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
<p>Default: <code>['iso-8601']</code></p>
<h4 id="date_format">DATE_FORMAT</h4>
<h4 id="date_format"><a class="toclink" href="#date_format">DATE_FORMAT</a></h4>
<p>A format string that should be used by default for rendering the output of <code>DateField</code> serializer fields. If <code>None</code>, then <code>DateField</code> serializer fields will return Python <code>date</code> objects, and the date encoding will be determined by the renderer.</p>
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
<p>Default: <code>'iso-8601'</code></p>
<h4 id="date_input_formats">DATE_INPUT_FORMATS</h4>
<h4 id="date_input_formats"><a class="toclink" href="#date_input_formats">DATE_INPUT_FORMATS</a></h4>
<p>A list of format strings that should be used by default for parsing inputs to <code>DateField</code> serializer fields.</p>
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
<p>Default: <code>['iso-8601']</code></p>
<h4 id="time_format">TIME_FORMAT</h4>
<h4 id="time_format"><a class="toclink" href="#time_format">TIME_FORMAT</a></h4>
<p>A format string that should be used by default for rendering the output of <code>TimeField</code> serializer fields. If <code>None</code>, then <code>TimeField</code> serializer fields will return Python <code>time</code> objects, and the time encoding will be determined by the renderer.</p>
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
<p>Default: <code>'iso-8601'</code></p>
<h4 id="time_input_formats">TIME_INPUT_FORMATS</h4>
<h4 id="time_input_formats"><a class="toclink" href="#time_input_formats">TIME_INPUT_FORMATS</a></h4>
<p>A list of format strings that should be used by default for parsing inputs to <code>TimeField</code> serializer fields.</p>
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
<p>Default: <code>['iso-8601']</code></p>
<hr />
<h2 id="encodings">Encodings</h2>
<h4 id="unicode_json">UNICODE_JSON</h4>
<h2 id="encodings"><a class="toclink" href="#encodings">Encodings</a></h2>
<h4 id="unicode_json"><a class="toclink" href="#unicode_json">UNICODE_JSON</a></h4>
<p>When set to <code>True</code>, JSON responses will allow unicode characters in responses. For example:</p>
<pre><code>{"unicode black star":"★"}
</code></pre>
@ -615,7 +615,7 @@ If set to <code>None</code> then generic filtering is disabled.</p>
</code></pre>
<p>Both styles conform to <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.</p>
<p>Default: <code>True</code></p>
<h4 id="compact_json">COMPACT_JSON</h4>
<h4 id="compact_json"><a class="toclink" href="#compact_json">COMPACT_JSON</a></h4>
<p>When set to <code>True</code>, JSON responses will return compact representations, with no spacing after <code>':'</code> and <code>','</code> characters. For example:</p>
<pre><code>{"is_admin":false,"email":"jane@example"}
</code></pre>
@ -624,14 +624,14 @@ If set to <code>None</code> then generic filtering is disabled.</p>
</code></pre>
<p>The default style is to return minified responses, in line with <a href="https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses">Heroku's API design guidelines</a>.</p>
<p>Default: <code>True</code></p>
<h4 id="coerce_decimal_to_string">COERCE_DECIMAL_TO_STRING</h4>
<h4 id="coerce_decimal_to_string"><a class="toclink" href="#coerce_decimal_to_string">COERCE_DECIMAL_TO_STRING</a></h4>
<p>When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.</p>
<p>When set to <code>True</code>, the serializer <code>DecimalField</code> class will return strings instead of <code>Decimal</code> objects. When set to <code>False</code>, serializers will return <code>Decimal</code> objects, which the default JSON encoder will return as floats.</p>
<p>Default: <code>True</code></p>
<hr />
<h2 id="view-names-and-descriptions">View names and descriptions</h2>
<h2 id="view-names-and-descriptions"><a class="toclink" href="#view-names-and-descriptions">View names and descriptions</a></h2>
<p><strong>The following settings are used to generate the view names and descriptions, as used in responses to <code>OPTIONS</code> requests, and as used in the browsable API.</strong></p>
<h4 id="view_name_function">VIEW_NAME_FUNCTION</h4>
<h4 id="view_name_function"><a class="toclink" href="#view_name_function">VIEW_NAME_FUNCTION</a></h4>
<p>A string representing the function that should be used when generating view names.</p>
<p>This should be a function with the following signature:</p>
<pre><code>view_name(cls, suffix=None)
@ -641,7 +641,7 @@ If set to <code>None</code> then generic filtering is disabled.</p>
<li><code>suffix</code>: The optional suffix used when differentiating individual views in a viewset.</li>
</ul>
<p>Default: <code>'rest_framework.views.get_view_name'</code></p>
<h4 id="view_description_function">VIEW_DESCRIPTION_FUNCTION</h4>
<h4 id="view_description_function"><a class="toclink" href="#view_description_function">VIEW_DESCRIPTION_FUNCTION</a></h4>
<p>A string representing the function that should be used when generating view descriptions.</p>
<p>This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support <code>rst</code> markup in your view docstrings being output in the browsable API.</p>
<p>This should be a function with the following signature:</p>
@ -653,8 +653,8 @@ If set to <code>None</code> then generic filtering is disabled.</p>
</ul>
<p>Default: <code>'rest_framework.views.get_view_description'</code></p>
<hr />
<h2 id="miscellaneous-settings">Miscellaneous settings</h2>
<h4 id="exception_handler">EXCEPTION_HANDLER</h4>
<h2 id="miscellaneous-settings"><a class="toclink" href="#miscellaneous-settings">Miscellaneous settings</a></h2>
<h4 id="exception_handler"><a class="toclink" href="#exception_handler">EXCEPTION_HANDLER</a></h4>
<p>A string representing the function that should be used when returning a response for any given exception. If the function returns <code>None</code>, a 500 error will be raised.</p>
<p>This setting can be changed to support error responses other than the default <code>{"detail": "Failure..."}</code> responses. For example, you can use it to provide API responses like <code>{"errors": [{"message": "Failure...", "code": ""} ...]}</code>.</p>
<p>This should be a function with the following signature:</p>
@ -664,13 +664,13 @@ If set to <code>None</code> then generic filtering is disabled.</p>
<li><code>exc</code>: The exception.</li>
</ul>
<p>Default: <code>'rest_framework.views.exception_handler'</code></p>
<h4 id="non_field_errors_key">NON_FIELD_ERRORS_KEY</h4>
<h4 id="non_field_errors_key"><a class="toclink" href="#non_field_errors_key">NON_FIELD_ERRORS_KEY</a></h4>
<p>A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.</p>
<p>Default: <code>'non_field_errors'</code></p>
<h4 id="url_field_name">URL_FIELD_NAME</h4>
<h4 id="url_field_name"><a class="toclink" href="#url_field_name">URL_FIELD_NAME</a></h4>
<p>A string representing the key that should be used for the URL fields generated by <code>HyperlinkedModelSerializer</code>.</p>
<p>Default: <code>'url'</code></p>
<h4 id="num_proxies">NUM_PROXIES</h4>
<h4 id="num_proxies"><a class="toclink" href="#num_proxies">NUM_PROXIES</a></h4>
<p>An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to <code>None</code> then less strict IP matching will be used by the throttle classes.</p>
<p>Default: <code>None</code></p>

View File

@ -387,7 +387,7 @@
<h1 id="status-codes">Status Codes</h1>
<h1 id="status-codes"><a class="toclink" href="#status-codes">Status Codes</a></h1>
<blockquote>
<p>418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.</p>
<p>&mdash; <a href="http://www.ietf.org/rfc/rfc2324.txt">RFC 2324</a>, Hyper Text Coffee Pot Control Protocol</p>
@ -413,12 +413,12 @@ class ExampleTestCase(APITestCase):
</code></pre>
<p>For more information on proper usage of HTTP status codes see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">RFC 2616</a>
and <a href="http://tools.ietf.org/html/rfc6585">RFC 6585</a>.</p>
<h2 id="informational-1xx">Informational - 1xx</h2>
<h2 id="informational-1xx"><a class="toclink" href="#informational-1xx">Informational - 1xx</a></h2>
<p>This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.</p>
<pre><code>HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS
</code></pre>
<h2 id="successful-2xx">Successful - 2xx</h2>
<h2 id="successful-2xx"><a class="toclink" href="#successful-2xx">Successful - 2xx</a></h2>
<p>This class of status code indicates that the client's request was successfully received, understood, and accepted.</p>
<pre><code>HTTP_200_OK
HTTP_201_CREATED
@ -428,7 +428,7 @@ HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
</code></pre>
<h2 id="redirection-3xx">Redirection - 3xx</h2>
<h2 id="redirection-3xx"><a class="toclink" href="#redirection-3xx">Redirection - 3xx</a></h2>
<p>This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.</p>
<pre><code>HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
@ -439,7 +439,7 @@ HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
</code></pre>
<h2 id="client-error-4xx">Client Error - 4xx</h2>
<h2 id="client-error-4xx"><a class="toclink" href="#client-error-4xx">Client Error - 4xx</a></h2>
<p>The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.</p>
<pre><code>HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
@ -463,7 +463,7 @@ HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
</code></pre>
<h2 id="server-error-5xx">Server Error - 5xx</h2>
<h2 id="server-error-5xx"><a class="toclink" href="#server-error-5xx">Server Error - 5xx</a></h2>
<p>Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.</p>
<pre><code>HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
@ -473,7 +473,7 @@ HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
</code></pre>
<h2 id="helper-functions">Helper functions</h2>
<h2 id="helper-functions"><a class="toclink" href="#helper-functions">Helper functions</a></h2>
<p>The following helper functions are available for identifying the category of the response code.</p>
<pre><code>is_informational() # 1xx
is_success() # 2xx

View File

@ -437,15 +437,15 @@
<h1 id="testing">Testing</h1>
<h1 id="testing"><a class="toclink" href="#testing">Testing</a></h1>
<blockquote>
<p>Code without tests is broken as designed.</p>
<p>&mdash; <a href="http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper">Jacob Kaplan-Moss</a></p>
</blockquote>
<p>REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.</p>
<h1 id="apirequestfactory">APIRequestFactory</h1>
<h1 id="apirequestfactory"><a class="toclink" href="#apirequestfactory">APIRequestFactory</a></h1>
<p>Extends <a href="https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory">Django's existing <code>RequestFactory</code> class</a>.</p>
<h2 id="creating-test-requests">Creating test requests</h2>
<h2 id="creating-test-requests"><a class="toclink" href="#creating-test-requests">Creating test requests</a></h2>
<p>The <code>APIRequestFactory</code> class supports an almost identical API to Django's standard <code>RequestFactory</code> class. This means that the standard <code>.get()</code>, <code>.post()</code>, <code>.put()</code>, <code>.patch()</code>, <code>.delete()</code>, <code>.head()</code> and <code>.options()</code> methods are all available.</p>
<pre><code>from rest_framework.test import APIRequestFactory
@ -453,7 +453,7 @@
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'})
</code></pre>
<h4 id="using-the-format-argument">Using the <code>format</code> argument</h4>
<h4 id="using-the-format-argument"><a class="toclink" href="#using-the-format-argument">Using the <code>format</code> argument</a></h4>
<p>Methods which create a request body, such as <code>post</code>, <code>put</code> and <code>patch</code>, include a <code>format</code> argument, which make it easy to generate requests using a content type other than multipart form data. For example:</p>
<pre><code># Create a JSON POST request
factory = APIRequestFactory()
@ -461,11 +461,11 @@ request = factory.post('/notes/', {'title': 'new idea'}, format='json')
</code></pre>
<p>By default the available formats are <code>'multipart'</code> and <code>'json'</code>. For compatibility with Django's existing <code>RequestFactory</code> the default format is <code>'multipart'</code>.</p>
<p>To support a wider set of request formats, or change the default format, <a href="#configuration">see the configuration section</a>.</p>
<h4 id="explicitly-encoding-the-request-body">Explicitly encoding the request body</h4>
<h4 id="explicitly-encoding-the-request-body"><a class="toclink" href="#explicitly-encoding-the-request-body">Explicitly encoding the request body</a></h4>
<p>If you need to explicitly encode the request body, you can do so by setting the <code>content_type</code> flag. For example:</p>
<pre><code>request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
</code></pre>
<h4 id="put-and-patch-with-form-data">PUT and PATCH with form data</h4>
<h4 id="put-and-patch-with-form-data"><a class="toclink" href="#put-and-patch-with-form-data">PUT and PATCH with form data</a></h4>
<p>One difference worth noting between Django's <code>RequestFactory</code> and REST framework's <code>APIRequestFactory</code> is that multipart form data will be encoded for methods other than just <code>.post()</code>.</p>
<p>For example, using <code>APIRequestFactory</code>, you can make a form PUT request like so:</p>
<pre><code>factory = APIRequestFactory()
@ -480,7 +480,7 @@ content = encode_multipart('BoUnDaRyStRiNg', data)
content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
request = factory.put('/notes/547/', content, content_type=content_type)
</code></pre>
<h2 id="forcing-authentication">Forcing authentication</h2>
<h2 id="forcing-authentication"><a class="toclink" href="#forcing-authentication">Forcing authentication</a></h2>
<p>When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.</p>
<p>To forcibly authenticate a request, use the <code>force_authenticate()</code> method.</p>
<pre><code>from rest_framework.test import force_authenticate
@ -509,16 +509,16 @@ request.user = user
response = view(request)
</code></pre>
<hr />
<h2 id="forcing-csrf-validation">Forcing CSRF validation</h2>
<h2 id="forcing-csrf-validation"><a class="toclink" href="#forcing-csrf-validation">Forcing CSRF validation</a></h2>
<p>By default, requests created with <code>APIRequestFactory</code> will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the <code>enforce_csrf_checks</code> flag when instantiating the factory.</p>
<pre><code>factory = APIRequestFactory(enforce_csrf_checks=True)
</code></pre>
<hr />
<p><strong>Note</strong>: It's worth noting that Django's standard <code>RequestFactory</code> doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.</p>
<hr />
<h1 id="apiclient">APIClient</h1>
<h1 id="apiclient"><a class="toclink" href="#apiclient">APIClient</a></h1>
<p>Extends <a href="https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client">Django's existing <code>Client</code> class</a>.</p>
<h2 id="making-requests">Making requests</h2>
<h2 id="making-requests"><a class="toclink" href="#making-requests">Making requests</a></h2>
<p>The <code>APIClient</code> class supports the same request interface as Django's standard <code>Client</code> class. This means the that standard <code>.get()</code>, <code>.post()</code>, <code>.put()</code>, <code>.patch()</code>, <code>.delete()</code>, <code>.head()</code> and <code>.options()</code> methods are all available. For example:</p>
<pre><code>from rest_framework.test import APIClient
@ -526,8 +526,8 @@ client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')
</code></pre>
<p>To support a wider set of request formats, or change the default format, <a href="#configuration">see the configuration section</a>.</p>
<h2 id="authenticating">Authenticating</h2>
<h4 id="loginkwargs">.login(**kwargs)</h4>
<h2 id="authenticating"><a class="toclink" href="#authenticating">Authenticating</a></h2>
<h4 id="loginkwargs"><a class="toclink" href="#loginkwargs">.login(**kwargs)</a></h4>
<p>The <code>login</code> method functions exactly as it does with Django's regular <code>Client</code> class. This allows you to authenticate requests against any views which include <code>SessionAuthentication</code>.</p>
<pre><code># Make all requests in the context of a logged in session.
client = APIClient()
@ -538,7 +538,7 @@ client.login(username='lauren', password='secret')
client.logout()
</code></pre>
<p>The <code>login</code> method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.</p>
<h4 id="credentialskwargs">.credentials(**kwargs)</h4>
<h4 id="credentialskwargs"><a class="toclink" href="#credentialskwargs">.credentials(**kwargs)</a></h4>
<p>The <code>credentials</code> method can be used to set headers that will then be included on all subsequent requests by the test client.</p>
<pre><code>from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
@ -553,7 +553,7 @@ client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
client.credentials()
</code></pre>
<p>The <code>credentials</code> method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.</p>
<h4 id="force_authenticateusernone-tokennone">.force_authenticate(user=None, token=None)</h4>
<h4 id="force_authenticateusernone-tokennone"><a class="toclink" href="#force_authenticateusernone-tokennone">.force_authenticate(user=None, token=None)</a></h4>
<p>Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.</p>
<p>This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.</p>
<pre><code>user = User.objects.get(username='lauren')
@ -563,13 +563,13 @@ client.force_authenticate(user=user)
<p>To unauthenticate subsequent requests, call <code>force_authenticate</code> setting the user and/or token to <code>None</code>.</p>
<pre><code>client.force_authenticate(user=None)
</code></pre>
<h2 id="csrf-validation">CSRF validation</h2>
<h2 id="csrf-validation"><a class="toclink" href="#csrf-validation">CSRF validation</a></h2>
<p>By default CSRF validation is not applied when using <code>APIClient</code>. If you need to explicitly enable CSRF validation, you can do so by setting the <code>enforce_csrf_checks</code> flag when instantiating the client.</p>
<pre><code>client = APIClient(enforce_csrf_checks=True)
</code></pre>
<p>As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling <code>login()</code>.</p>
<hr />
<h1 id="test-cases">Test cases</h1>
<h1 id="test-cases"><a class="toclink" href="#test-cases">Test cases</a></h1>
<p>REST framework includes the following test case classes, that mirror the existing Django test case classes, but use <code>APIClient</code> instead of Django's default <code>Client</code>.</p>
<ul>
<li><code>APISimpleTestCase</code></li>
@ -577,7 +577,7 @@ client.force_authenticate(user=user)
<li><code>APITestCase</code></li>
<li><code>APILiveServerTestCase</code></li>
</ul>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>You can use any of REST framework's test case classes as you would for the regular Django test case classes. The <code>self.client</code> attribute will be an <code>APIClient</code> instance.</p>
<pre><code>from django.core.urlresolvers import reverse
from rest_framework import status
@ -597,8 +597,8 @@ class AccountTests(APITestCase):
self.assertEqual(Account.objects.get().name, 'DabApps')
</code></pre>
<hr />
<h1 id="testing-responses">Testing responses</h1>
<h2 id="checking-the-response-data">Checking the response data</h2>
<h1 id="testing-responses"><a class="toclink" href="#testing-responses">Testing responses</a></h1>
<h2 id="checking-the-response-data"><a class="toclink" href="#checking-the-response-data">Checking the response data</a></h2>
<p>When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.</p>
<p>For example, it's easier to inspect <code>response.data</code>:</p>
<pre><code>response = self.client.get('/users/4/')
@ -608,7 +608,7 @@ self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
<pre><code>response = self.client.get('/users/4/')
self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
</code></pre>
<h2 id="rendering-responses">Rendering responses</h2>
<h2 id="rendering-responses"><a class="toclink" href="#rendering-responses">Rendering responses</a></h2>
<p>If you're testing views directly using <code>APIRequestFactory</code>, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access <code>response.content</code>, you'll first need to render the response.</p>
<pre><code>view = UserDetail.as_view()
request = factory.get('/users/4')
@ -617,15 +617,15 @@ response.render() # Cannot access `response.content` without this.
self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
</code></pre>
<hr />
<h1 id="configuration">Configuration</h1>
<h2 id="setting-the-default-format">Setting the default format</h2>
<h1 id="configuration"><a class="toclink" href="#configuration">Configuration</a></h1>
<h2 id="setting-the-default-format"><a class="toclink" href="#setting-the-default-format">Setting the default format</a></h2>
<p>The default format used to make test requests may be set using the <code>TEST_REQUEST_DEFAULT_FORMAT</code> setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your <code>settings.py</code> file:</p>
<pre><code>REST_FRAMEWORK = {
...
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}
</code></pre>
<h2 id="setting-the-available-formats">Setting the available formats</h2>
<h2 id="setting-the-available-formats"><a class="toclink" href="#setting-the-available-formats">Setting the available formats</a></h2>
<p>If you need to test requests using something other than multipart or json requests, you can do so by setting the <code>TEST_REQUEST_RENDERER_CLASSES</code> setting.</p>
<p>For example, to add support for using <code>format='html'</code> in test requests, you might have something like this in your <code>settings.py</code> file.</p>
<pre><code>REST_FRAMEWORK = {

View File

@ -407,7 +407,7 @@
<h1 id="throttling">Throttling</h1>
<h1 id="throttling"><a class="toclink" href="#throttling">Throttling</a></h1>
<blockquote>
<p>HTTP/1.1 420 Enhance Your Calm</p>
<p><a href="https://dev.twitter.com/docs/error-codes-responses">Twitter API rate limiting response</a></p>
@ -417,11 +417,11 @@
<p>Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.</p>
<p>Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.</p>
<p>Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.</p>
<h2 id="how-throttling-is-determined">How throttling is determined</h2>
<h2 id="how-throttling-is-determined"><a class="toclink" href="#how-throttling-is-determined">How throttling is determined</a></h2>
<p>As with permissions and authentication, throttling in REST framework is always defined as a list of classes.</p>
<p>Before running the main body of the view each throttle in the list is checked.
If any throttle check fails an <code>exceptions.Throttled</code> exception will be raised, and the main body of the view will not run.</p>
<h2 id="setting-the-throttling-policy">Setting the throttling policy</h2>
<h2 id="setting-the-throttling-policy"><a class="toclink" href="#setting-the-throttling-policy">Setting the throttling policy</a></h2>
<p>The default throttling policy may be set globally, using the <code>DEFAULT_THROTTLE_CLASSES</code> and <code>DEFAULT_THROTTLE_RATES</code> settings. For example.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
@ -459,12 +459,12 @@ def example_view(request, format=None):
}
return Response(content)
</code></pre>
<h2 id="how-clients-are-identified">How clients are identified</h2>
<h2 id="how-clients-are-identified"><a class="toclink" href="#how-clients-are-identified">How clients are identified</a></h2>
<p>The <code>X-Forwarded-For</code> and <code>Remote-Addr</code> HTTP headers are used to uniquely identify client IP addresses for throttling. If the <code>X-Forwarded-For</code> header is present then it will be used, otherwise the value of the <code>Remote-Addr</code> header will be used.</p>
<p>If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the <code>NUM_PROXIES</code> setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the <code>X-Forwarded-For</code> header, once any application proxy IP addresses have first been excluded. If set to zero, then the <code>Remote-Addr</code> header will always be used as the identifying IP address.</p>
<p>It is important to understand that if you configure the <code>NUM_PROXIES</code> setting, then all clients behind a unique <a href="http://en.wikipedia.org/wiki/Network_address_translation">NAT'd</a> gateway will be treated as a single client.</p>
<p>Further context on how the <code>X-Forwarded-For</code> header works, and identifying a remote client IP can be <a href="http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster">found here</a>.</p>
<h2 id="setting-up-the-cache">Setting up the cache</h2>
<h2 id="setting-up-the-cache"><a class="toclink" href="#setting-up-the-cache">Setting up the cache</a></h2>
<p>The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate <a href="https://docs.djangoproject.com/en/dev/ref/settings/#caches">cache settings</a>. The default value of <code>LocMemCache</code> backend should be okay for simple setups. See Django's <a href="https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache">cache documentation</a> for more details.</p>
<p>If you need to use a cache other than <code>'default'</code>, you can do so by creating a custom throttle class and setting the <code>cache</code> attribute. For example:</p>
<pre><code>class CustomAnonRateThrottle(AnonRateThrottle):
@ -472,8 +472,8 @@ def example_view(request, format=None):
</code></pre>
<p>You'll need to remember to also set your custom throttle class in the <code>'DEFAULT_THROTTLE_CLASSES'</code> settings key, or using the <code>throttle_classes</code> view attribute.</p>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="anonratethrottle">AnonRateThrottle</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="anonratethrottle"><a class="toclink" href="#anonratethrottle">AnonRateThrottle</a></h2>
<p>The <code>AnonRateThrottle</code> will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.</p>
<p>The allowed request rate is determined from one of the following (in order of preference).</p>
<ul>
@ -481,7 +481,7 @@ def example_view(request, format=None):
<li>The <code>DEFAULT_THROTTLE_RATES['anon']</code> setting.</li>
</ul>
<p><code>AnonRateThrottle</code> is suitable if you want to restrict the rate of requests from unknown sources.</p>
<h2 id="userratethrottle">UserRateThrottle</h2>
<h2 id="userratethrottle"><a class="toclink" href="#userratethrottle">UserRateThrottle</a></h2>
<p>The <code>UserRateThrottle</code> will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.</p>
<p>The allowed request rate is determined from one of the following (in order of preference).</p>
<ul>
@ -509,7 +509,7 @@ class SustainedRateThrottle(UserRateThrottle):
}
</code></pre>
<p><code>UserRateThrottle</code> is suitable if you want simple global rate restrictions per-user.</p>
<h2 id="scopedratethrottle">ScopedRateThrottle</h2>
<h2 id="scopedratethrottle"><a class="toclink" href="#scopedratethrottle">ScopedRateThrottle</a></h2>
<p>The <code>ScopedRateThrottle</code> class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a <code>.throttle_scope</code> property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.</p>
<p>The allowed request rate is determined by the <code>DEFAULT_THROTTLE_RATES</code> setting using a key from the request "scope".</p>
<p>For example, given the following views...</p>
@ -538,11 +538,11 @@ class UploadView(APIView):
</code></pre>
<p>User requests to either <code>ContactListView</code> or <code>ContactDetailView</code> would be restricted to a total of 1000 requests per-day. User requests to <code>UploadView</code> would be restricted to 20 requests per day.</p>
<hr />
<h1 id="custom-throttles">Custom throttles</h1>
<h1 id="custom-throttles"><a class="toclink" href="#custom-throttles">Custom throttles</a></h1>
<p>To create a custom throttle, override <code>BaseThrottle</code> and implement <code>.allow_request(self, request, view)</code>. The method should return <code>True</code> if the request should be allowed, and <code>False</code> otherwise.</p>
<p>Optionally you may also override the <code>.wait()</code> method. If implemented, <code>.wait()</code> should return a recommended number of seconds to wait before attempting the next request, or <code>None</code>. The <code>.wait()</code> method will only be called if <code>.allow_request()</code> has previously returned <code>False</code>.</p>
<p>If the <code>.wait()</code> method is implemented and the request is throttled, then a <code>Retry-After</code> header will be included in the response.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.</p>
<pre><code>class RandomRateThrottle(throttling.BaseThrottle):
def allow_request(self, request, view):

View File

@ -415,14 +415,14 @@
<h1 id="validators">Validators</h1>
<h1 id="validators"><a class="toclink" href="#validators">Validators</a></h1>
<blockquote>
<p>Validators can be useful for re-using validation logic between different types of fields.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/dev/ref/validators/">Django documentation</a></p>
</blockquote>
<p>Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.</p>
<p>However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.</p>
<h2 id="validation-in-rest-framework">Validation in REST framework</h2>
<h2 id="validation-in-rest-framework"><a class="toclink" href="#validation-in-rest-framework">Validation in REST framework</a></h2>
<p>Validation in Django REST framework serializers is handled a little differently to how validation works in Django's <code>ModelForm</code> class.</p>
<p>With <code>ModelForm</code> the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:</p>
<ul>
@ -431,7 +431,7 @@
<li>Printing the <code>repr</code> of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.</li>
</ul>
<p>When you're using <code>ModelSerializer</code> all of this is handled automatically for you. If you want to drop down to using a <code>Serializer</code> classes instead, then you need to define the validation rules explicitly.</p>
<h4 id="example">Example</h4>
<h4 id="example"><a class="toclink" href="#example">Example</a></h4>
<p>As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.</p>
<pre><code>class CustomerReportRecord(models.Model):
time_raised = models.DateTimeField(default=timezone.now, editable=False)
@ -456,7 +456,7 @@ CustomerReportSerializer():
<p>The interesting bit here is the <code>reference</code> field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.</p>
<p>Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.</p>
<hr />
<h2 id="uniquevalidator">UniqueValidator</h2>
<h2 id="uniquevalidator"><a class="toclink" href="#uniquevalidator">UniqueValidator</a></h2>
<p>This validator can be used to enforce the <code>unique=True</code> constraint on model fields.
It takes a single required argument, and an optional <code>messages</code> argument:</p>
<ul>
@ -469,7 +469,7 @@ It takes a single required argument, and an optional <code>messages</code> argum
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
)
</code></pre>
<h2 id="uniquetogethervalidator">UniqueTogetherValidator</h2>
<h2 id="uniquetogethervalidator"><a class="toclink" href="#uniquetogethervalidator">UniqueTogetherValidator</a></h2>
<p>This validator can be used to enforce <code>unique_together</code> constraints on model instances.
It has two required arguments, and a single optional <code>messages</code> argument:</p>
<ul>
@ -494,9 +494,9 @@ It has two required arguments, and a single optional <code>messages</code> argum
<hr />
<p><strong>Note</strong>: The <code>UniqueTogetherValidation</code> class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with <code>default</code> values are an exception to this as they always supply a value even when omitted from user input.</p>
<hr />
<h2 id="uniquefordatevalidator">UniqueForDateValidator</h2>
<h2 id="uniqueformonthvalidator">UniqueForMonthValidator</h2>
<h2 id="uniqueforyearvalidator">UniqueForYearValidator</h2>
<h2 id="uniquefordatevalidator"><a class="toclink" href="#uniquefordatevalidator">UniqueForDateValidator</a></h2>
<h2 id="uniqueformonthvalidator"><a class="toclink" href="#uniqueformonthvalidator">UniqueForMonthValidator</a></h2>
<h2 id="uniqueforyearvalidator"><a class="toclink" href="#uniqueforyearvalidator">UniqueForYearValidator</a></h2>
<p>These validators can be used to enforce the <code>unique_for_date</code>, <code>unique_for_month</code> and <code>unique_for_year</code> constraints on model instances. They take the following arguments:</p>
<ul>
<li><code>queryset</code> <em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
@ -519,23 +519,23 @@ It has two required arguments, and a single optional <code>messages</code> argum
</code></pre>
<p>The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class <code>default=...</code>, because the value being used for the default wouldn't be generated until after the validation has run.</p>
<p>There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using <code>ModelSerializer</code> you'll probably simply rely on the defaults that REST framework generates for you, but if you are using <code>Serializer</code> or simply want more explicit control, use on of the styles demonstrated below.</p>
<h4 id="using-with-a-writable-date-field">Using with a writable date field.</h4>
<h4 id="using-with-a-writable-date-field"><a class="toclink" href="#using-with-a-writable-date-field">Using with a writable date field.</a></h4>
<p>If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a <code>default</code> argument, or by setting <code>required=True</code>.</p>
<pre><code>published = serializers.DateTimeField(required=True)
</code></pre>
<h4 id="using-with-a-read-only-date-field">Using with a read-only date field.</h4>
<h4 id="using-with-a-read-only-date-field"><a class="toclink" href="#using-with-a-read-only-date-field">Using with a read-only date field.</a></h4>
<p>If you want the date field to be visible, but not editable by the user, then set <code>read_only=True</code> and additionally set a <code>default=...</code> argument.</p>
<pre><code>published = serializers.DateTimeField(read_only=True, default=timezone.now)
</code></pre>
<p>The field will not be writable to the user, but the default value will still be passed through to the <code>validated_data</code>.</p>
<h4 id="using-with-a-hidden-date-field">Using with a hidden date field.</h4>
<h4 id="using-with-a-hidden-date-field"><a class="toclink" href="#using-with-a-hidden-date-field">Using with a hidden date field.</a></h4>
<p>If you want the date field to be entirely hidden from the user, then use <code>HiddenField</code>. This field type does not accept user input, but instead always returns it's default value to the <code>validated_data</code> in the serializer.</p>
<pre><code>published = serializers.HiddenField(default=timezone.now)
</code></pre>
<hr />
<p><strong>Note</strong>: The <code>UniqueFor&lt;Range&gt;Validation</code> classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with <code>default</code> values are an exception to this as they always supply a value even when omitted from user input.</p>
<hr />
<h1 id="advanced-default-argument-usage">Advanced 'default' argument usage</h1>
<h1 id="advanced-default-argument-usage"><a class="toclink" href="#advanced-default-argument-usage">Advanced 'default' argument usage</a></h1>
<p>Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that <em>is</em> available as input to the validator.</p>
<p>Two patterns that you may want to use for this sort of validation include:</p>
<ul>
@ -543,13 +543,13 @@ It has two required arguments, and a single optional <code>messages</code> argum
<li>Using a standard field with <code>read_only=True</code>, but that also includes a <code>default=…</code> argument. This field <em>will</em> be used in the serializer output representation, but cannot be set directly by the user.</li>
</ul>
<p>REST framework includes a couple of defaults that may be useful in this context.</p>
<h4 id="currentuserdefault">CurrentUserDefault</h4>
<h4 id="currentuserdefault"><a class="toclink" href="#currentuserdefault">CurrentUserDefault</a></h4>
<p>A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.</p>
<pre><code>owner = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
</code></pre>
<h4 id="createonlydefault">CreateOnlyDefault</h4>
<h4 id="createonlydefault"><a class="toclink" href="#createonlydefault">CreateOnlyDefault</a></h4>
<p>A default class that can be used to <em>only set a default argument during create operations</em>. During updates the field is omitted.</p>
<p>It takes a single argument, which is the default value or callable that should be used during create operations.</p>
<pre><code>created_at = serializers.DateTimeField(
@ -558,15 +558,15 @@ It has two required arguments, and a single optional <code>messages</code> argum
)
</code></pre>
<hr />
<h1 id="writing-custom-validators">Writing custom validators</h1>
<h1 id="writing-custom-validators"><a class="toclink" href="#writing-custom-validators">Writing custom validators</a></h1>
<p>You can use any of Django's existing validators, or write your own custom validators.</p>
<h2 id="function-based">Function based</h2>
<h2 id="function-based"><a class="toclink" href="#function-based">Function based</a></h2>
<p>A validator may be any callable that raises a <code>serializers.ValidationError</code> on failure.</p>
<pre><code>def even_number(value):
if value % 2 != 0:
raise serializers.ValidationError('This field must be an even number.')
</code></pre>
<h2 id="class-based">Class based</h2>
<h2 id="class-based"><a class="toclink" href="#class-based">Class based</a></h2>
<p>To write a class based validator, use the <code>__call__</code> method. Class based validators are useful as they allow you to parameterize and reuse behavior.</p>
<pre><code>class MultipleOf(object):
def __init__(self, base):
@ -577,7 +577,7 @@ It has two required arguments, and a single optional <code>messages</code> argum
message = 'This field must be a multiple of %d.' % self.base
raise serializers.ValidationError(message)
</code></pre>
<h4 id="using-set_context">Using <code>set_context()</code></h4>
<h4 id="using-set_context"><a class="toclink" href="#using-set_context">Using <code>set_context()</code></a></h4>
<p>In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a <code>set_context</code> method on a class based validator.</p>
<pre><code>def set_context(self, serializer_field):
# Determine if this is an update or a create operation.

View File

@ -407,7 +407,7 @@
<h1 id="versioning">Versioning</h1>
<h1 id="versioning"><a class="toclink" href="#versioning">Versioning</a></h1>
<blockquote>
<p>Versioning an interface is just a "polite" way to kill deployed clients.</p>
<p>&mdash; <a href="http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31">Roy Fielding</a>.</p>
@ -415,17 +415,17 @@
<p>API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.</p>
<p>Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.</p>
<p>There are a number of valid approaches to approaching versioning. <a href="http://www.infoq.com/articles/roy-fielding-on-versioning">Non-versioned systems can also be appropriate</a>, particularly if you're engineering for very long-term systems with multiple clients outside of your control.</p>
<h2 id="versioning-with-rest-framework">Versioning with REST framework</h2>
<h2 id="versioning-with-rest-framework"><a class="toclink" href="#versioning-with-rest-framework">Versioning with REST framework</a></h2>
<p>When API versioning is enabled, the <code>request.version</code> attribute will contain a string that corresponds to the version requested in the incoming client request.</p>
<p>By default, versioning is not enabled, and <code>request.version</code> will always return <code>None</code>.</p>
<h4 id="varying-behavior-based-on-the-version">Varying behavior based on the version</h4>
<h4 id="varying-behavior-based-on-the-version"><a class="toclink" href="#varying-behavior-based-on-the-version">Varying behavior based on the version</a></h4>
<p>How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:</p>
<pre><code>def get_serializer_class(self):
if self.request.version == 'v1':
return AccountSerializerVersion1
return AccountSerializer
</code></pre>
<h4 id="reversing-urls-for-versioned-apis">Reversing URLs for versioned APIs</h4>
<h4 id="reversing-urls-for-versioned-apis"><a class="toclink" href="#reversing-urls-for-versioned-apis">Reversing URLs for versioned APIs</a></h4>
<p>The <code>reverse</code> function included by REST framework ties in with the versioning scheme. You need to make sure to include the current <code>request</code> as a keyword argument, like so.</p>
<pre><code>from rest_framework.reverse import reverse
@ -436,7 +436,7 @@ reverse('bookings-list', request=request)
<li>If <code>NamespacedVersioning</code> was being used, and the API version was 'v1', then the URL lookup used would be <code>'v1:bookings-list'</code>, which might resolve to a URL like <code>http://example.org/v1/bookings/</code>.</li>
<li>If <code>QueryParameterVersioning</code> was being used, and the API version was <code>1.0</code>, then the returned URL might be something like <code>http://example.org/bookings/?version=1.0</code></li>
</ul>
<h4 id="versioned-apis-and-hyperlinked-serializers">Versioned APIs and hyperlinked serializers</h4>
<h4 id="versioned-apis-and-hyperlinked-serializers"><a class="toclink" href="#versioned-apis-and-hyperlinked-serializers">Versioned APIs and hyperlinked serializers</a></h4>
<p>When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.</p>
<pre><code>def get(self, request):
queryset = Booking.objects.all()
@ -444,7 +444,7 @@ reverse('bookings-list', request=request)
return Response({'all_bookings': serializer.data})
</code></pre>
<p>Doing so will allow any returned URLs to include the appropriate versioning.</p>
<h2 id="configuring-the-versioning-scheme">Configuring the versioning scheme</h2>
<h2 id="configuring-the-versioning-scheme"><a class="toclink" href="#configuring-the-versioning-scheme">Configuring the versioning scheme</a></h2>
<p>The versioning scheme is defined by the <code>DEFAULT_VERSIONING_CLASS</code> settings key.</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
@ -455,7 +455,7 @@ reverse('bookings-list', request=request)
<pre><code>class ProfileList(APIView):
versioning_class = versioning.QueryParameterVersioning
</code></pre>
<h4 id="other-versioning-settings">Other versioning settings</h4>
<h4 id="other-versioning-settings"><a class="toclink" href="#other-versioning-settings">Other versioning settings</a></h4>
<p>The following settings keys are also used to control versioning:</p>
<ul>
<li><code>DEFAULT_VERSION</code>. The value that should be used for <code>request.version</code> when no versioning information is present. Defaults to <code>None</code>.</li>
@ -475,8 +475,8 @@ class ExampleView(APIVIew):
versioning_class = ExampleVersioning
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="acceptheaderversioning">AcceptHeaderVersioning</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="acceptheaderversioning"><a class="toclink" href="#acceptheaderversioning">AcceptHeaderVersioning</a></h2>
<p>This scheme requires the client to specify the version as part of the media type in the <code>Accept</code> header. The version is included as a media type parameter, that supplements the main media type.</p>
<p>Here's an example HTTP request using the accept header versioning style.</p>
<pre><code>GET /bookings/ HTTP/1.1
@ -485,7 +485,7 @@ Accept: application/json; version=1.0
</code></pre>
<p>In the example request above <code>request.version</code> attribute would return the string <code>'1.0'</code>.</p>
<p>Versioning based on accept headers is <a href="http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned">generally considered</a> as <a href="https://github.com/interagent/http-api-design#version-with-accepts-header">best practice</a>, although other styles may be suitable depending on your client requirements.</p>
<h4 id="using-accept-headers-with-vendor-media-types">Using accept headers with vendor media types</h4>
<h4 id="using-accept-headers-with-vendor-media-types"><a class="toclink" href="#using-accept-headers-with-vendor-media-types">Using accept headers with vendor media types</a></h4>
<p>Strictly speaking the <code>json</code> media type is not specified as <a href="http://tools.ietf.org/html/rfc4627#section-6">including additional parameters</a>. If you are building a well-specified public API you might consider using a <a href="http://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree">vendor media type</a>. To do so, configure your renderers to use a JSON based renderer with a custom media type:</p>
<pre><code>class BookingsAPIRenderer(JSONRenderer):
media_type = 'application/vnd.megacorp.bookings+json'
@ -495,7 +495,7 @@ Accept: application/json; version=1.0
Host: example.com
Accept: application/vnd.megacorp.bookings+json; version=1.0
</code></pre>
<h2 id="urlpathversioning">URLPathVersioning</h2>
<h2 id="urlpathversioning"><a class="toclink" href="#urlpathversioning">URLPathVersioning</a></h2>
<p>This scheme requires the client to specify the version as part of the URL path.</p>
<pre><code>GET /v1/bookings/ HTTP/1.1
Host: example.com
@ -515,7 +515,7 @@ Accept: application/json
)
]
</code></pre>
<h2 id="namespaceversioning">NamespaceVersioning</h2>
<h2 id="namespaceversioning"><a class="toclink" href="#namespaceversioning">NamespaceVersioning</a></h2>
<p>To the client, this scheme is the same as <code>URLParameterVersioning</code>. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.</p>
<pre><code>GET /v1/something/ HTTP/1.1
Host: example.com
@ -536,7 +536,7 @@ urlpatterns = [
]
</code></pre>
<p>Both <code>URLParameterVersioning</code> and <code>NamespaceVersioning</code> are reasonable if you just need a simple versioning scheme. The <code>URLParameterVersioning</code> approach might be better suitable for small ad-hoc projects, and the <code>NamespaceVersioning</code> is probably easier to manage for larger projects.</p>
<h2 id="hostnameversioning">HostNameVersioning</h2>
<h2 id="hostnameversioning"><a class="toclink" href="#hostnameversioning">HostNameVersioning</a></h2>
<p>The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.</p>
<p>For example the following is an HTTP request to the <code>http://v1.example.com/bookings/</code> URL:</p>
<pre><code>GET /bookings/ HTTP/1.1
@ -549,16 +549,16 @@ Accept: application/json
<p>Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.</p>
<p>The <code>HostNameVersioning</code> scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as <code>127.0.0.1</code>. There are various online services which you to <a href="https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains">access localhost with a custom subdomain</a> which you may find helpful in this case.</p>
<p>Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.</p>
<h2 id="queryparameterversioning">QueryParameterVersioning</h2>
<h2 id="queryparameterversioning"><a class="toclink" href="#queryparameterversioning">QueryParameterVersioning</a></h2>
<p>This scheme is a simple style that includes the version as a query parameter in the URL. For example:</p>
<pre><code>GET /something/?version=0.1 HTTP/1.1
Host: example.com
Accept: application/json
</code></pre>
<hr />
<h1 id="custom-versioning-schemes">Custom versioning schemes</h1>
<h1 id="custom-versioning-schemes"><a class="toclink" href="#custom-versioning-schemes">Custom versioning schemes</a></h1>
<p>To implement a custom versioning scheme, subclass <code>BaseVersioning</code> and override the <code>.determine_version</code> method.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following example uses a custom <code>X-API-Version</code> header to determine the requested version.</p>
<pre><code>class XAPIVersionScheme(versioning.BaseVersioning):
def determine_version(self, request, *args, **kwargs):

View File

@ -397,7 +397,7 @@
<h1 id="class-based-views">Class Based Views</h1>
<h1 id="class-based-views"><a class="toclink" href="#class-based-views">Class Based Views</a></h1>
<blockquote>
<p>Django's class based views are a welcome departure from the old-style views.</p>
<p>&mdash; <a href="http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html">Reinout van Rees</a></p>
@ -433,52 +433,52 @@ class ListUsers(APIView):
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
</code></pre>
<h2 id="api-policy-attributes">API policy attributes</h2>
<h2 id="api-policy-attributes"><a class="toclink" href="#api-policy-attributes">API policy attributes</a></h2>
<p>The following attributes control the pluggable aspects of API views.</p>
<h3 id="renderer_classes">.renderer_classes</h3>
<h3 id="parser_classes">.parser_classes</h3>
<h3 id="authentication_classes">.authentication_classes</h3>
<h3 id="throttle_classes">.throttle_classes</h3>
<h3 id="permission_classes">.permission_classes</h3>
<h3 id="content_negotiation_class">.content_negotiation_class</h3>
<h2 id="api-policy-instantiation-methods">API policy instantiation methods</h2>
<h3 id="renderer_classes"><a class="toclink" href="#renderer_classes">.renderer_classes</a></h3>
<h3 id="parser_classes"><a class="toclink" href="#parser_classes">.parser_classes</a></h3>
<h3 id="authentication_classes"><a class="toclink" href="#authentication_classes">.authentication_classes</a></h3>
<h3 id="throttle_classes"><a class="toclink" href="#throttle_classes">.throttle_classes</a></h3>
<h3 id="permission_classes"><a class="toclink" href="#permission_classes">.permission_classes</a></h3>
<h3 id="content_negotiation_class"><a class="toclink" href="#content_negotiation_class">.content_negotiation_class</a></h3>
<h2 id="api-policy-instantiation-methods"><a class="toclink" href="#api-policy-instantiation-methods">API policy instantiation methods</a></h2>
<p>The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.</p>
<h3 id="get_renderersself">.get_renderers(self)</h3>
<h3 id="get_parsersself">.get_parsers(self)</h3>
<h3 id="get_authenticatorsself">.get_authenticators(self)</h3>
<h3 id="get_throttlesself">.get_throttles(self)</h3>
<h3 id="get_permissionsself">.get_permissions(self)</h3>
<h3 id="get_content_negotiatorself">.get_content_negotiator(self)</h3>
<h2 id="api-policy-implementation-methods">API policy implementation methods</h2>
<h3 id="get_renderersself"><a class="toclink" href="#get_renderersself">.get_renderers(self)</a></h3>
<h3 id="get_parsersself"><a class="toclink" href="#get_parsersself">.get_parsers(self)</a></h3>
<h3 id="get_authenticatorsself"><a class="toclink" href="#get_authenticatorsself">.get_authenticators(self)</a></h3>
<h3 id="get_throttlesself"><a class="toclink" href="#get_throttlesself">.get_throttles(self)</a></h3>
<h3 id="get_permissionsself"><a class="toclink" href="#get_permissionsself">.get_permissions(self)</a></h3>
<h3 id="get_content_negotiatorself"><a class="toclink" href="#get_content_negotiatorself">.get_content_negotiator(self)</a></h3>
<h2 id="api-policy-implementation-methods"><a class="toclink" href="#api-policy-implementation-methods">API policy implementation methods</a></h2>
<p>The following methods are called before dispatching to the handler method.</p>
<h3 id="check_permissionsself-request">.check_permissions(self, request)</h3>
<h3 id="check_throttlesself-request">.check_throttles(self, request)</h3>
<h3 id="perform_content_negotiationself-request-forcefalse">.perform_content_negotiation(self, request, force=False)</h3>
<h2 id="dispatch-methods">Dispatch methods</h2>
<h3 id="check_permissionsself-request"><a class="toclink" href="#check_permissionsself-request">.check_permissions(self, request)</a></h3>
<h3 id="check_throttlesself-request"><a class="toclink" href="#check_throttlesself-request">.check_throttles(self, request)</a></h3>
<h3 id="perform_content_negotiationself-request-forcefalse"><a class="toclink" href="#perform_content_negotiationself-request-forcefalse">.perform_content_negotiation(self, request, force=False)</a></h3>
<h2 id="dispatch-methods"><a class="toclink" href="#dispatch-methods">Dispatch methods</a></h2>
<p>The following methods are called directly by the view's <code>.dispatch()</code> method.
These perform any actions that need to occur before or after calling the handler methods such as <code>.get()</code>, <code>.post()</code>, <code>put()</code>, <code>patch()</code> and <code>.delete()</code>.</p>
<h3 id="initialself-request-42args-kwargs">.initial(self, request, *args, **kwargs)</h3>
<h3 id="initialself-request-42args-kwargs"><a class="toclink" href="#initialself-request-42args-kwargs">.initial(self, request, *args, **kwargs)</a></h3>
<p>Performs any actions that need to occur before the handler method gets called.
This method is used to enforce permissions and throttling, and perform content negotiation.</p>
<p>You won't typically need to override this method.</p>
<h3 id="handle_exceptionself-exc">.handle_exception(self, exc)</h3>
<h3 id="handle_exceptionself-exc"><a class="toclink" href="#handle_exceptionself-exc">.handle_exception(self, exc)</a></h3>
<p>Any exception thrown by the handler method will be passed to this method, which either returns a <code>Response</code> instance, or re-raises the exception.</p>
<p>The default implementation handles any subclass of <code>rest_framework.exceptions.APIException</code>, as well as Django's <code>Http404</code> and <code>PermissionDenied</code> exceptions, and returns an appropriate error response.</p>
<p>If you need to customize the error responses your API returns you should subclass this method.</p>
<h3 id="initialize_requestself-request-42args-kwargs">.initialize_request(self, request, *args, **kwargs)</h3>
<h3 id="initialize_requestself-request-42args-kwargs"><a class="toclink" href="#initialize_requestself-request-42args-kwargs">.initialize_request(self, request, *args, **kwargs)</a></h3>
<p>Ensures that the request object that is passed to the handler method is an instance of <code>Request</code>, rather than the usual Django <code>HttpRequest</code>.</p>
<p>You won't typically need to override this method.</p>
<h3 id="finalize_responseself-request-response-42args-kwargs">.finalize_response(self, request, response, *args, **kwargs)</h3>
<h3 id="finalize_responseself-request-response-42args-kwargs"><a class="toclink" href="#finalize_responseself-request-response-42args-kwargs">.finalize_response(self, request, response, *args, **kwargs)</a></h3>
<p>Ensures that any <code>Response</code> object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.</p>
<p>You won't typically need to override this method.</p>
<hr />
<h1 id="function-based-views">Function Based Views</h1>
<h1 id="function-based-views"><a class="toclink" href="#function-based-views">Function Based Views</a></h1>
<blockquote>
<p>Saying [that Class based views] is always the superior solution is a mistake.</p>
<p>&mdash; <a href="http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html">Nick Coghlan</a></p>
</blockquote>
<p>REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of <code>Request</code> (rather than the usual Django <code>HttpRequest</code>) and allows them to return a <code>Response</code> (instead of a Django <code>HttpResponse</code>), and allow you to configure how the request is processed.</p>
<h2 id="api_view">@api_view()</h2>
<h2 id="api_view"><a class="toclink" href="#api_view">@api_view()</a></h2>
<p><strong>Signature:</strong> <code>@api_view(http_method_names=['GET'])</code></p>
<p>The core of this functionality is the <code>api_view</code> decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:</p>
<pre><code>from rest_framework.decorators import api_view
@ -495,7 +495,7 @@ def hello_world(request):
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
</code></pre>
<h2 id="api-policy-decorators">API policy decorators</h2>
<h2 id="api-policy-decorators"><a class="toclink" href="#api-policy-decorators">API policy decorators</a></h2>
<p>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come <em>after</em> (below) the <code>@api_view</code> decorator. For example, to create a view that uses a <a href="../throttling/">throttle</a> to ensure it can only be called once per day by a particular user, use the <code>@throttle_classes</code> decorator, passing a list of throttle classes:</p>
<pre><code>from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle

View File

@ -403,7 +403,7 @@
<h1 id="viewsets">ViewSets</h1>
<h1 id="viewsets"><a class="toclink" href="#viewsets">ViewSets</a></h1>
<blockquote>
<p>After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.</p>
<p>&mdash; <a href="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
@ -412,7 +412,7 @@
<p>A <code>ViewSet</code> class is simply <strong>a type of class-based View, that does not provide any method handlers</strong> such as <code>.get()</code> or <code>.post()</code>, and instead provides actions such as <code>.list()</code> and <code>.create()</code>.</p>
<p>The method handlers for a <code>ViewSet</code> are only bound to the corresponding actions at the point of finalizing the view, using the <code>.as_view()</code> method.</p>
<p>Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>Let's define a simple viewset that can be used to list or retrieve all the users in the system.</p>
<pre><code>from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
@ -461,7 +461,7 @@ urlpatterns = router.urls
<li>By using routers, we no longer need to deal with wiring up the URL conf ourselves.</li>
</ul>
<p>Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.</p>
<h2 id="marking-extra-actions-for-routing">Marking extra actions for routing</h2>
<h2 id="marking-extra-actions-for-routing"><a class="toclink" href="#marking-extra-actions-for-routing">Marking extra actions for routing</a></h2>
<p>The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:</p>
<pre><code>class UserViewSet(viewsets.ViewSet):
"""
@ -543,17 +543,17 @@ class UserViewSet(viewsets.ModelViewSet):
</code></pre>
<p>The two new actions will then be available at the urls <code>^users/{pk}/set_password/$</code> and <code>^users/{pk}/unset_password/$</code></p>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="viewset">ViewSet</h2>
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
<h2 id="viewset"><a class="toclink" href="#viewset">ViewSet</a></h2>
<p>The <code>ViewSet</code> class inherits from <code>APIView</code>. You can use any of the standard attributes such as <code>permission_classes</code>, <code>authentication_classes</code> in order to control the API policy on the viewset.</p>
<p>The <code>ViewSet</code> class does not provide any implementations of actions. In order to use a <code>ViewSet</code> class you'll override the class and define the action implementations explicitly.</p>
<h2 id="genericviewset">GenericViewSet</h2>
<h2 id="genericviewset"><a class="toclink" href="#genericviewset">GenericViewSet</a></h2>
<p>The <code>GenericViewSet</code> class inherits from <code>GenericAPIView</code>, and provides the default set of <code>get_object</code>, <code>get_queryset</code> methods and other generic view base behavior, but does not include any actions by default.</p>
<p>In order to use a <code>GenericViewSet</code> class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.</p>
<h2 id="modelviewset">ModelViewSet</h2>
<h2 id="modelviewset"><a class="toclink" href="#modelviewset">ModelViewSet</a></h2>
<p>The <code>ModelViewSet</code> class inherits from <code>GenericAPIView</code> and includes implementations for various actions, by mixing in the behavior of the various mixin classes.</p>
<p>The actions provided by the <code>ModelViewSet</code> class are <code>.list()</code>, <code>.retrieve()</code>, <code>.create()</code>, <code>.update()</code>, and <code>.destroy()</code>.</p>
<h4 id="example_1">Example</h4>
<h4 id="example_1"><a class="toclink" href="#example_1">Example</a></h4>
<p>Because <code>ModelViewSet</code> extends <code>GenericAPIView</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
<pre><code>class AccountViewSet(viewsets.ModelViewSet):
"""
@ -577,9 +577,9 @@ class UserViewSet(viewsets.ModelViewSet):
</code></pre>
<p>Note however that upon removal of the <code>queryset</code> property from your <code>ViewSet</code>, any associated <a href="../routers/">router</a> will be unable to derive the base_name of your Model automatically, and so you will have to specify the <code>base_name</code> kwarg as part of your <a href="../routers/">router registration</a>.</p>
<p>Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.</p>
<h2 id="readonlymodelviewset">ReadOnlyModelViewSet</h2>
<h2 id="readonlymodelviewset"><a class="toclink" href="#readonlymodelviewset">ReadOnlyModelViewSet</a></h2>
<p>The <code>ReadOnlyModelViewSet</code> class also inherits from <code>GenericAPIView</code>. As with <code>ModelViewSet</code> it also includes implementations for various actions, but unlike <code>ModelViewSet</code> only provides the 'read-only' actions, <code>.list()</code> and <code>.retrieve()</code>.</p>
<h4 id="example_2">Example</h4>
<h4 id="example_2"><a class="toclink" href="#example_2">Example</a></h4>
<p>As with <code>ModelViewSet</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
<pre><code>class AccountViewSet(viewsets.ReadOnlyModelViewSet):
"""
@ -589,9 +589,9 @@ class UserViewSet(viewsets.ModelViewSet):
serializer_class = AccountSerializer
</code></pre>
<p>Again, as with <code>ModelViewSet</code>, you can use any of the standard attributes and method overrides available to <code>GenericAPIView</code>.</p>
<h1 id="custom-viewset-base-classes">Custom ViewSet base classes</h1>
<h1 id="custom-viewset-base-classes"><a class="toclink" href="#custom-viewset-base-classes">Custom ViewSet base classes</a></h1>
<p>You may need to provide custom <code>ViewSet</code> classes that do not have the full set of <code>ModelViewSet</code> actions, or that customize the behavior in some other way.</p>
<h2 id="example_3">Example</h2>
<h2 id="example_3"><a class="toclink" href="#example_3">Example</a></h2>
<p>To create a base viewset class that provides <code>create</code>, <code>list</code> and <code>retrieve</code> operations, inherit from <code>GenericViewSet</code>, and mixin the required actions:</p>
<pre><code>class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,

View File

@ -413,3 +413,7 @@ ul.sponsor {
#mkdocs_search_modal article p{
word-wrap: break-word;
}
.toclink {
color: #333;
}

View File

@ -467,7 +467,7 @@
<hr />
<p><img alt="Screenshot" src="./img/quickstart.png" /></p>
<p><strong>Above</strong>: <em>Screenshot from the browsable API</em></p>
<h2 id="requirements">Requirements</h2>
<h2 id="requirements"><a class="toclink" href="#requirements">Requirements</a></h2>
<p>REST framework requires the following:</p>
<ul>
<li>Python (2.7, 3.2, 3.3, 3.4, 3.5)</li>
@ -480,7 +480,7 @@
<li>[django-crispy-forms][django-crispy-forms] - Improved HTML display for filtering.</li>
<li><a href="https://github.com/lukaszb/django-guardian">django-guardian</a> (1.1.1+) - Object level permissions support.</li>
</ul>
<h2 id="installation">Installation</h2>
<h2 id="installation"><a class="toclink" href="#installation">Installation</a></h2>
<p>Install using <code>pip</code>, including any optional packages you want...</p>
<pre><code>pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
@ -502,7 +502,7 @@ pip install django-filter # Filtering support
]
</code></pre>
<p>Note that the URL path can be whatever you want, but you must include <code>'rest_framework.urls'</code> with the <code>'rest_framework'</code> namespace.</p>
<h2 id="example">Example</h2>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>Let's take a look at a quick example of using REST framework to build a simple model-backed API.</p>
<p>We'll create a read-write API for accessing information on the users of our project.</p>
<p>Any global settings for a REST framework API are kept in a single configuration dictionary named <code>REST_FRAMEWORK</code>. Start off by adding the following to your <code>settings.py</code> module:</p>
@ -544,9 +544,9 @@ urlpatterns = [
]
</code></pre>
<p>You can now open the API in your browser at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.</p>
<h2 id="quickstart">Quickstart</h2>
<h2 id="quickstart"><a class="toclink" href="#quickstart">Quickstart</a></h2>
<p>Can't wait to get started? The <a href="tutorial/quickstart/">quickstart guide</a> is the fastest way to get up and running, and building APIs with REST framework.</p>
<h2 id="tutorial">Tutorial</h2>
<h2 id="tutorial"><a class="toclink" href="#tutorial">Tutorial</a></h2>
<p>The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.</p>
<ul>
<li><a href="tutorial/1-serialization/">1 - Serialization</a></li>
@ -557,7 +557,7 @@ urlpatterns = [
<li><a href="tutorial/6-viewsets-and-routers/">6 - Viewsets &amp; routers</a></li>
</ul>
<p>There is a live example API of the finished tutorial API for testing purposes, <a href="http://restframework.herokuapp.com/">available here</a>.</p>
<h2 id="api-guide">API Guide</h2>
<h2 id="api-guide"><a class="toclink" href="#api-guide">API Guide</a></h2>
<p>The API guide is your complete reference manual to all the functionality provided by REST framework.</p>
<ul>
<li><a href="api-guide/requests/">Requests</a></li>
@ -587,7 +587,7 @@ urlpatterns = [
<li><a href="api-guide/testing/">Testing</a></li>
<li><a href="api-guide/settings/">Settings</a></li>
</ul>
<h2 id="topics">Topics</h2>
<h2 id="topics"><a class="toclink" href="#topics">Topics</a></h2>
<p>General guides to using REST framework.</p>
<ul>
<li><a href="topics/documenting-your-api/">Documenting your API</a></li>
@ -607,20 +607,20 @@ urlpatterns = [
<li><a href="topics/kickstarter-announcement/">Kickstarter Announcement</a></li>
<li><a href="topics/release-notes/">Release Notes</a></li>
</ul>
<h2 id="development">Development</h2>
<h2 id="development"><a class="toclink" href="#development">Development</a></h2>
<p>See the <a href="topics/contributing/">Contribution guidelines</a> for information on how to clone
the repository, run the test suite and contribute changes back to REST
Framework.</p>
<h2 id="support">Support</h2>
<h2 id="support"><a class="toclink" href="#support">Support</a></h2>
<p>For support please see the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>, try the <code>#restframework</code> channel on <code>irc.freenode.net</code>, search <a href="https://botbot.me/freenode/restframework/">the IRC archives</a>, or raise a question on <a href="http://stackoverflow.com/">Stack Overflow</a>, making sure to include the <a href="http://stackoverflow.com/questions/tagged/django-rest-framework">'django-rest-framework'</a> tag.</p>
<p><a href="http://dabapps.com/services/build/api-development/">Paid support is available</a> from <a href="http://dabapps.com">DabApps</a>, and can include work on REST framework core, or support with building your REST framework API. Please <a href="http://dabapps.com/contact/">contact DabApps</a> if you'd like to discuss commercial support options.</p>
<p>For updates on REST framework development, you may also want to follow <a href="https://twitter.com/_tomchristie">the author</a> on Twitter.</p>
<p><a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></p>
<h2 id="security">Security</h2>
<h2 id="security"><a class="toclink" href="#security">Security</a></h2>
<p>If you believe youve found something in Django REST framework which has security implications, please <strong>do not raise the issue in a public forum</strong>.</p>
<p>Send a description of the issue via email to <a href="mailto:rest-framework-security@googlegroups.com">rest-framework-security@googlegroups.com</a>. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.</p>
<h2 id="license">License</h2>
<h2 id="license"><a class="toclink" href="#license">License</a></h2>
<p>Copyright (c) 2011-2015, Tom Christie
All rights reserved.</p>
<p>Redistribution and use in source and binary forms, with or without

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@
<url>
<loc>http://www.django-rest-framework.org//</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
@ -13,43 +13,43 @@
<url>
<loc>http://www.django-rest-framework.org//tutorial/quickstart/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/1-serialization/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/2-requests-and-responses/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/3-class-based-views/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
@ -59,157 +59,157 @@
<url>
<loc>http://www.django-rest-framework.org//api-guide/requests/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/responses/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/views/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/generic-views/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/viewsets/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/routers/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/parsers/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/renderers/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/serializers/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/fields/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/relations/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/validators/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/authentication/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/permissions/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/throttling/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/filtering/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/pagination/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/versioning/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/content-negotiation/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/metadata/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/format-suffixes/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/reverse/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/exceptions/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/status-codes/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/testing/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//api-guide/settings/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
@ -219,97 +219,97 @@
<url>
<loc>http://www.django-rest-framework.org//topics/documenting-your-api/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/internationalization/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/ajax-csrf-cors/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/html-and-forms/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/browser-enhancements/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/browsable-api/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/third-party-resources/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/contributing/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/project-management/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/3.0-announcement/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/3.1-announcement/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/3.2-announcement/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/3.3-announcement/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/kickstarter-announcement/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<loc>http://www.django-rest-framework.org//topics/release-notes/</loc>
<lastmod>2015-10-28</lastmod>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
</url>

View File

@ -397,14 +397,14 @@
<h1 id="django-rest-framework-30">Django REST framework 3.0</h1>
<h1 id="django-rest-framework-30"><a class="toclink" href="#django-rest-framework-30">Django REST framework 3.0</a></h1>
<p>The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.</p>
<p><strong>This release is incremental in nature. There <em>are</em> some breaking API changes, and upgrading <em>will</em> require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.</strong></p>
<p>The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.</p>
<p>3.0 is the first of three releases that have been funded by our recent <a href="http://kickstarter.com/projects/tomchristie/django-rest-framework-3">Kickstarter campaign</a>.</p>
<p>As ever, a huge thank you to our many <a href="http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors">wonderful sponsors</a>. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.</p>
<hr />
<h2 id="new-features">New features</h2>
<h2 id="new-features"><a class="toclink" href="#new-features">New features</a></h2>
<p>Notable features of this new release include:</p>
<ul>
<li>Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.</li>
@ -419,14 +419,14 @@
</ul>
<p>Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two <a href="https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3">Kickstarter stretch goals</a> - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.</p>
<hr />
<h4 id="rest-framework-under-the-hood">REST framework: Under the hood.</h4>
<h4 id="rest-framework-under-the-hood"><a class="toclink" href="#rest-framework-under-the-hood">REST framework: Under the hood.</a></h4>
<p>This talk from the <a href="http://www.djangounderthehood.com/">Django: Under the Hood</a> event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.</p>
<iframe style="display: block; margin: 0 auto 0 auto" width="560" height="315" src="//www.youtube.com/embed/3cSsbe-tA0E" frameborder="0" allowfullscreen></iframe>
<hr />
<p><em>Below is an in-depth guide to the API changes and migration notes for 3.0.</em></p>
<h2 id="request-objects">Request objects</h2>
<h4 id="the-data-and-query_params-properties">The <code>.data</code> and <code>.query_params</code> properties.</h4>
<h2 id="request-objects"><a class="toclink" href="#request-objects">Request objects</a></h2>
<h4 id="the-data-and-query_params-properties"><a class="toclink" href="#the-data-and-query_params-properties">The <code>.data</code> and <code>.query_params</code> properties.</a></h4>
<p>The usage of <code>request.DATA</code> and <code>request.FILES</code> is now pending deprecation in favor of a single <code>request.data</code> attribute that contains <em>all</em> the parsed data.</p>
<p>Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.</p>
<p>You may now pass all the request data to a serializer class in a single argument:</p>
@ -439,8 +439,8 @@ ExampleSerializer(data=request.DATA, files=request.FILES)
</code></pre>
<p>The usage of <code>request.QUERY_PARAMS</code> is now pending deprecation in favor of the lowercased <code>request.query_params</code>.</p>
<hr />
<h2 id="serializers">Serializers</h2>
<h4 id="single-step-object-creation">Single-step object creation.</h4>
<h2 id="serializers"><a class="toclink" href="#serializers">Serializers</a></h2>
<h4 id="single-step-object-creation"><a class="toclink" href="#single-step-object-creation">Single-step object creation.</a></h4>
<p>Previously the serializers used a two-step object creation, as follows:</p>
<ol>
<li>Validating the data would create an object instance. This instance would be available as <code>serializer.object</code>.</li>
@ -458,7 +458,7 @@ ExampleSerializer(data=request.DATA, files=request.FILES)
<li>Calling <code>serializer.save()</code> then saves and returns the new object instance.</li>
</ol>
<p>The resulting API changes are further detailed below.</p>
<h4 id="the-create-and-update-methods">The <code>.create()</code> and <code>.update()</code> methods.</h4>
<h4 id="the-create-and-update-methods"><a class="toclink" href="#the-create-and-update-methods">The <code>.create()</code> and <code>.update()</code> methods.</a></h4>
<p>The <code>.restore_object()</code> method is now removed, and we instead have two separate methods, <code>.create()</code> and <code>.update()</code>. These methods work slightly different to the previous <code>.restore_object()</code>.</p>
<p>When using the <code>.create()</code> and <code>.update()</code> methods you should both create <em>and save</em> the object instance. This is in contrast to the previous <code>.restore_object()</code> behavior that would instantiate the object but not save it.</p>
<p>These methods also replace the optional <code>.save_object()</code> method, which no longer exists.</p>
@ -490,7 +490,7 @@ def create(self, validated_data):
return Snippet.objects.create(**validated_data)
</code></pre>
<p>Note that these methods should return the newly created object instance.</p>
<h4 id="use-validated_data-instead-of-object">Use <code>.validated_data</code> instead of <code>.object</code>.</h4>
<h4 id="use-validated_data-instead-of-object"><a class="toclink" href="#use-validated_data-instead-of-object">Use <code>.validated_data</code> instead of <code>.object</code>.</a></h4>
<p>You must now use the <code>.validated_data</code> attribute if you need to inspect the data before saving, rather than using the <code>.object</code> attribute, which no longer exists.</p>
<p>For example the following code <em>is no longer valid</em>:</p>
<pre><code>if serializer.is_valid():
@ -506,17 +506,17 @@ def create(self, validated_data):
logging.info('Creating ticket "%s"' % name)
serializer.save(user=request.user) # Include the user when saving.
</code></pre>
<h4 id="using-is_validraise_exceptiontrue">Using <code>.is_valid(raise_exception=True)</code></h4>
<h4 id="using-is_validraise_exceptiontrue"><a class="toclink" href="#using-is_validraise_exceptiontrue">Using <code>.is_valid(raise_exception=True)</code></a></h4>
<p>The <code>.is_valid()</code> method now takes an optional boolean flag, <code>raise_exception</code>.</p>
<p>Calling <code>.is_valid(raise_exception=True)</code> will cause a <code>ValidationError</code> to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.</p>
<p>The handling and formatting of error responses may be altered globally by using the <code>EXCEPTION_HANDLER</code> settings key.</p>
<p>This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.</p>
<h4 id="using-serializersvalidationerror">Using <code>serializers.ValidationError</code>.</h4>
<h4 id="using-serializersvalidationerror"><a class="toclink" href="#using-serializersvalidationerror">Using <code>serializers.ValidationError</code>.</a></h4>
<p>Previously <code>serializers.ValidationError</code> error was simply a synonym for <code>django.core.exceptions.ValidationError</code>. This has now been altered so that it inherits from the standard <code>APIException</code> base class.</p>
<p>The reason behind this is that Django's <code>ValidationError</code> class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.</p>
<p>For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the <code>serializers.ValidationError</code> exception class, and not Django's built-in exception.</p>
<p>We strongly recommend that you use the namespaced import style of <code>import serializers</code> and not <code>from serializers import ValidationError</code> in order to avoid any potential confusion.</p>
<h4 id="change-to-validate_field_name">Change to <code>validate_&lt;field_name&gt;</code>.</h4>
<h4 id="change-to-validate_field_name"><a class="toclink" href="#change-to-validate_field_name">Change to <code>validate_&lt;field_name&gt;</code>.</a></h4>
<p>The <code>validate_&lt;field_name&gt;</code> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:</p>
<pre><code>def validate_score(self, attrs, source):
if attrs['score'] % 10 != 0:
@ -542,7 +542,7 @@ def create(self, validated_data):
raise serializers.ValidationError({'my_field': 'A field error'})
</code></pre>
<p>This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.</p>
<h4 id="removal-of-transform_field_name">Removal of <code>transform_&lt;field_name&gt;</code>.</h4>
<h4 id="removal-of-transform_field_name"><a class="toclink" href="#removal-of-transform_field_name">Removal of <code>transform_&lt;field_name&gt;</code>.</a></h4>
<p>The under-used <code>transform_&lt;field_name&gt;</code> on serializer classes is no longer provided. Instead you should just override <code>to_representation()</code> if you need to apply any modifications to the representation style.</p>
<p>For example:</p>
<pre><code>def to_representation(self, instance):
@ -564,7 +564,7 @@ def create(self, validated_data):
ret[key] = method(value)
return ret
</code></pre>
<h4 id="differences-between-modelserializer-validation-and-modelform">Differences between ModelSerializer validation and ModelForm.</h4>
<h4 id="differences-between-modelserializer-validation-and-modelform"><a class="toclink" href="#differences-between-modelserializer-validation-and-modelform">Differences between ModelSerializer validation and ModelForm.</a></h4>
<p>This change also means that we no longer use the <code>.full_clean()</code> method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on <code>ModelSerializer</code> classes that can't also be easily replicated on regular <code>Serializer</code> classes.</p>
<p>For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.</p>
<p>The one difference that you do need to note is that the <code>.clean()</code> method will not be called as part of serializer validation, as it would be if using a <code>ModelForm</code>. Use the serializer <code>.validate()</code> method to perform a final validation step on incoming data where required.</p>
@ -575,7 +575,7 @@ def create(self, validated_data):
return attrs
</code></pre>
<p>Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.</p>
<h4 id="writable-nested-serialization">Writable nested serialization.</h4>
<h4 id="writable-nested-serialization"><a class="toclink" href="#writable-nested-serialization">Writable nested serialization.</a></h4>
<p>REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:</p>
<ul>
<li>There can be complex dependencies involved in order of saving multiple related model instances.</li>
@ -620,7 +620,7 @@ AssertionError: The `.create()` method does not support nested writable fields b
return user
</code></pre>
<p>The single-step object creation makes this far simpler and more obvious than the previous <code>.restore_object()</code> behavior.</p>
<h4 id="printable-serializer-representations">Printable serializer representations.</h4>
<h4 id="printable-serializer-representations"><a class="toclink" href="#printable-serializer-representations">Printable serializer representations.</a></h4>
<p>Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.</p>
<p>For instance, given the following example model:</p>
<pre><code>class LocationRating(models.Model):
@ -642,7 +642,7 @@ LocationRatingSerializer():
rating = IntegerField()
created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
</code></pre>
<h4 id="the-extra_kwargs-option">The <code>extra_kwargs</code> option.</h4>
<h4 id="the-extra_kwargs-option"><a class="toclink" href="#the-extra_kwargs-option">The <code>extra_kwargs</code> option.</a></h4>
<p>The <code>write_only_fields</code> option on <code>ModelSerializer</code> has been moved to <code>PendingDeprecation</code> and replaced with a more generic <code>extra_kwargs</code>.</p>
<pre><code>class MySerializer(serializer.ModelSerializer):
class Meta:
@ -661,7 +661,7 @@ LocationRatingSerializer():
fields = ('id', 'email', 'notes', 'is_admin')
</code></pre>
<p>The <code>read_only_fields</code> option remains as a convenient shortcut for the more common case.</p>
<h4 id="changes-to-hyperlinkedmodelserializer">Changes to <code>HyperlinkedModelSerializer</code>.</h4>
<h4 id="changes-to-hyperlinkedmodelserializer"><a class="toclink" href="#changes-to-hyperlinkedmodelserializer">Changes to <code>HyperlinkedModelSerializer</code>.</a></h4>
<p>The <code>view_name</code> and <code>lookup_field</code> options have been moved to <code>PendingDeprecation</code>. They are no longer required, as you can use the <code>extra_kwargs</code> argument instead:</p>
<pre><code>class MySerializer(serializer.HyperlinkedModelSerializer):
class Meta:
@ -682,7 +682,7 @@ LocationRatingSerializer():
model = MyModel
fields = ('url', 'email', 'notes', 'is_admin')
</code></pre>
<h4 id="fields-for-model-methods-and-properties">Fields for model methods and properties.</h4>
<h4 id="fields-for-model-methods-and-properties"><a class="toclink" href="#fields-for-model-methods-and-properties">Fields for model methods and properties.</a></h4>
<p>With <code>ModelSerializer</code> you can now specify field names in the <code>fields</code> option that refer to model methods or properties. For example, suppose you have the following model:</p>
<pre><code>class Invitation(models.Model):
created = models.DateTimeField()
@ -706,7 +706,7 @@ InvitationSerializer():
message = CharField(max_length=1000)
expiry_date = ReadOnlyField()
</code></pre>
<h4 id="the-listserializer-class">The <code>ListSerializer</code> class.</h4>
<h4 id="the-listserializer-class"><a class="toclink" href="#the-listserializer-class">The <code>ListSerializer</code> class.</a></h4>
<p>The <code>ListSerializer</code> class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.</p>
<pre><code>class MultipleUserSerializer(ListSerializer):
child = UserSerializer()
@ -714,7 +714,7 @@ InvitationSerializer():
<p>You can also still use the <code>many=True</code> argument to serializer classes. It's worth noting that <code>many=True</code> argument transparently creates a <code>ListSerializer</code> instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.</p>
<p>You will typically want to <em>continue to use the existing <code>many=True</code> flag</em> rather than declaring <code>ListSerializer</code> classes explicitly, but declaring the classes explicitly can be useful if you need to write custom <code>create</code> or <code>update</code> methods for bulk updates, or provide for other custom behavior.</p>
<p>See also the new <code>ListField</code> class, which validates input in the same way, but does not include the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p>
<h4 id="the-baseserializer-class">The <code>BaseSerializer</code> class.</h4>
<h4 id="the-baseserializer-class"><a class="toclink" href="#the-baseserializer-class">The <code>BaseSerializer</code> class.</a></h4>
<p>REST framework now includes a simple <code>BaseSerializer</code> class that can be used to easily support alternative serialization and deserialization styles.</p>
<p>This class implements the same basic API as the <code>Serializer</code> class:</p>
<ul>
@ -732,7 +732,7 @@ InvitationSerializer():
</ul>
<p>Because this class provides the same interface as the <code>Serializer</code> class, you can use it with the existing generic class based views exactly as you would for a regular <code>Serializer</code> or <code>ModelSerializer</code>.</p>
<p>The only difference you'll notice when doing so is the <code>BaseSerializer</code> classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.</p>
<h5 id="read-only-baseserializer-classes">Read-only <code>BaseSerializer</code> classes.</h5>
<h5 id="read-only-baseserializer-classes"><a class="toclink" href="#read-only-baseserializer-classes">Read-only <code>BaseSerializer</code> classes.</a></h5>
<p>To implement a read-only serializer using the <code>BaseSerializer</code> class, we just need to override the <code>.to_representation()</code> method. Let's take a look at an example using a simple Django model:</p>
<pre><code>class HighScore(models.Model):
created = models.DateTimeField(auto_now_add=True)
@ -761,7 +761,7 @@ def all_high_scores(request):
serializer = HighScoreSerializer(queryset, many=True)
return Response(serializer.data)
</code></pre>
<h5 id="read-write-baseserializer-classes">Read-write <code>BaseSerializer</code> classes.</h5>
<h5 id="read-write-baseserializer-classes"><a class="toclink" href="#read-write-baseserializer-classes">Read-write <code>BaseSerializer</code> classes.</a></h5>
<p>To create a read-write serializer we first need to implement a <code>.to_internal_value()</code> method. This method returns the validated values that will be used to construct the object instance, and may raise a <code>ValidationError</code> if the supplied data is in an incorrect format.</p>
<p>Once you've implemented <code>.to_internal_value()</code>, the basic validation API will be available on the serializer, and you will be able to use <code>.is_valid()</code>, <code>.validated_data</code> and <code>.errors</code>.</p>
<p>If you want to also support <code>.save()</code> you'll need to also implement either or both of the <code>.create()</code> and <code>.update()</code> methods.</p>
@ -801,7 +801,7 @@ def all_high_scores(request):
def create(self, validated_data):
return HighScore.objects.create(**validated_data)
</code></pre>
<h4 id="creating-new-generic-serializers-with-baseserializer">Creating new generic serializers with <code>BaseSerializer</code>.</h4>
<h4 id="creating-new-generic-serializers-with-baseserializer"><a class="toclink" href="#creating-new-generic-serializers-with-baseserializer">Creating new generic serializers with <code>BaseSerializer</code>.</a></h4>
<p>The <code>BaseSerializer</code> class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.</p>
<p>The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.</p>
<pre><code>class ObjectSerializer(serializers.BaseSerializer):
@ -837,8 +837,8 @@ def all_high_scores(request):
output[attribute_name] = str(attribute)
</code></pre>
<hr />
<h2 id="serializer-fields">Serializer fields</h2>
<h4 id="the-field-and-readonly-field-classes">The <code>Field</code> and <code>ReadOnly</code> field classes.</h4>
<h2 id="serializer-fields"><a class="toclink" href="#serializer-fields">Serializer fields</a></h2>
<h4 id="the-field-and-readonly-field-classes"><a class="toclink" href="#the-field-and-readonly-field-classes">The <code>Field</code> and <code>ReadOnly</code> field classes.</a></h4>
<p>There are some minor tweaks to the field base classes.</p>
<p>Previously we had these two base classes:</p>
<ul>
@ -850,7 +850,7 @@ def all_high_scores(request):
<li><code>Field</code> is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.</li>
<li><code>ReadOnlyField</code> is a concrete implementation for read-only fields that simply returns the attribute value without modification.</li>
</ul>
<h4 id="the-required-allow_null-allow_blank-and-default-arguments">The <code>required</code>, <code>allow_null</code>, <code>allow_blank</code> and <code>default</code> arguments.</h4>
<h4 id="the-required-allow_null-allow_blank-and-default-arguments"><a class="toclink" href="#the-required-allow_null-allow_blank-and-default-arguments">The <code>required</code>, <code>allow_null</code>, <code>allow_blank</code> and <code>default</code> arguments.</a></h4>
<p>REST framework now has more explicit and clear control over validating empty values for fields.</p>
<p>Previously the meaning of the <code>required=False</code> keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be <code>None</code> or the empty string.</p>
<p>We now have a better separation, with separate <code>required</code>, <code>allow_null</code> and <code>allow_blank</code> arguments.</p>
@ -863,9 +863,9 @@ def all_high_scores(request):
</ul>
<p>Typically you'll want to use <code>required=False</code> if the corresponding model field has a default value, and additionally set either <code>allow_null=True</code> or <code>allow_blank=True</code> if required.</p>
<p>The <code>default</code> argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the <code>required</code> argument when a default is specified, and doing so will result in an error.</p>
<h4 id="coercing-output-types">Coercing output types.</h4>
<h4 id="coercing-output-types"><a class="toclink" href="#coercing-output-types">Coercing output types.</a></h4>
<p>The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an <code>IntegerField</code> would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.</p>
<h4 id="removal-of-validate">Removal of <code>.validate()</code>.</h4>
<h4 id="removal-of-validate"><a class="toclink" href="#removal-of-validate">Removal of <code>.validate()</code>.</a></h4>
<p>The <code>.validate()</code> method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override <code>to_internal_value()</code>.</p>
<pre><code>class UppercaseCharField(serializers.CharField):
def to_internal_value(self, data):
@ -875,7 +875,7 @@ def all_high_scores(request):
return value
</code></pre>
<p>Previously validation errors could be raised in either <code>.to_native()</code> or <code>.validate()</code>, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.</p>
<h4 id="the-listfield-class">The <code>ListField</code> class.</h4>
<h4 id="the-listfield-class"><a class="toclink" href="#the-listfield-class">The <code>ListField</code> class.</a></h4>
<p>The <code>ListField</code> class has now been added. This field validates list input. It takes a <code>child</code> keyword argument which is used to specify the field used to validate each item in the list. For example:</p>
<pre><code>scores = ListField(child=IntegerField(min_value=0, max_value=100))
</code></pre>
@ -887,13 +887,13 @@ def all_high_scores(request):
<pre><code>scores = ScoresField()
</code></pre>
<p>See also the new <code>ListSerializer</code> class, which validates input in the same way, but also includes the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p>
<h4 id="the-choicefield-class-may-now-accept-a-flat-list">The <code>ChoiceField</code> class may now accept a flat list.</h4>
<h4 id="the-choicefield-class-may-now-accept-a-flat-list"><a class="toclink" href="#the-choicefield-class-may-now-accept-a-flat-list">The <code>ChoiceField</code> class may now accept a flat list.</a></h4>
<p>The <code>ChoiceField</code> class may now accept a list of choices in addition to the existing style of using a list of pairs of <code>(name, display_value)</code>. The following is now valid:</p>
<pre><code>color = ChoiceField(choices=['red', 'green', 'blue'])
</code></pre>
<h4 id="the-multiplechoicefield-class">The <code>MultipleChoiceField</code> class.</h4>
<h4 id="the-multiplechoicefield-class"><a class="toclink" href="#the-multiplechoicefield-class">The <code>MultipleChoiceField</code> class.</a></h4>
<p>The <code>MultipleChoiceField</code> class has been added. This field acts like <code>ChoiceField</code>, but returns a set, which may include none, one or many of the valid choices.</p>
<h4 id="changes-to-the-custom-field-api">Changes to the custom field API.</h4>
<h4 id="changes-to-the-custom-field-api"><a class="toclink" href="#changes-to-the-custom-field-api">Changes to the custom field API.</a></h4>
<p>The <code>from_native(self, value)</code> and <code>to_native(self, data)</code> method names have been replaced with the more obviously named <code>to_internal_value(self, data)</code> and <code>to_representation(self, value)</code>.</p>
<p>The <code>field_from_native()</code> and <code>field_to_native()</code> methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...</p>
<pre><code>def field_to_native(self, obj, field_name):
@ -914,7 +914,7 @@ def all_high_scores(request):
def to_representation(self, value):
return value.__class__.__name__
</code></pre>
<h4 id="explicit-queryset-required-on-relational-fields">Explicit <code>queryset</code> required on relational fields.</h4>
<h4 id="explicit-queryset-required-on-relational-fields"><a class="toclink" href="#explicit-queryset-required-on-relational-fields">Explicit <code>queryset</code> required on relational fields.</a></h4>
<p>Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a <code>ModelSerializer</code>.</p>
<p>This code <em>would be valid</em> in <code>2.4.3</code>:</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
@ -943,7 +943,7 @@ This removes some magic and makes it easier and more obvious to move between imp
model = Account
</code></pre>
<p>The <code>queryset</code> argument is only ever required for writable fields, and is not required or valid for fields with <code>read_only=True</code>.</p>
<h4 id="optional-argument-to-serializermethodfield">Optional argument to <code>SerializerMethodField</code>.</h4>
<h4 id="optional-argument-to-serializermethodfield"><a class="toclink" href="#optional-argument-to-serializermethodfield">Optional argument to <code>SerializerMethodField</code>.</a></h4>
<p>The argument to <code>SerializerMethodField</code> is now optional, and defaults to <code>get_&lt;field_name&gt;</code>. For example the following is valid:</p>
<pre><code>class AccountSerializer(serializers.Serializer):
# `method_name='get_billing_details'` by default.
@ -955,12 +955,12 @@ This removes some magic and makes it easier and more obvious to move between imp
<p>In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code <em>will raise an error</em>:</p>
<pre><code>billing_details = serializers.SerializerMethodField('get_billing_details')
</code></pre>
<h4 id="enforcing-consistent-source-usage">Enforcing consistent <code>source</code> usage.</h4>
<h4 id="enforcing-consistent-source-usage"><a class="toclink" href="#enforcing-consistent-source-usage">Enforcing consistent <code>source</code> usage.</a></h4>
<p>I've see several codebases that unnecessarily include the <code>source</code> argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that <code>source</code> is usually not required.</p>
<p>The following usage will <em>now raise an error</em>:</p>
<pre><code>email = serializers.EmailField(source='email')
</code></pre>
<h4 id="the-uniquevalidator-and-uniquetogethervalidator-classes">The <code>UniqueValidator</code> and <code>UniqueTogetherValidator</code> classes.</h4>
<h4 id="the-uniquevalidator-and-uniquetogethervalidator-classes"><a class="toclink" href="#the-uniquevalidator-and-uniquetogethervalidator-classes">The <code>UniqueValidator</code> and <code>UniqueTogetherValidator</code> classes.</a></h4>
<p>REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit <code>Serializer</code> class instead of using <code>ModelSerializer</code>.</p>
<p>The <code>UniqueValidator</code> should be applied to a serializer field, and takes a single <code>queryset</code> argument.</p>
<pre><code>from rest_framework import serializers
@ -986,14 +986,14 @@ class OrganizationSerializer(serializers.Serializer):
fields=('category', 'position')
)]
</code></pre>
<h4 id="the-uniquefordatevalidator-classes">The <code>UniqueForDateValidator</code> classes.</h4>
<h4 id="the-uniquefordatevalidator-classes"><a class="toclink" href="#the-uniquefordatevalidator-classes">The <code>UniqueForDateValidator</code> classes.</a></h4>
<p>REST framework also now includes explicit validator classes for validating the <code>unique_for_date</code>, <code>unique_for_month</code>, and <code>unique_for_year</code> model field constraints. These are used internally instead of calling into <code>Model.full_clean()</code>.</p>
<p>These classes are documented in the <a href="../../api-guide/validators/">Validators</a> section of the documentation.</p>
<hr />
<h2 id="generic-views">Generic views</h2>
<h4 id="simplification-of-view-logic">Simplification of view logic.</h4>
<h2 id="generic-views"><a class="toclink" href="#generic-views">Generic views</a></h2>
<h4 id="simplification-of-view-logic"><a class="toclink" href="#simplification-of-view-logic">Simplification of view logic.</a></h4>
<p>The view logic for the default method handlers has been significantly simplified, due to the new serializers API.</p>
<h4 id="changes-to-prepost-save-hooks">Changes to pre/post save hooks.</h4>
<h4 id="changes-to-prepost-save-hooks"><a class="toclink" href="#changes-to-prepost-save-hooks">Changes to pre/post save hooks.</a></h4>
<p>The <code>pre_save</code> and <code>post_save</code> hooks no longer exist, but are replaced with <code>perform_create(self, serializer)</code> and <code>perform_update(self, serializer)</code>.</p>
<p>These methods should save the object instance by calling <code>serializer.save()</code>, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.</p>
<p>For example:</p>
@ -1010,22 +1010,22 @@ class OrganizationSerializer(serializers.Serializer):
# Delete the object instance.
instance.delete()
</code></pre>
<h4 id="removal-of-view-attributes">Removal of view attributes.</h4>
<h4 id="removal-of-view-attributes"><a class="toclink" href="#removal-of-view-attributes">Removal of view attributes.</a></h4>
<p>The <code>.object</code> and <code>.object_list</code> attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.</p>
<p>I would personally recommend that developers treat view instances as immutable objects in their application code.</p>
<h4 id="put-as-create">PUT as create.</h4>
<h4 id="put-as-create"><a class="toclink" href="#put-as-create">PUT as create.</a></h4>
<p>Allowing <code>PUT</code> as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning <code>404</code> responses.</p>
<p>Both styles "<code>PUT</code> as 404" and "<code>PUT</code> as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.</p>
<p>If you need to restore the previous behavior you may want to include <a href="https://gist.github.com/tomchristie/a2ace4577eff2c603b1b">this <code>AllowPUTAsCreateMixin</code> class</a> as a mixin to your views.</p>
<h4 id="customizing-error-responses">Customizing error responses.</h4>
<h4 id="customizing-error-responses"><a class="toclink" href="#customizing-error-responses">Customizing error responses.</a></h4>
<p>The generic views now raise <code>ValidationFailed</code> exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a <code>400 Bad Request</code> response directly.</p>
<p>This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.</p>
<hr />
<h2 id="the-metadata-api">The metadata API</h2>
<h2 id="the-metadata-api"><a class="toclink" href="#the-metadata-api">The metadata API</a></h2>
<p>Behavior for dealing with <code>OPTIONS</code> requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.</p>
<p>This makes it far easier to use a different style for <code>OPTIONS</code> responses throughout your API, and makes it possible to create third-party metadata policies.</p>
<hr />
<h2 id="serializers-as-html-forms">Serializers as HTML forms</h2>
<h2 id="serializers-as-html-forms"><a class="toclink" href="#serializers-as-html-forms">Serializers as HTML forms</a></h2>
<p>REST framework 3.0 includes templated HTML form rendering for serializers.</p>
<p>This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.</p>
<p>Significant changes that you do need to be aware of include:</p>
@ -1034,7 +1034,7 @@ class OrganizationSerializer(serializers.Serializer):
<li>Nested lists of HTML forms are not yet supported, but are planned for 3.1.</li>
<li>Because we now use templated HTML form generation, <strong>the <code>widget</code> option is no longer available for serializer fields</strong>. You can instead control the template that is used for a given field, by using the <code>style</code> dictionary.</li>
</ul>
<h4 id="the-style-keyword-argument-for-serializer-fields">The <code>style</code> keyword argument for serializer fields.</h4>
<h4 id="the-style-keyword-argument-for-serializer-fields"><a class="toclink" href="#the-style-keyword-argument-for-serializer-fields">The <code>style</code> keyword argument for serializer fields.</a></h4>
<p>The <code>style</code> keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the <code>HTMLFormRenderer</code> uses the <code>base_template</code> key to determine which template to render the field with.</p>
<p>For example, to use a <code>textarea</code> control instead of the default <code>input</code> control, you would use the following…</p>
<pre><code>additional_notes = serializers.CharField(
@ -1049,15 +1049,15 @@ class OrganizationSerializer(serializers.Serializer):
</code></pre>
<p>This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.</p>
<hr />
<h2 id="api-style">API style</h2>
<h2 id="api-style"><a class="toclink" href="#api-style">API style</a></h2>
<p>There are some improvements in the default style we use in our API responses.</p>
<h4 id="unicode-json-by-default">Unicode JSON by default.</h4>
<h4 id="unicode-json-by-default"><a class="toclink" href="#unicode-json-by-default">Unicode JSON by default.</a></h4>
<p>Unicode JSON is now the default. The <code>UnicodeJSONRenderer</code> class no longer exists, and the <code>UNICODE_JSON</code> setting has been added. To revert this behavior use the new setting:</p>
<pre><code>REST_FRAMEWORK = {
'UNICODE_JSON': False
}
</code></pre>
<h4 id="compact-json-by-default">Compact JSON by default.</h4>
<h4 id="compact-json-by-default"><a class="toclink" href="#compact-json-by-default">Compact JSON by default.</a></h4>
<p>We now output compact JSON in responses by default. For example, we return:</p>
<pre><code>{"email":"amy@example.com","is_admin":true}
</code></pre>
@ -1069,7 +1069,7 @@ class OrganizationSerializer(serializers.Serializer):
'COMPACT_JSON': False
}
</code></pre>
<h4 id="file-fields-as-urls">File fields as URLs</h4>
<h4 id="file-fields-as-urls"><a class="toclink" href="#file-fields-as-urls">File fields as URLs</a></h4>
<p>The <code>FileField</code> and <code>ImageField</code> classes are now represented as URLs by default. You should ensure you set Django's <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL">standard <code>MEDIA_URL</code> setting</a> appropriately, and ensure your application <a href="https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development">serves the uploaded files</a>.</p>
<p>You can revert this behavior, and display filenames in the representation by using the <code>UPLOADED_FILES_USE_URL</code> settings key:</p>
<pre><code>REST_FRAMEWORK = {
@ -1085,9 +1085,9 @@ serializer = ExampleSerializer(instance, context=context)
return Response(serializer.data)
</code></pre>
<p>If the request is omitted from the context, the returned URLs will be of the form <code>/url_path/filename.txt</code>.</p>
<h4 id="throttle-headers-using-retry-after">Throttle headers using <code>Retry-After</code>.</h4>
<h4 id="throttle-headers-using-retry-after"><a class="toclink" href="#throttle-headers-using-retry-after">Throttle headers using <code>Retry-After</code>.</a></h4>
<p>The custom <code>X-Throttle-Wait-Second</code> header has now been dropped in favor of the standard <code>Retry-After</code> header. You can revert this behavior if needed by writing a custom exception handler for your application.</p>
<h4 id="date-and-time-objects-as-iso-8859-1-strings-in-serializer-data">Date and time objects as ISO-8859-1 strings in serializer data.</h4>
<h4 id="date-and-time-objects-as-iso-8859-1-strings-in-serializer-data"><a class="toclink" href="#date-and-time-objects-as-iso-8859-1-strings-in-serializer-data">Date and time objects as ISO-8859-1 strings in serializer data.</a></h4>
<p>Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as <code>Date</code>, <code>Time</code> and <code>DateTime</code> objects, and later coerced to strings by the renderer.</p>
<p>You can modify this behavior globally by settings the existing <code>DATE_FORMAT</code>, <code>DATETIME_FORMAT</code> and <code>TIME_FORMAT</code> settings keys. Setting these values to <code>None</code> instead of their default value of <code>'iso-8859-1'</code> will result in native objects being returned in serializer data.</p>
<pre><code>REST_FRAMEWORK = {
@ -1101,7 +1101,7 @@ return Response(serializer.data)
<pre><code># Return `DateTime` instances in `serializer.data`, not strings.
created = serializers.DateTimeField(format=None)
</code></pre>
<h4 id="decimals-as-strings-in-serializer-data">Decimals as strings in serializer data.</h4>
<h4 id="decimals-as-strings-in-serializer-data"><a class="toclink" href="#decimals-as-strings-in-serializer-data">Decimals as strings in serializer data.</a></h4>
<p>Decimals are now coerced to strings by default in the serializer output. Previously they were returned as <code>Decimal</code> objects, and later coerced to strings by the renderer.</p>
<p>You can modify this behavior globally by using the <code>COERCE_DECIMAL_TO_STRING</code> settings key.</p>
<pre><code>REST_FRAMEWORK = {
@ -1118,7 +1118,7 @@ amount = serializers.DecimalField(
</code></pre>
<p>The default JSON renderer will return float objects for un-coerced <code>Decimal</code> instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.</p>
<hr />
<h2 id="miscellaneous-notes">Miscellaneous notes</h2>
<h2 id="miscellaneous-notes"><a class="toclink" href="#miscellaneous-notes">Miscellaneous notes</a></h2>
<ul>
<li>The serializer <code>ChoiceField</code> does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.</li>
<li>Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.</li>
@ -1126,7 +1126,7 @@ amount = serializers.DecimalField(
<li><code>APIException</code> subclasses could previously take any arbitrary type in the <code>detail</code> argument. These exceptions now use translatable text strings, and as a result call <code>force_text</code> on the <code>detail</code> argument, which <em>must be a string</em>. If you need complex arguments to an <code>APIException</code> class, you should subclass it and override the <code>__init__()</code> method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.</li>
</ul>
<hr />
<h2 id="whats-coming-next">What's coming next</h2>
<h2 id="whats-coming-next"><a class="toclink" href="#whats-coming-next">What's coming next</a></h2>
<p>3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.</p>
<p>The 3.1 release is planned to address improvements in the following components:</p>
<ul>

View File

@ -389,7 +389,7 @@
<h1 id="django-rest-framework-31">Django REST framework 3.1</h1>
<h1 id="django-rest-framework-31"><a class="toclink" href="#django-rest-framework-31">Django REST framework 3.1</a></h1>
<p>The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.</p>
<p>Some highlights include:</p>
<ul>
@ -401,7 +401,7 @@
<li>Support for Django 1.8's <code>HStoreField</code> and <code>ArrayField</code>.</li>
</ul>
<hr />
<h2 id="pagination">Pagination</h2>
<h2 id="pagination"><a class="toclink" href="#pagination">Pagination</a></h2>
<p>The pagination API has been improved, making it both easier to use, and more powerful.</p>
<p>A guide to the headline features follows. For full details, see <a href="../../api-guide/pagination/">the pagination documentation</a>.</p>
<p>Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.</p>
@ -411,19 +411,19 @@
<li>The <code>paginate_by</code>, <code>page_query_param</code>, <code>paginate_by_param</code> and <code>max_paginate_by</code> generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.</li>
<li>The <code>pagination_serializer_class</code> view attribute and <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> settings key <strong>are no longer valid</strong>. The pagination API does not use serializers to determine the output format, and you'll need to instead override the <code>get_paginated_response</code> method on a pagination class in order to specify how the output format is controlled.</li>
</ul>
<h4 id="new-pagination-schemes">New pagination schemes.</h4>
<h4 id="new-pagination-schemes"><a class="toclink" href="#new-pagination-schemes">New pagination schemes.</a></h4>
<p>Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.</p>
<p>The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for <a href="http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/">this blog post</a> on the subject.</p>
<h4 id="pagination-controls-in-the-browsable-api">Pagination controls in the browsable API.</h4>
<h4 id="pagination-controls-in-the-browsable-api"><a class="toclink" href="#pagination-controls-in-the-browsable-api">Pagination controls in the browsable API.</a></h4>
<p>Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:</p>
<p><img alt="page number based pagination" src="../../img/pages-pagination.png" /></p>
<p>The cursor based pagination renders a more simple style of control:</p>
<p><img alt="cursor based pagination" src="../../img/cursor-pagination.png" /></p>
<h4 id="support-for-header-based-pagination">Support for header-based pagination.</h4>
<h4 id="support-for-header-based-pagination"><a class="toclink" href="#support-for-header-based-pagination">Support for header-based pagination.</a></h4>
<p>The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the <code>Link</code> or <code>Content-Range</code> headers.</p>
<p>For more information, see the <a href="../../api-guide/pagination/#custom-pagination-styles">custom pagination styles</a> documentation.</p>
<hr />
<h2 id="versioning">Versioning</h2>
<h2 id="versioning"><a class="toclink" href="#versioning">Versioning</a></h2>
<p>We've made it <a href="../../api-guide/versioning/">easier to build versioned APIs</a>. Built-in schemes for versioning include both URL based and Accept header based variations.</p>
<p>When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.</p>
<p>For example, when using <code>NamespaceVersioning</code>, and the following hyperlinked serializer:</p>
@ -445,7 +445,7 @@
}
</code></pre>
<hr />
<h2 id="internationalization">Internationalization</h2>
<h2 id="internationalization"><a class="toclink" href="#internationalization">Internationalization</a></h2>
<p>REST framework now includes a built-in set of translations, and <a href="../internationalization/">supports internationalized error responses</a>. This allows you to either change the default language, or to allow clients to specify the language via the <code>Accept-Language</code> header.</p>
<p>You can change the default language by using the standard Django <code>LANGUAGE_CODE</code> setting:</p>
<pre><code>LANGUAGE_CODE = "es-es"
@ -482,18 +482,18 @@ Host: example.org
<p>For more details, see the <a href="../internationalization/">internationalization documentation</a>.</p>
<p>Many thanks to <a href="https://github.com/jakul">Craig Blaszczyk</a> for helping push this through.</p>
<hr />
<h2 id="new-field-types">New field types</h2>
<h2 id="new-field-types"><a class="toclink" href="#new-field-types">New field types</a></h2>
<p>Django 1.8's new <code>ArrayField</code>, <code>HStoreField</code> and <code>UUIDField</code> are now all fully supported.</p>
<p>This work also means that we now have both <code>serializers.DictField()</code>, and <code>serializers.ListField()</code> types, allowing you to express and validate a wider set of representations.</p>
<p>If you're building a new 1.8 project, then you should probably consider using <code>UUIDField</code> as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:</p>
<pre><code>http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d
</code></pre>
<hr />
<h2 id="modelserializer-api">ModelSerializer API</h2>
<h2 id="modelserializer-api"><a class="toclink" href="#modelserializer-api">ModelSerializer API</a></h2>
<p>The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.</p>
<p>For more information, see the documentation on <a href="../../api-guide/serializers/#customizing-field-mappings">customizing field mappings</a> for ModelSerializer classes.</p>
<hr />
<h2 id="moving-packages-out-of-core">Moving packages out of core</h2>
<h2 id="moving-packages-out-of-core"><a class="toclink" href="#moving-packages-out-of-core">Moving packages out of core</a></h2>
<p>We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to <code>pip install</code> the new packages, and change any import paths.</p>
<p>We're making this change in order to help distribute the maintainance workload, and keep better focus of the core essentials of the framework.</p>
<p>The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained <a href="https://github.com/evonove/django-oauth-toolkit">Django OAuth toolkit</a> has now been promoted as our recommended option for integrating OAuth support.</p>
@ -518,12 +518,12 @@ Host: example.org
</code></pre>
<p>Thanks go to the latest member of our maintenance team, <a href="https://github.com/jpadilla/">José Padilla</a>, for handling this work and taking on ownership of these packages.</p>
<hr />
<h2 id="deprecations">Deprecations</h2>
<h2 id="deprecations"><a class="toclink" href="#deprecations">Deprecations</a></h2>
<p>The <code>request.DATA</code>, <code>request.FILES</code> and <code>request.QUERY_PARAMS</code> attributes move from pending deprecation, to deprecated. Use <code>request.data</code> and <code>request.query_params</code> instead, as discussed in the 3.0 release notes.</p>
<p>The ModelSerializer Meta options for <code>write_only_fields</code>, <code>view_name</code> and <code>lookup_field</code> are also moved from pending deprecation, to deprecated. Use <code>extra_kwargs</code> instead, as discussed in the 3.0 release notes.</p>
<p>All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.</p>
<hr />
<h2 id="whats-next">What's next?</h2>
<h2 id="whats-next"><a class="toclink" href="#whats-next">What's next?</a></h2>
<p>The next focus will be on HTML renderings of API output and will include:</p>
<ul>
<li>HTML form rendering of serializers.</li>

View File

@ -377,14 +377,14 @@
<h1 id="django-rest-framework-32">Django REST framework 3.2</h1>
<h1 id="django-rest-framework-32"><a class="toclink" href="#django-rest-framework-32">Django REST framework 3.2</a></h1>
<p>The 3.2 release is the first version to include an admin interface for the browsable API.</p>
<p><img alt="The AdminRenderer" src="../../img/admin.png" /></p>
<p>This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing <code>BrowsableAPIRenderer</code>, or used together with it, allowing you to switch between the two styles as required.</p>
<p>We've also fixed a huge number of issues, and made numerous cleanups and improvements.</p>
<p>Over the course of the 3.1.x series we've <a href="https://github.com/tomchristie/django-rest-framework/issues?utf8=%E2%9C%93&amp;q=closed%3A%3E2015-03-05">resolved nearly 600 tickets</a> on our GitHub issue tracker. This means we're currently running at a rate of <strong>closing around 100 issues or pull requests per month</strong>.</p>
<p>None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking <a href="http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors">a look through our sponsors</a> and finding out who's hiring.</p>
<h2 id="adminrenderer">AdminRenderer</h2>
<h2 id="adminrenderer"><a class="toclink" href="#adminrenderer">AdminRenderer</a></h2>
<p>To include <code>AdminRenderer</code> simply add it to your settings:</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
@ -399,10 +399,10 @@
<p>There are some limitations to the <code>AdminRenderer</code>, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.</p>
<p>Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.</p>
<p>The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.</p>
<h2 id="supported-versions">Supported versions</h2>
<h2 id="supported-versions"><a class="toclink" href="#supported-versions">Supported versions</a></h2>
<p>This release drops support for Django 1.4.</p>
<p>Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.</p>
<h2 id="deprecations">Deprecations</h2>
<h2 id="deprecations"><a class="toclink" href="#deprecations">Deprecations</a></h2>
<p>There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.</p>
<ul>
<li><code>request.DATA</code> was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of <code>request.data</code> instead.</li>
@ -419,10 +419,10 @@
<li><code>settings.PAGINATE_BY_PARAM</code> - Use <code>paginator.page_size_query_param</code> instead.</li>
<li><code>settings.MAX_PAGINATE_BY</code> - Use <code>max_page_size</code> instead.</li>
</ul>
<h2 id="modifications-to-list-behaviors">Modifications to list behaviors</h2>
<h2 id="modifications-to-list-behaviors"><a class="toclink" href="#modifications-to-list-behaviors">Modifications to list behaviors</a></h2>
<p>There are a couple of bug fixes that are worth calling out as they introduce differing behavior.</p>
<p>These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.</p>
<h3 id="manytomany-fields-and-blanktrue">ManyToMany fields and blank=True</h3>
<h3 id="manytomany-fields-and-blanktrue"><a class="toclink" href="#manytomany-fields-and-blanktrue">ManyToMany fields and blank=True</a></h3>
<p>We've now added an <code>allow_empty</code> argument, which can be used with <code>ListSerializer</code>, or with <code>many=True</code> relationships. This is <code>True</code> by default, but can be set to <code>False</code> if you want to disallow empty lists as valid input.</p>
<p>As a follow-up to this we are now able to properly mirror the behavior of Django's <code>ModelForm</code> with respect to how many-to-many fields are validated.</p>
<p>Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has <code>blank=True</code> set.</p>
@ -432,7 +432,7 @@
<li><code>models.ManyToManyField(blank=True)</code><code>serializers.PrimaryKeyRelatedField(many=True)</code></li>
</ul>
<p>The upshot is this: If you have many to many fields in your models, then make sure you've included the argument <code>blank=True</code> if you want to allow empty inputs in the equivalent <code>ModelSerializer</code> fields.</p>
<h3 id="list-fields-and-allow_null">List fields and allow_null</h3>
<h3 id="list-fields-and-allow_null"><a class="toclink" href="#list-fields-and-allow_null">List fields and allow_null</a></h3>
<p>When using <code>allow_null</code> with <code>ListField</code> or a nested <code>many=True</code> serializer the previous behavior was to allow <code>null</code> values as items in the list. The behavior is now to allow <code>null</code> values instead of the list.</p>
<p>For example, take the following field:</p>
<pre><code>NestedSerializer(many=True, allow_null=True)
@ -450,7 +450,7 @@
<p>If you want to allow <code>null</code> child items, you'll need to instead specify <code>allow_null</code> on the child class, using an explicit <code>ListField</code> instead of <code>many=True</code>. For example:</p>
<pre><code>ListField(child=NestedSerializer(allow_null=True))
</code></pre>
<h2 id="whats-next">What's next?</h2>
<h2 id="whats-next"><a class="toclink" href="#whats-next">What's next?</a></h2>
<p>The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.</p>
<p>This release is planned to include:</p>
<ul>

View File

@ -369,13 +369,13 @@
<h1 id="django-rest-framework-33">Django REST framework 3.3</h1>
<h1 id="django-rest-framework-33"><a class="toclink" href="#django-rest-framework-33">Django REST framework 3.3</a></h1>
<p>The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding <strong>thank you</strong> to all our wonderful sponsors and supporters.</p>
<p>The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned &amp; refined large parts of the project.</p>
<p>In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow <a href="https://twitter.com/_tomchristie">@_tomchristie</a> to keep up to date with these announcements, and be among the first set of sign ups.</p>
<p>We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished &amp; professional product.</p>
<hr />
<h2 id="release-notes">Release notes</h2>
<h2 id="release-notes"><a class="toclink" href="#release-notes">Release notes</a></h2>
<p>Significant new functionality in the 3.3 release includes:</p>
<ul>
<li>Filters presented as HTML controls in the browsable API.</li>
@ -387,13 +387,13 @@
<p><img alt="Filter Controls" src="../../img/filter-controls.png" /></p>
<p><em>Example of the new filter controls</em></p>
<hr />
<h2 id="supported-versions">Supported versions</h2>
<h2 id="supported-versions"><a class="toclink" href="#supported-versions">Supported versions</a></h2>
<p>This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.</p>
<p>This brings our supported versions into line with Django's <a href="https://www.djangoproject.com/download/#supported-versions">currently supported versions</a></p>
<h2 id="deprecations">Deprecations</h2>
<h2 id="deprecations"><a class="toclink" href="#deprecations">Deprecations</a></h2>
<p>The AJAX based support for the browsable API means that there are a number of internal cleanups in the <code>request</code> class. For the vast majority of developers this should largely remain transparent:</p>
<ul>
<li>To support form based <code>PUT</code> and <code>DELETE</code>, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-forms] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.</li>
<li>To support form based <code>PUT</code> and <code>DELETE</code>, or to support form content types such as JSON, you should now use the <a href="https://github.com/tomchristie/ajax-form">AJAX forms</a> javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.</li>
<li>The <code>accept</code> query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to <a href="../browser-enhancements/#url-based-accept-headers">use a custom content negotiation class</a>.</li>
<li>The custom <code>HTTP_X_HTTP_METHOD_OVERRIDE</code> header is no longer supported by default. If you require it then you'll need to <a href="../browser-enhancements/#http-header-based-method-overriding">use custom middleware</a>.</li>
</ul>

View File

@ -369,16 +369,16 @@
<h1 id="working-with-ajax-csrf-cors">Working with AJAX, CSRF &amp; CORS</h1>
<h1 id="working-with-ajax-csrf-cors"><a class="toclink" href="#working-with-ajax-csrf-cors">Working with AJAX, CSRF &amp; CORS</a></h1>
<blockquote>
<p>"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability &mdash; very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."</p>
<p>&mdash; <a href="http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html">Jeff Atwood</a></p>
</blockquote>
<h2 id="javascript-clients">Javascript clients</h2>
<h2 id="javascript-clients"><a class="toclink" href="#javascript-clients">Javascript clients</a></h2>
<p>If youre building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.</p>
<p>AJAX requests that are made within the same context as the API they are interacting with will typically use <code>SessionAuthentication</code>. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.</p>
<p>AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as <code>TokenAuthentication</code>.</p>
<h2 id="csrf-protection">CSRF protection</h2>
<h2 id="csrf-protection"><a class="toclink" href="#csrf-protection">CSRF protection</a></h2>
<p><a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)">Cross Site Request Forgery</a> protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.</p>
<p>To guard against these type of attacks, you need to do two things:</p>
<ol>
@ -387,7 +387,7 @@
</ol>
<p>If you're using <code>SessionAuthentication</code> you'll need to include valid CSRF tokens for any <code>POST</code>, <code>PUT</code>, <code>PATCH</code> or <code>DELETE</code> operations.</p>
<p>In order to make AJAX requests, you need to include CSRF token in the HTTP header, as <a href="https://docs.djangoproject.com/en/dev/ref/csrf/#ajax">described in the Django documentation</a>.</p>
<h2 id="cors">CORS</h2>
<h2 id="cors"><a class="toclink" href="#cors">CORS</a></h2>
<p><a href="http://www.w3.org/TR/cors/">Cross-Origin Resource Sharing</a> is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.</p>
<p>The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.</p>
<p><a href="https://github.com/ottoyiu/">Otto Yiu</a> maintains the <a href="https://github.com/ottoyiu/django-cors-headers/">django-cors-headers</a> package, which is known to work correctly with REST framework APIs.</p>

View File

@ -369,17 +369,17 @@
<h1 id="the-browsable-api">The Browsable API</h1>
<h1 id="the-browsable-api"><a class="toclink" href="#the-browsable-api">The Browsable API</a></h1>
<blockquote>
<p>It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.</p>
<p>&mdash; <a href="http://en.wikiquote.org/wiki/Alfred_North_Whitehead">Alfred North Whitehead</a>, An Introduction to Mathematics (1911)</p>
</blockquote>
<p>API may stand for Application <em>Programming</em> Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the <code>HTML</code> format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using <code>POST</code>, <code>PUT</code>, and <code>DELETE</code>.</p>
<h2 id="urls">URLs</h2>
<h2 id="urls"><a class="toclink" href="#urls">URLs</a></h2>
<p>If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The <code>rest_framework</code> package includes a <a href="../../api-guide/reverse/"><code>reverse</code></a> helper for this purpose.</p>
<h2 id="formats">Formats</h2>
<h2 id="formats"><a class="toclink" href="#formats">Formats</a></h2>
<p>By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using <code>?format=</code> in the request, so you can look at the raw JSON response in a browser by adding <code>?format=json</code> to the URL. There are helpful extensions for viewing JSON in <a href="https://addons.mozilla.org/en-US/firefox/addon/jsonview/">Firefox</a> and <a href="https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc">Chrome</a>.</p>
<h2 id="customizing">Customizing</h2>
<h2 id="customizing"><a class="toclink" href="#customizing">Customizing</a></h2>
<p>The browsable API is built with <a href="http://getbootstrap.com">Twitter's Bootstrap</a> (v 2.1.1), making it easy to customize the look-and-feel.</p>
<p>To customize the default style, create a template called <code>rest_framework/api.html</code> that extends from <code>rest_framework/base.html</code>. For example:</p>
<p><strong>templates/rest_framework/api.html</strong></p>
@ -387,7 +387,7 @@
... # Override blocks with required customizations
</code></pre>
<h3 id="overriding-the-default-theme">Overriding the default theme</h3>
<h3 id="overriding-the-default-theme"><a class="toclink" href="#overriding-the-default-theme">Overriding the default theme</a></h3>
<p>To replace the default theme, add a <code>bootstrap_theme</code> block to your <code>api.html</code> and insert a <code>link</code> to the desired Bootstrap theme css file. This will completely replace the included theme.</p>
<pre><code>{% block bootstrap_theme %}
&lt;link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css"&gt;
@ -412,7 +412,7 @@
<p><img alt="Slate theme" src="../../img/slate.png" /></p>
<p><em>Screenshot of the bootswatch 'Slate' theme</em></p>
<hr />
<h3 id="blocks">Blocks</h3>
<h3 id="blocks"><a class="toclink" href="#blocks">Blocks</a></h3>
<p>All of the blocks available in the browsable API base template that can be used in your <code>api.html</code>.</p>
<ul>
<li><code>body</code> - The entire html <code>&lt;body&gt;</code>.</li>
@ -426,11 +426,11 @@
<li><code>title</code> - Title of the page.</li>
<li><code>userlinks</code> - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use <code>{{ block.super }}</code> to preserve the authentication links.</li>
</ul>
<h4 id="components">Components</h4>
<h4 id="components"><a class="toclink" href="#components">Components</a></h4>
<p>All of the standard <a href="http://getbootstrap.com/2.3.2/components.html">Bootstrap components</a> are available.</p>
<h4 id="tooltips">Tooltips</h4>
<h4 id="tooltips"><a class="toclink" href="#tooltips">Tooltips</a></h4>
<p>The browsable API makes use of the Bootstrap tooltips component. Any element with the <code>js-tooltip</code> class and a <code>title</code> attribute has that title content will display a tooltip on hover events.</p>
<h3 id="login-template">Login Template</h3>
<h3 id="login-template"><a class="toclink" href="#login-template">Login Template</a></h3>
<p>To add branding and customize the look-and-feel of the login template, create a template called <code>login.html</code> and add it to your project, eg: <code>templates/rest_framework/login.html</code>. The template should extend from <code>rest_framework/login_base.html</code>.</p>
<p>You can add your site name or branding by including the branding block:</p>
<pre><code>{% block branding %}
@ -438,8 +438,8 @@
{% endblock %}
</code></pre>
<p>You can also customize the style by adding the <code>bootstrap_theme</code> or <code>style</code> block similar to <code>api.html</code>.</p>
<h3 id="advanced-customization">Advanced Customization</h3>
<h4 id="context">Context</h4>
<h3 id="advanced-customization"><a class="toclink" href="#advanced-customization">Advanced Customization</a></h3>
<h4 id="context"><a class="toclink" href="#context">Context</a></h4>
<p>The context that's available to the template:</p>
<ul>
<li><code>allowed_methods</code> : A list of methods allowed by the resource</li>
@ -460,9 +460,9 @@
<li><code>METHOD_PARAM</code> : The view can accept a method override</li>
</ul>
<p>You can override the <code>BrowsableAPIRenderer.get_context()</code> method to customise the context that gets passed to the template.</p>
<h4 id="not-using-basehtml">Not using base.html</h4>
<h4 id="not-using-basehtml"><a class="toclink" href="#not-using-basehtml">Not using base.html</a></h4>
<p>For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have <code>api.html</code> extend <code>base.html</code>. Then the page content and capabilities are entirely up to you.</p>
<h4 id="handling-choicefield-with-large-numbers-of-items">Handling <code>ChoiceField</code> with large numbers of items.</h4>
<h4 id="handling-choicefield-with-large-numbers-of-items"><a class="toclink" href="#handling-choicefield-with-large-numbers-of-items">Handling <code>ChoiceField</code> with large numbers of items.</a></h4>
<p>When a relationship or <code>ChoiceField</code> has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.</p>
<p>The simplest option in this case is to replace the select input with a standard text input. For example:</p>
<pre><code> author = serializers.HyperlinkedRelatedField(
@ -470,7 +470,7 @@
style={'base_template': 'input.html'}
)
</code></pre>
<h4 id="autocomplete">Autocomplete</h4>
<h4 id="autocomplete"><a class="toclink" href="#autocomplete">Autocomplete</a></h4>
<p>An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.</p>
<p>There are <a href="https://www.djangopackages.com/grids/g/auto-complete/">a variety of packages for autocomplete widgets</a>, such as <a href="https://github.com/yourlabs/django-autocomplete-light">django-autocomplete-light</a>, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the <code>widget</code> keyword argument since it now uses templated HTML generation.</p>
<p>Better support for autocomplete inputs is planned in future versions.</p>

View File

@ -381,14 +381,14 @@
<h1 id="browser-enhancements">Browser enhancements</h1>
<h1 id="browser-enhancements"><a class="toclink" href="#browser-enhancements">Browser enhancements</a></h1>
<blockquote>
<p>"There are two noncontroversial uses for overloaded POST. The first is to <em>simulate</em> HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"</p>
<p>&mdash; <a href="http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260">RESTful Web Services</a>, Leonard Richardson &amp; Sam Ruby.</p>
</blockquote>
<p>In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide.</p>
<p>As of version 3.3.0 onwards these are enabled with javascript, using the <a href="https://github.com/tomchristie/ajax-form">ajax-form</a> library.</p>
<h2 id="browser-based-put-delete-etc">Browser based PUT, DELETE, etc...</h2>
<h2 id="browser-based-put-delete-etc"><a class="toclink" href="#browser-based-put-delete-etc">Browser based PUT, DELETE, etc...</a></h2>
<p>The <a href="https://github.com/tomchristie/ajax-form">AJAX form library</a> supports browser-based <code>PUT</code>, <code>DELETE</code> and other methods on HTML forms.</p>
<p>After including the library, use the <code>data-method</code> attribute on the form, like so:</p>
<pre><code>&lt;form action="/" data-method="PUT"&gt;
@ -397,7 +397,7 @@
&lt;/form&gt;
</code></pre>
<p>Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in <a href="http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work">Ruby on Rails</a>) is no longer supported due to subtle issues that it introduces in request parsing.</p>
<h2 id="browser-based-submission-of-non-form-content">Browser based submission of non-form content</h2>
<h2 id="browser-based-submission-of-non-form-content"><a class="toclink" href="#browser-based-submission-of-non-form-content">Browser based submission of non-form content</a></h2>
<p>Browser-based submission of content types such as JSON are supported by the <a href="https://github.com/tomchristie/ajax-form">AJAX form library</a>, using form fields with <code>data-override='content-type'</code> and <code>data-override='content'</code> attributes.</p>
<p>For example:</p>
<pre><code> &lt;form action="/"&gt;
@ -407,12 +407,12 @@
&lt;/form&gt;
</code></pre>
<p>Note that prior to 3.3.0, this support was server-side rather than javascript based.</p>
<h2 id="url-based-format-suffixes">URL based format suffixes</h2>
<h2 id="url-based-format-suffixes"><a class="toclink" href="#url-based-format-suffixes">URL based format suffixes</a></h2>
<p>REST framework can take <code>?format=json</code> style URL parameters, which can be a
useful shortcut for determining which content type should be returned from
the view.</p>
<p>This behavior is controlled using the <code>URL_FORMAT_OVERRIDE</code> setting.</p>
<h2 id="http-header-based-method-overriding">HTTP header based method overriding</h2>
<h2 id="http-header-based-method-overriding"><a class="toclink" href="#http-header-based-method-overriding">HTTP header based method overriding</a></h2>
<p>Prior to version 3.3.0 the semi extension header <code>X-HTTP-Method-Override</code> was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware.</p>
<p>For example:</p>
<pre><code>METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
@ -425,7 +425,7 @@ class MethodOverrideMiddleware(object):
return
request.method = request.META[METHOD_OVERRIDE_HEADER]
</code></pre>
<h2 id="url-based-accept-headers">URL based accept headers</h2>
<h2 id="url-based-accept-headers"><a class="toclink" href="#url-based-accept-headers">URL based accept headers</a></h2>
<p>Until version 3.3.0 REST framework included built-in support for <code>?accept=application/json</code> style URL parameters, which would allow the <code>Accept</code> header to be overridden.</p>
<p>Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed.</p>
<p>For example:</p>
@ -435,7 +435,7 @@ class MethodOverrideMiddleware(object):
header = request.query_params.get('_accept', header)
return [token.strip() for token in header.split(',')]
</code></pre>
<h2 id="doesnt-html5-support-put-and-delete-forms">Doesn't HTML5 support PUT and DELETE forms?</h2>
<h2 id="doesnt-html5-support-put-and-delete-forms"><a class="toclink" href="#doesnt-html5-support-put-and-delete-forms">Doesn't HTML5 support PUT and DELETE forms?</a></h2>
<p>Nope. It was at one point intended to support <code>PUT</code> and <code>DELETE</code> forms, but
was later <a href="http://www.w3.org/TR/html5-diff/#changes-2010-06-24">dropped from the spec</a>. There remains
<a href="http://amundsen.com/examples/put-delete-forms/">ongoing discussion</a> about adding support for <code>PUT</code> and <code>DELETE</code>,

View File

@ -411,22 +411,22 @@
<h1 id="contributing-to-rest-framework">Contributing to REST framework</h1>
<h1 id="contributing-to-rest-framework"><a class="toclink" href="#contributing-to-rest-framework">Contributing to REST framework</a></h1>
<blockquote>
<p>The world can only really be changed one piece at a time. The art is picking that piece.</p>
<p>&mdash; <a href="http://www.w3.org/People/Berners-Lee/FAQ.html">Tim Berners-Lee</a></p>
</blockquote>
<p>There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.</p>
<h2 id="community">Community</h2>
<h2 id="community"><a class="toclink" href="#community">Community</a></h2>
<p>The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.</p>
<p>If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.</p>
<p>Other really great ways you can help move the community forward include helping to answer questions on the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a>, or setting up an <a href="http://stackexchange.com/filters/66475/rest-framework">email alert on StackOverflow</a> so that you get notified of any new questions with the <code>django-rest-framework</code> tag.</p>
<p>When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.</p>
<h2 id="code-of-conduct">Code of conduct</h2>
<h2 id="code-of-conduct"><a class="toclink" href="#code-of-conduct">Code of conduct</a></h2>
<p>Please keep the tone polite &amp; professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.</p>
<p>Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.</p>
<p>The <a href="https://www.djangoproject.com/conduct/">Django code of conduct</a> gives a fuller set of guidelines for participating in community forums.</p>
<h1 id="issues">Issues</h1>
<h1 id="issues"><a class="toclink" href="#issues">Issues</a></h1>
<p>It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a>. Feature requests, bug reports and other issues should be raised on the GitHub <a href="https://github.com/tomchristie/django-rest-framework/issues?state=open">issue tracker</a>.</p>
<p>Some tips on good issue reporting:</p>
<ul>
@ -436,7 +436,7 @@
<li>Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.</li>
<li>Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.</li>
</ul>
<h2 id="triaging-issues">Triaging issues</h2>
<h2 id="triaging-issues"><a class="toclink" href="#triaging-issues">Triaging issues</a></h2>
<p>Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to</p>
<ul>
<li>Read through the ticket - does it make sense, is it missing any context that would help explain it better?</li>
@ -445,12 +445,12 @@
<li>If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?</li>
<li>If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.</li>
</ul>
<h1 id="development">Development</h1>
<h1 id="development"><a class="toclink" href="#development">Development</a></h1>
<p>To start developing on Django REST framework, clone the repo:</p>
<pre><code>git clone git@github.com:tomchristie/django-rest-framework.git
</code></pre>
<p>Changes should broadly follow the <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.</p>
<h2 id="testing">Testing</h2>
<h2 id="testing"><a class="toclink" href="#testing">Testing</a></h2>
<p>To run the tests, clone the repository, and then:</p>
<pre><code># Setup the virtual environment
virtualenv env
@ -460,7 +460,7 @@ pip install -r requirements.txt
# Run the tests
./runtests.py
</code></pre>
<h3 id="test-options">Test options</h3>
<h3 id="test-options"><a class="toclink" href="#test-options">Test options</a></h3>
<p>Run using a more concise output style.</p>
<pre><code>./runtests.py -q
</code></pre>
@ -483,11 +483,11 @@ pip install -r requirements.txt
<pre><code>./runtests.py test_this_method
</code></pre>
<p>Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.</p>
<h3 id="running-against-multiple-environments">Running against multiple environments</h3>
<h3 id="running-against-multiple-environments"><a class="toclink" href="#running-against-multiple-environments">Running against multiple environments</a></h3>
<p>You can also use the excellent <a href="http://tox.readthedocs.org/en/latest/">tox</a> testing tool to run the tests against all supported versions of Python and Django. Install <code>tox</code> globally, and then simply run:</p>
<pre><code>tox
</code></pre>
<h2 id="pull-requests">Pull requests</h2>
<h2 id="pull-requests"><a class="toclink" href="#pull-requests">Pull requests</a></h2>
<p>It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.</p>
<p>It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.</p>
<p>It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.</p>
@ -496,12 +496,12 @@ pip install -r requirements.txt
<p>Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.</p>
<p><img alt="Travis status" src="../../img/travis-status.png" /></p>
<p><em>Above: Travis build notifications</em></p>
<h2 id="managing-compatibility-issues">Managing compatibility issues</h2>
<h2 id="managing-compatibility-issues"><a class="toclink" href="#managing-compatibility-issues">Managing compatibility issues</a></h2>
<p>Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the <code>compat.py</code> module, and should provide a single common interface that the rest of the codebase can use.</p>
<h1 id="documentation">Documentation</h1>
<h1 id="documentation"><a class="toclink" href="#documentation">Documentation</a></h1>
<p>The documentation for REST framework is built from the <a href="http://daringfireball.net/projects/markdown/basics">Markdown</a> source files in <a href="https://github.com/tomchristie/django-rest-framework/tree/master/docs">the docs directory</a>.</p>
<p>There are many great Markdown editors that make working with the documentation really easy. The <a href="http://mouapp.com/">Mou editor for Mac</a> is one such editor that comes highly recommended.</p>
<h2 id="building-the-documentation">Building the documentation</h2>
<h2 id="building-the-documentation"><a class="toclink" href="#building-the-documentation">Building the documentation</a></h2>
<p>To build the documentation, install MkDocs with <code>pip install mkdocs</code> and then run the following command.</p>
<pre><code>mkdocs build
</code></pre>
@ -509,16 +509,16 @@ pip install -r requirements.txt
<p>You can build the documentation and open a preview in a browser window by using the <code>serve</code> command.</p>
<pre><code>mkdocs serve
</code></pre>
<h2 id="language-style">Language style</h2>
<h2 id="language-style"><a class="toclink" href="#language-style">Language style</a></h2>
<p>Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.</p>
<p>Some other tips:</p>
<ul>
<li>Keep paragraphs reasonably short.</li>
<li>Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.</li>
</ul>
<h2 id="markdown-style">Markdown style</h2>
<h2 id="markdown-style"><a class="toclink" href="#markdown-style">Markdown style</a></h2>
<p>There are a couple of conventions you should follow when working on the documentation.</p>
<h5 id="1-headers">1. Headers</h5>
<h5 id="1-headers"><a class="toclink" href="#1-headers">1. Headers</a></h5>
<p>Headers should use the hash style. For example:</p>
<pre><code>### Some important topic
</code></pre>
@ -526,7 +526,7 @@ pip install -r requirements.txt
<pre><code>Some important topic
====================
</code></pre>
<h5 id="2-links">2. Links</h5>
<h5 id="2-links"><a class="toclink" href="#2-links">2. Links</a></h5>
<p>Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.</p>
<pre><code>Here is a link to [some other thing][other-thing].
@ -539,7 +539,7 @@ More text...
<pre><code>[authentication]: ../api-guide/authentication.md
</code></pre>
<p>Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.</p>
<h5 id="3-notes">3. Notes</h5>
<h5 id="3-notes"><a class="toclink" href="#3-notes">3. Notes</a></h5>
<p>If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:</p>
<pre><code>---

View File

@ -369,38 +369,38 @@
<h1 id="documenting-your-api">Documenting your API</h1>
<h1 id="documenting-your-api"><a class="toclink" href="#documenting-your-api">Documenting your API</a></h1>
<blockquote>
<p>A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.</p>
<p>&mdash; Roy Fielding, <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">REST APIs must be hypertext driven</a></p>
</blockquote>
<p>There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.</p>
<h2 id="endpoint-documentation">Endpoint documentation</h2>
<h2 id="endpoint-documentation"><a class="toclink" href="#endpoint-documentation">Endpoint documentation</a></h2>
<p>The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.</p>
<hr />
<h4 id="django-rest-swagger">Django REST Swagger</h4>
<h4 id="django-rest-swagger"><a class="toclink" href="#django-rest-swagger">Django REST Swagger</a></h4>
<p>Marc Gibbons' <a href="https://github.com/marcgibbons/django-rest-swagger">Django REST Swagger</a> integrates REST framework with the <a href="https://developers.helloreverb.com/swagger/">Swagger</a> API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.</p>
<p>The package is fully documented, well supported, and comes highly recommended.</p>
<p>Django REST Swagger supports REST framework versions 2.3 and above.</p>
<p><img alt="Screenshot - Django REST Swagger" src="../../img/django-rest-swagger.png" /></p>
<hr />
<h4 id="rest-framework-docs">REST Framework Docs</h4>
<h4 id="rest-framework-docs"><a class="toclink" href="#rest-framework-docs">REST Framework Docs</a></h4>
<p>The <a href="https://github.com/marcgibbons/django-rest-framework-docs">REST Framework Docs</a> package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.</p>
<p><img alt="Screenshot - REST Framework Docs" src="../../img/rest-framework-docs.png" /></p>
<hr />
<h4 id="apiary">Apiary</h4>
<h4 id="apiary"><a class="toclink" href="#apiary">Apiary</a></h4>
<p>There are various other online tools and services for providing API documentation. One notable service is <a href="http://apiary.io/">Apiary</a>. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing &amp; prototyping, and various other tools.</p>
<p><img alt="Screenshot - Apiary" src="../../img/apiary.png" /></p>
<hr />
<h2 id="self-describing-apis">Self describing APIs</h2>
<h2 id="self-describing-apis"><a class="toclink" href="#self-describing-apis">Self describing APIs</a></h2>
<p>The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.</p>
<p><img alt="Screenshot - Self describing API" src="../../img/self-describing.png" /></p>
<hr />
<h4 id="setting-the-title">Setting the title</h4>
<h4 id="setting-the-title"><a class="toclink" href="#setting-the-title">Setting the title</a></h4>
<p>The title that is used in the browsable API is generated from the view class name or function name. Any trailing <code>View</code> or <code>ViewSet</code> suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.</p>
<p>For example, the view <code>UserListView</code>, will be named <code>User List</code> when presented in the browsable API.</p>
<p>When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set <code>UserViewSet</code> will generate views named <code>User List</code> and <code>User Instance</code>.</p>
<h4 id="setting-the-description">Setting the description</h4>
<h4 id="setting-the-description"><a class="toclink" href="#setting-the-description">Setting the description</a></h4>
<p>The description in the browsable API is generated from the docstring of the view or viewset.</p>
<p>If the python <code>markdown</code> library is installed, then <a href="http://daringfireball.net/projects/markdown/">markdown syntax</a> may be used in the docstring, and will be converted to HTML in the browsable API. For example:</p>
<pre><code>class AccountListView(views.APIView):
@ -413,7 +413,7 @@
"""
</code></pre>
<p>Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.</p>
<h4 id="the-options-method">The <code>OPTIONS</code> method</h4>
<h4 id="the-options-method"><a class="toclink" href="#the-options-method">The <code>OPTIONS</code> method</a></h4>
<p>REST framework APIs also support programmatically accessible descriptions, using the <code>OPTIONS</code> HTTP method. A view will respond to an <code>OPTIONS</code> request with metadata including the name, description, and the various media types it accepts and responds with.</p>
<p>When using the generic views, any <code>OPTIONS</code> requests will additionally respond with metadata regarding any <code>POST</code> or <code>PUT</code> actions available, describing which fields are on the serializer.</p>
<p>You can modify the response behavior to <code>OPTIONS</code> requests by overriding the <code>metadata</code> view method. For example:</p>
@ -426,7 +426,7 @@
return data
</code></pre>
<hr />
<h2 id="the-hypermedia-approach">The hypermedia approach</h2>
<h2 id="the-hypermedia-approach"><a class="toclink" href="#the-hypermedia-approach">The hypermedia approach</a></h2>
<p>To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.</p>
<p>In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the <em>media types</em> that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.</p>
<p>To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The <a href="../rest-hypermedia-hateoas/">REST, Hypermedia &amp; HATEOAS</a> section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.</p>

View File

@ -369,9 +369,9 @@
<h1 id="html-forms">HTML &amp; Forms</h1>
<h1 id="html-forms"><a class="toclink" href="#html-forms">HTML &amp; Forms</a></h1>
<p>REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.</p>
<h2 id="rendering-html">Rendering HTML</h2>
<h2 id="rendering-html"><a class="toclink" href="#rendering-html">Rendering HTML</a></h2>
<p>In order to return HTML responses you'll need to either <code>TemplateHTMLRenderer</code>, or <code>StaticHTMLRenderer</code>.</p>
<p>The <code>TemplateHTMLRenderer</code> class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.</p>
<p>The <code>StaticHTMLRender</code> class expects the response to contain a string of the pre-rendered HTML content.</p>
@ -380,6 +380,7 @@
<p><strong>views.py</strong>:</p>
<pre><code>from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
@ -401,7 +402,7 @@ class ProfileList(APIView):
&lt;/ul&gt;
&lt;/body&gt;&lt;/html&gt;
</code></pre>
<h2 id="rendering-forms">Rendering Forms</h2>
<h2 id="rendering-forms"><a class="toclink" href="#rendering-forms">Rendering Forms</a></h2>
<p>Serializers may be rendered as forms by using the <code>render_form</code> template tag, and including the serializer instance as context to the template.</p>
<p>The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:</p>
<p><strong>views.py</strong>:</p>
@ -442,7 +443,7 @@ class ProfileDetail(APIView):
&lt;/body&gt;&lt;/html&gt;
</code></pre>
<h3 id="using-template-packs">Using template packs</h3>
<h3 id="using-template-packs"><a class="toclink" href="#using-template-packs">Using template packs</a></h3>
<p>The <code>render_form</code> tag takes an optional <code>template_pack</code> argument, that specifies which template directory should be used for rendering the form and form fields.</p>
<p>REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are <code>horizontal</code>, <code>vertical</code>, and <code>inline</code>. The default style is <code>horizontal</code>. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.</p>
<p>The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:</p>
@ -465,7 +466,7 @@ class ProfileDetail(APIView):
remember_me = serializers.BooleanField()
</code></pre>
<hr />
<h4 id="rest_frameworkvertical"><code>rest_framework/vertical</code></h4>
<h4 id="rest_frameworkvertical"><a class="toclink" href="#rest_frameworkvertical"><code>rest_framework/vertical</code></a></h4>
<p>Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.</p>
<p><em>This is the default template pack.</em></p>
<pre><code>{% load rest_framework %}
@ -480,7 +481,7 @@ class ProfileDetail(APIView):
</code></pre>
<p><img alt="Vertical form example" src="../../img/vertical.png" /></p>
<hr />
<h4 id="rest_frameworkhorizontal"><code>rest_framework/horizontal</code></h4>
<h4 id="rest_frameworkhorizontal"><a class="toclink" href="#rest_frameworkhorizontal"><code>rest_framework/horizontal</code></a></h4>
<p>Presents labels and controls alongside each other, using a 2/10 column split.</p>
<p><em>This is the form style used in the browsable API and admin renderers.</em></p>
<pre><code>{% load rest_framework %}
@ -499,7 +500,7 @@ class ProfileDetail(APIView):
</code></pre>
<p><img alt="Horizontal form example" src="../../img/horizontal.png" /></p>
<hr />
<h4 id="rest_frameworkinline"><code>rest_framework/inline</code></h4>
<h4 id="rest_frameworkinline"><a class="toclink" href="#rest_frameworkinline"><code>rest_framework/inline</code></a></h4>
<p>A compact form style that presents all the controls inline.</p>
<pre><code>{% load rest_framework %}
@ -512,7 +513,7 @@ class ProfileDetail(APIView):
&lt;/form&gt;
</code></pre>
<p><img alt="Inline form example" src="../../img/inline.png" /></p>
<h2 id="field-styles">Field styles</h2>
<h2 id="field-styles"><a class="toclink" href="#field-styles">Field styles</a></h2>
<p>Serializer fields can have their rendering style customized by using the <code>style</code> keyword argument. This argument is a dictionary of options that control the template and layout used.</p>
<p>The most common way to customize the field style is to use the <code>base_template</code> style keyword argument to select which template in the template pack should be use.</p>
<p>For example, to render a <code>CharField</code> as an HTML textarea rather than the default HTML input, you would use something like this:</p>

View File

@ -369,7 +369,7 @@
<h1 id="internationalization">Internationalization</h1>
<h1 id="internationalization"><a class="toclink" href="#internationalization">Internationalization</a></h1>
<blockquote>
<p>Supporting internationalization is not optional. It must be a core feature.</p>
<p>&mdash; <a href="http://youtu.be/Wa0VfS2q94Y">Jannis Leidel, speaking at Django Under the Hood, 2015</a>.</p>
@ -380,7 +380,7 @@
<li>Select a language other than English as the default, using the standard <code>LANGUAGE_CODE</code> Django setting.</li>
<li>Allow clients to choose a language themselves, using the <code>LocaleMiddleware</code> included with Django. A typical usage for API clients would be to include an <code>Accept-Language</code> request header.</li>
</ul>
<h2 id="enabling-internationalized-apis">Enabling internationalized APIs</h2>
<h2 id="enabling-internationalized-apis"><a class="toclink" href="#enabling-internationalized-apis">Enabling internationalized APIs</a></h2>
<p>You can change the default language by using the standard Django <code>LANGUAGE_CODE</code> setting:</p>
<pre><code>LANGUAGE_CODE = "es-es"
</code></pre>
@ -407,7 +407,7 @@ Host: example.org
<pre><code>{"detail": {"username": ["Esse campo deve ser unico."]}}
</code></pre>
<p>If you want to use different string for parts of the response such as <code>detail</code> and <code>non_field_errors</code> then you can modify this behavior by using a <a href="../../api-guide/exceptions/#custom-exception-handling">custom exception handler</a>.</p>
<h4 id="specifying-the-set-of-supported-languages">Specifying the set of supported languages.</h4>
<h4 id="specifying-the-set-of-supported-languages"><a class="toclink" href="#specifying-the-set-of-supported-languages">Specifying the set of supported languages.</a></h4>
<p>By default all available languages will be supported.</p>
<p>If you only wish to support a subset of the available languages, use Django's standard <code>LANGUAGES</code> setting:</p>
<pre><code>LANGUAGES = [
@ -415,14 +415,14 @@ Host: example.org
('en', _('English')),
]
</code></pre>
<h2 id="adding-new-translations">Adding new translations</h2>
<h2 id="adding-new-translations"><a class="toclink" href="#adding-new-translations">Adding new translations</a></h2>
<p>REST framework translations are managed online using <a href="https://www.transifex.com/projects/p/django-rest-framework/">Transifex</a>. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package.</p>
<p>Sometimes you may need to add translation strings to your project locally. You may need to do this if:</p>
<ul>
<li>You want to use REST Framework in a language which has not been translated yet on Transifex.</li>
<li>Your project includes custom error messages, which are not part of REST framework's default translation strings.</li>
</ul>
<h4 id="translating-a-new-language-locally">Translating a new language locally</h4>
<h4 id="translating-a-new-language-locally"><a class="toclink" href="#translating-a-new-language-locally">Translating a new language locally</a></h4>
<p>This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading <a href="https://docs.djangoproject.com/en/1.7/topics/i18n/translation">Django's translation docs</a>.</p>
<p>If you're translating a new language you'll need to translate the existing REST framework error messages:</p>
<ol>
@ -447,7 +447,7 @@ available for Django to use. You should see a message like <code>processing file
</li>
</ol>
<p>If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source <code>django.po</code> file into a <code>LOCALE_PATHS</code> folder, and can instead simply run Django's standard <code>makemessages</code> process.</p>
<h2 id="how-the-language-is-determined">How the language is determined</h2>
<h2 id="how-the-language-is-determined"><a class="toclink" href="#how-the-language-is-determined">How the language is determined</a></h2>
<p>If you want to allow per-request language preferences you'll need to include <code>django.middleware.locale.LocaleMiddleware</code> in your <code>MIDDLEWARE_CLASSES</code> setting.</p>
<p>You can find more information on how the language preference is determined in the <a href="https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#how-django-discovers-language-preference">Django documentation</a>. For reference, the method is:</p>
<ol>

View File

@ -365,13 +365,13 @@
<h1 id="kickstarting-django-rest-framework-3">Kickstarting Django REST framework 3</h1>
<h1 id="kickstarting-django-rest-framework-3"><a class="toclink" href="#kickstarting-django-rest-framework-3">Kickstarting Django REST framework 3</a></h1>
<hr />
<iframe style="display: block; margin: 0 auto 0 auto" width="480" height="360" src="https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3/widget/video.html" frameborder="0" scrolling="no"> </iframe>
<hr />
<p>In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.</p>
<h2 id="project-details">Project details</h2>
<h2 id="project-details"><a class="toclink" href="#project-details">Project details</a></h2>
<p>This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:</p>
<ul>
<li>Faster, simpler and easier-to-use serializers.</li>
@ -388,10 +388,10 @@
<p>Many thanks to everyone for your support so far,</p>
<p>Tom Christie :)</p>
<hr />
<h2 id="sponsors">Sponsors</h2>
<h2 id="sponsors"><a class="toclink" href="#sponsors">Sponsors</a></h2>
<p>We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.</p>
<hr />
<h3 id="platinum-sponsors">Platinum sponsors</h3>
<h3 id="platinum-sponsors"><a class="toclink" href="#platinum-sponsors">Platinum sponsors</a></h3>
<p>Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.</p>
<ul class="sponsor diamond">
<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/0-eventbrite.png);">Eventbrite</a></li>
@ -413,7 +413,7 @@
<div style="clear: both"></div>
<hr />
<h3 id="gold-sponsors">Gold sponsors</h3>
<h3 id="gold-sponsors"><a class="toclink" href="#gold-sponsors">Gold sponsors</a></h3>
<p>Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.</p>
<ul class="sponsor gold">
<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../../img/sponsors/2-laterpay.png);">LaterPay</a></li>
@ -447,7 +447,7 @@
<div style="clear: both; padding-bottom: 40px;"></div>
<hr />
<h3 id="silver-sponsors">Silver sponsors</h3>
<h3 id="silver-sponsors"><a class="toclink" href="#silver-sponsors">Silver sponsors</a></h3>
<p>The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank&nbsp;you to individuals who have choosen to privately support the project at this level.</p>
<ul class="sponsor silver">
<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
@ -491,12 +491,12 @@
<p><strong>Individual backers</strong>: Paul Hallett, <a href="http://www.paulwhippconsulting.com/">Paul Whipp</a>, Dylan Roy, Jannis Leidel, <a href="https://linovia.com/en/">Xavier Ordoquy</a>, <a href="http://spielmannsolutions.com/">Johannes Spielmann</a>, <a href="http://brooklynhacker.com/">Rob Spectre</a>, <a href="http://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.</p>
<hr />
<h3 id="advocates">Advocates</h3>
<h3 id="advocates"><a class="toclink" href="#advocates">Advocates</a></h3>
<p>The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!</p>
<p><strong>Individual backers</strong>: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.</p>
<p><strong>Corporate backers</strong>: Savannah Informatics, Prism Skylabs, Musical Operating Devices.</p>
<hr />
<h3 id="supporters">Supporters</h3>
<h3 id="supporters"><a class="toclink" href="#supporters">Supporters</a></h3>
<p>There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!</p>

View File

@ -377,7 +377,7 @@
<h1 id="project-management">Project management</h1>
<h1 id="project-management"><a class="toclink" href="#project-management">Project management</a></h1>
<blockquote>
<p>"No one can whistle a symphony; it takes a whole orchestra to play it"</p>
<p>&mdash; Halford E. Luccock</p>
@ -386,9 +386,9 @@
<p>The aim is to ensure that the project has a high
<a href="http://en.wikipedia.org/wiki/Bus_factor">"bus factor"</a>, and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.</p>
<hr />
<h2 id="maintenance-team">Maintenance team</h2>
<h2 id="maintenance-team"><a class="toclink" href="#maintenance-team">Maintenance team</a></h2>
<p>We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.</p>
<h4 id="current-team">Current team</h4>
<h4 id="current-team"><a class="toclink" href="#current-team">Current team</a></h4>
<p>The <a href="https://github.com/tomchristie/django-rest-framework/issues/2190">maintenance team for Q1 2015</a>:</p>
<ul>
<li><a href="https://github.com/tomchristie/">@tomchristie</a></li>
@ -397,7 +397,7 @@
<li><a href="https://github.com/kevin-brown/">@kevin-brown</a></li>
<li><a href="https://github.com/jpadilla/">@jpadilla</a></li>
</ul>
<h4 id="maintenance-cycles">Maintenance cycles</h4>
<h4 id="maintenance-cycles"><a class="toclink" href="#maintenance-cycles">Maintenance cycles</a></h4>
<p>Each maintenance cycle is initiated by an issue being opened with the <code>Process</code> label.</p>
<ul>
<li>To be considered for a maintainer role simply comment against the issue.</li>
@ -430,7 +430,7 @@ If you wish to be considered for this or a future date, please comment against t
To modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.
</code></pre>
<h4 id="responsibilities-of-team-members">Responsibilities of team members</h4>
<h4 id="responsibilities-of-team-members"><a class="toclink" href="#responsibilities-of-team-members">Responsibilities of team members</a></h4>
<p>Team members have the following responsibilities.</p>
<ul>
<li>Close invalid or resolved tickets.</li>
@ -448,7 +448,7 @@ To modify this process for future maintenance cycles make a pull request to the
</ul>
<p>It should be noted that participating actively in the REST framework project clearly <strong>does not require being part of the maintenance team</strong>. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.</p>
<hr />
<h2 id="release-process">Release process</h2>
<h2 id="release-process"><a class="toclink" href="#release-process">Release process</a></h2>
<p>The release manager is selected on every quarterly maintenance cycle.</p>
<ul>
<li>The manager should be selected by <code>@tomchristie</code>.</li>
@ -484,9 +484,9 @@ To modify this process for future releases make a pull request to the [project m
</code></pre>
<p>When pushing the release to PyPI ensure that your environment has been installed from our development <code>requirement.txt</code>, so that documentation and PyPI installs are consistently being built against a pinned set of packages.</p>
<hr />
<h2 id="translations">Translations</h2>
<h2 id="translations"><a class="toclink" href="#translations">Translations</a></h2>
<p>The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the <a href="https://www.transifex.com/projects/p/django-rest-framework/">transifex service</a>.</p>
<h3 id="managing-transifex">Managing Transifex</h3>
<h3 id="managing-transifex"><a class="toclink" href="#managing-transifex">Managing Transifex</a></h3>
<p>The <a href="https://pypi.python.org/pypi/transifex-client">official Transifex client</a> is used to upload and download translations to Transifex. The client is installed using pip:</p>
<pre><code>pip install transifex-client
</code></pre>
@ -497,7 +497,7 @@ token = ***
password = ***
hostname = https://www.transifex.com
</code></pre>
<h3 id="upload-new-source-files">Upload new source files</h3>
<h3 id="upload-new-source-files"><a class="toclink" href="#upload-new-source-files">Upload new source files</a></h3>
<p>When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:</p>
<pre><code># 1. Update the source django.po file, which is the US English version.
cd rest_framework
@ -513,7 +513,7 @@ tx push -s
<li>Modified strings will be added as well.</li>
<li>Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then <a href="http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations">Transifex Translation Memory</a> will automatically include the translation string.</li>
</ul>
<h3 id="download-translations">Download translations</h3>
<h3 id="download-translations"><a class="toclink" href="#download-translations">Download translations</a></h3>
<p>When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:</p>
<pre><code># 3. Pull the translated django.po files from Transifex.
tx pull -a
@ -522,14 +522,14 @@ cd rest_framework
django-admin.py compilemessages
</code></pre>
<hr />
<h2 id="project-requirements">Project requirements</h2>
<h2 id="project-requirements"><a class="toclink" href="#project-requirements">Project requirements</a></h2>
<p>All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the <code>requirements</code> directory. The requirements files are referenced from the <code>tox.ini</code> configuration file, ensuring we have a single source of truth for package versions used in testing.</p>
<p>Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the <code>pip list --outdated</code>.</p>
<hr />
<h2 id="project-ownership">Project ownership</h2>
<h2 id="project-ownership"><a class="toclink" href="#project-ownership">Project ownership</a></h2>
<p>The PyPI package is owned by <code>@tomchristie</code>. As a backup <code>@j4mie</code> also has ownership of the package.</p>
<p>If <code>@tomchristie</code> ceases to participate in the project then <code>@j4mie</code> has responsibility for handing over ownership duties.</p>
<h4 id="outstanding-management-ownership-issues">Outstanding management &amp; ownership issues</h4>
<h4 id="outstanding-management-ownership-issues"><a class="toclink" href="#outstanding-management-ownership-issues">Outstanding management &amp; ownership issues</a></h4>
<p>The following issues still need to be addressed:</p>
<ul>
<li><a href="https://github.com/tomchristie/django-rest-framework/issues/2162">Consider moving the repo into a proper GitHub organization</a>.</li>

View File

@ -385,16 +385,16 @@
<h1 id="release-notes">Release Notes</h1>
<h1 id="release-notes"><a class="toclink" href="#release-notes">Release Notes</a></h1>
<blockquote>
<p>Release Early, Release Often</p>
<p>&mdash; Eric S. Raymond, <a href="http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html">The Cathedral and the Bazaar</a>.</p>
</blockquote>
<h2 id="versioning">Versioning</h2>
<h2 id="versioning"><a class="toclink" href="#versioning">Versioning</a></h2>
<p>Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.</p>
<p>Medium version numbers (0.x.0) may include API changes, in line with the <a href="#deprecation-policy">deprecation policy</a>. You should read the release notes carefully before upgrading between medium point releases.</p>
<p>Major version numbers (x.0.0) are reserved for substantial project milestones.</p>
<h2 id="deprecation-policy">Deprecation policy</h2>
<h2 id="deprecation-policy"><a class="toclink" href="#deprecation-policy">Deprecation policy</a></h2>
<p>REST framework releases follow a formal deprecation policy, which is in line with <a href="https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy">Django's deprecation policy</a>.</p>
<p>The timeline for deprecation of a feature present in version 1.0 would work as follows:</p>
<ul>
@ -409,7 +409,7 @@
</li>
</ul>
<p>Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.</p>
<h2 id="upgrading">Upgrading</h2>
<h2 id="upgrading"><a class="toclink" href="#upgrading">Upgrading</a></h2>
<p>To upgrade Django REST framework to the latest version, use pip:</p>
<pre><code>pip install -U djangorestframework
</code></pre>
@ -417,8 +417,17 @@
<pre><code>pip freeze | grep djangorestframework
</code></pre>
<hr />
<h2 id="33x-series">3.3.x series</h2>
<h3 id="330">3.3.0</h3>
<h2 id="33x-series"><a class="toclink" href="#33x-series">3.3.x series</a></h2>
<h3 id="331"><a class="toclink" href="#331">3.3.1</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.3.1+Release%22">4th November 2015</a>.</p>
<ul>
<li>Resolve parsing bug when accessing <code>request.POST</code> (<a href="https://github.com/tomchristie/django-rest-framework/issues/3592">#3592</a>)</li>
<li>Correctly deal with <code>to_field</code> referring to primary key. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3593">#3593</a>)</li>
<li>Allow filter HTML to render when no <code>filter_class</code> is defined. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3560">#3560</a>)</li>
<li>Fix admin rendering issues. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3564">#3564</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/3556">#3556</a>)</li>
<li>Fix issue with DecimalValidator. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3568">#3568</a>)</li>
</ul>
<h3 id="330"><a class="toclink" href="#330">3.3.0</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.3.0+Release%22">28th October 2015</a>.</p>
<ul>
<li>HTML controls for filters. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3315">#3315</a>)</li>
@ -433,13 +442,13 @@
<li>Removed support for Django 1.5 &amp; 1.6. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3421">#3421</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/3429">#3429</a>)</li>
<li>Removed 'south' migrations. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3495">#3495</a>)</li>
</ul>
<h2 id="32x-series">3.2.x series</h2>
<h3 id="325">3.2.5</h3>
<h2 id="32x-series"><a class="toclink" href="#32x-series">3.2.x series</a></h2>
<h3 id="325"><a class="toclink" href="#325">3.2.5</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.5+Release%22">27th October 2015</a>.</p>
<ul>
<li>Escape <code>username</code> in optional logout tag. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3550">#3550</a>)</li>
</ul>
<h3 id="324">3.2.4</h3>
<h3 id="324"><a class="toclink" href="#324">3.2.4</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.4+Release%22">21th September 2015</a>.</p>
<ul>
<li>Don't error on missing <code>ViewSet.search_fields</code> attribute. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3324">#3324</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/3323">#3323</a>)</li>
@ -448,7 +457,7 @@
<li>Multi-level dictionaries not supported in multipart requests. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3314">#3314</a>)</li>
<li>Fix <code>ListField</code> truncation on HTTP PATCH (<a href="https://github.com/tomchristie/django-rest-framework/issues/3415">#3415</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2761">#2761</a>)</li>
</ul>
<h3 id="323">3.2.3</h3>
<h3 id="323"><a class="toclink" href="#323">3.2.3</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.3+Release%22">24th August 2015</a>.</p>
<ul>
<li>Added <code>html_cutoff</code> and <code>html_cutoff_text</code> for limiting select dropdowns. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3313">#3313</a>)</li>
@ -459,7 +468,7 @@
<li>Fix to ensure admin renderer continues to work when pagination is disabled. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3275">#3275</a>)</li>
<li>Resolve error with <code>LimitOffsetPagination</code> when count=0, offset=0. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3303">#3303</a>)</li>
</ul>
<h3 id="322">3.2.2</h3>
<h3 id="322"><a class="toclink" href="#322">3.2.2</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.2+Release%22">13th August 2015</a>.</p>
<ul>
<li>Add <code>display_value()</code> method for use when displaying relational field select inputs. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3254">#3254</a>)</li>
@ -469,7 +478,7 @@
<li>Resolve issue with rendering nested serializers in forms. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3260">#3260</a>)</li>
<li>Raise an error if user accidentally pass a serializer instance to a response, rather than data. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3241">#3241</a>)</li>
</ul>
<h3 id="321">3.2.1</h3>
<h3 id="321"><a class="toclink" href="#321">3.2.1</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.1+Release%22">7th August 2015</a>.</p>
<ul>
<li>Fix for relational select widgets rendering without any choices. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3237">#3237</a>)</li>
@ -477,7 +486,7 @@
<li>Fix for ListFields with single value in HTML form input. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3238">#3238</a>)</li>
<li>Allow <code>request.FILES</code> for compat with Django's <code>HTTPRequest</code> class. (<a href="https://github.com/tomchristie/django-rest-framework/issues/3239">#3239</a>)</li>
</ul>
<h3 id="320">3.2.0</h3>
<h3 id="320"><a class="toclink" href="#320">3.2.0</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.2.0+Release%22">6th August 2015</a>.</p>
<ul>
<li>Add <code>AdminRenderer</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2926">#2926</a>)</li>
@ -511,8 +520,8 @@
<li>Numerous other cleanups, improvements to error messaging, private API &amp; minor fixes.</li>
</ul>
<hr />
<h2 id="31x-series">3.1.x series</h2>
<h3 id="313">3.1.3</h3>
<h2 id="31x-series"><a class="toclink" href="#31x-series">3.1.x series</a></h2>
<h3 id="313"><a class="toclink" href="#313">3.1.3</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.3+Release%22">4th June 2015</a>.</p>
<ul>
<li>Add <code>DurationField</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2481">#2481</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2989">#2989</a>)</li>
@ -528,7 +537,7 @@
<li><code>IPAddressField</code> improvements. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2747">#2747</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2618">#2618</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/3008">#3008</a>)</li>
<li>Improve <code>DecimalField</code> for easier subclassing. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2695">#2695</a>)</li>
</ul>
<h3 id="312">3.1.2</h3>
<h3 id="312"><a class="toclink" href="#312">3.1.2</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.2+Release%22">13rd May 2015</a>.</p>
<ul>
<li><code>DateField.to_representation</code> can handle str and empty values. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2656">#2656</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2687">#2687</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2869">#2869</a>)</li>
@ -547,7 +556,7 @@
<li>Check <code>AcceptHeaderVersioning</code> with content negotiation in place. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2868">#2868</a>)</li>
<li>Allow <code>DjangoObjectPermissions</code> to use views that define <code>get_queryset</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2905">#2905</a>)</li>
</ul>
<h3 id="311">3.1.1</h3>
<h3 id="311"><a class="toclink" href="#311">3.1.1</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.1+Release%22">23rd March 2015</a>.</p>
<ul>
<li><strong>Security fix</strong>: Escape tab switching cookie name in browsable API.</li>
@ -562,12 +571,12 @@
<li>Support serializing unsaved models with related fields. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2637">#2637</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2641">#2641</a>)</li>
<li>Allow blank/null on radio.html choices. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2631">#2631</a>)</li>
</ul>
<h3 id="310">3.1.0</h3>
<h3 id="310"><a class="toclink" href="#310">3.1.0</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.1.0+Release%22">5th March 2015</a>.</p>
<p>For full details see the <a href="../3.1-announcement/">3.1 release announcement</a>.</p>
<hr />
<h2 id="30x-series">3.0.x series</h2>
<h3 id="305">3.0.5</h3>
<h2 id="30x-series"><a class="toclink" href="#30x-series">3.0.x series</a></h2>
<h3 id="305"><a class="toclink" href="#305">3.0.5</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.5+Release%22">10th February 2015</a>.</p>
<ul>
<li>Fix a bug where <code>_closable_objects</code> breaks pickling. (<a href="https://github.com/tomchristie/django-rest-framework/issues/1850">#1850</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2492">#2492</a>)</li>
@ -579,7 +588,7 @@
<li>Fix <code>detail_route</code> and <code>list_route</code> mutable argument. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2518">#2518</a>)</li>
<li>Prefetching the user object when getting the token in <code>TokenAuthentication</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2519">#2519</a>)</li>
</ul>
<h3 id="304">3.0.4</h3>
<h3 id="304"><a class="toclink" href="#304">3.0.4</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.4+Release%22">28th January 2015</a>.</p>
<ul>
<li>Django 1.8a1 support. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2425">#2425</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2446">#2446</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2441">#2441</a>)</li>
@ -596,7 +605,7 @@
<li>Fix the serializer inheritance. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2388">#2388</a>)</li>
<li>Fix caching issues with <code>ReturnDict</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2360">#2360</a>)</li>
</ul>
<h3 id="303">3.0.3</h3>
<h3 id="303"><a class="toclink" href="#303">3.0.3</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.3+Release%22">8th January 2015</a>.</p>
<ul>
<li>Fix <code>MinValueValidator</code> on <code>models.DateField</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2369">#2369</a>)</li>
@ -615,7 +624,7 @@
<li>Ability to customize router URLs for custom actions, using <code>url_path</code>. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2010">#2010</a>)</li>
<li>Don't install Django REST Framework as egg. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2386">#2386</a>)</li>
</ul>
<h3 id="302">3.0.2</h3>
<h3 id="302"><a class="toclink" href="#302">3.0.2</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.2+Release%22">17th December 2014</a>.</p>
<ul>
<li>Ensure <code>request.user</code> is made available to response middleware. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2155">#2155</a>)</li>
@ -626,7 +635,7 @@
<li>Fix empty HTML values when a default is provided. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2280">#2280</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2294">#2294</a>)</li>
<li>Fix <code>SlugRelatedField</code> raising <code>UnicodeEncodeError</code> when used as a multiple choice input. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2290">#2290</a>)</li>
</ul>
<h3 id="301">3.0.1</h3>
<h3 id="301"><a class="toclink" href="#301">3.0.1</a></h3>
<p><strong>Date</strong>: <a href="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.1+Release%22">11th December 2014</a>.</p>
<ul>
<li>More helpful error message when the default Serializer <code>create()</code> fails. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2013">#2013</a>)</li>
@ -650,7 +659,7 @@
<li>Improve field lookup behavior for dicts/mappings. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2244">#2244</a>, <a href="https://github.com/tomchristie/django-rest-framework/issues/2243">#2243</a>)</li>
<li>Optimized hyperlinked PK. (<a href="https://github.com/tomchristie/django-rest-framework/issues/2242">#2242</a>)</li>
</ul>
<h3 id="300">3.0.0</h3>
<h3 id="300"><a class="toclink" href="#300">3.0.0</a></h3>
<p><strong>Date</strong>: 1st December 2014</p>
<p>For full details see the <a href="../3.0-announcement/">3.0 release announcement</a>.</p>
<hr />
@ -677,6 +686,8 @@
<!-- 3.2.5 -->
<!-- 3.3.0 -->
<!-- 3.3.1 -->
</div> <!--/span-->

View File

@ -369,7 +369,7 @@
<h1 id="rest-hypermedia-hateoas">REST, Hypermedia &amp; HATEOAS</h1>
<h1 id="rest-hypermedia-hateoas"><a class="toclink" href="#rest-hypermedia-hateoas">REST, Hypermedia &amp; HATEOAS</a></h1>
<blockquote>
<p>You keep using that word "REST". I do not think it means what you think it means.</p>
<p>&mdash; Mike Amundsen, <a href="http://vimeo.com/channels/restfest/page:2">REST fest 2012 keynote</a>.</p>
@ -387,12 +387,12 @@ the Design of Network-based Software Architectures</a>.</li>
<li>The <a href="http://martinfowler.com/articles/richardsonMaturityModel.html">Richardson Maturity Model</a>.</li>
</ul>
<p>For a more thorough background, check out Klabnik's <a href="http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list">Hypermedia API reading list</a>.</p>
<h2 id="building-hypermedia-apis-with-rest-framework">Building Hypermedia APIs with REST framework</h2>
<h2 id="building-hypermedia-apis-with-rest-framework"><a class="toclink" href="#building-hypermedia-apis-with-rest-framework">Building Hypermedia APIs with REST framework</a></h2>
<p>REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.</p>
<h2 id="what-rest-framework-provides">What REST framework provides.</h2>
<h2 id="what-rest-framework-provides"><a class="toclink" href="#what-rest-framework-provides">What REST framework provides.</a></h2>
<p>It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.</p>
<p>REST framework also includes <a href="../../api-guide/serializers/">serialization</a> and <a href="../../api-guide/parsers/">parser</a>/<a href="../../api-guide/renderers/">renderer</a> components that make it easy to build appropriate media types, <a href="../../api-guide/fields/">hyperlinked relations</a> for building well-connected systems, and great support for <a href="../../api-guide/content-negotiation/">content negotiation</a>.</p>
<h2 id="what-rest-framework-doesnt-provide">What REST framework doesn't provide.</h2>
<h2 id="what-rest-framework-doesnt-provide"><a class="toclink" href="#what-rest-framework-doesnt-provide">What REST framework doesn't provide.</a></h2>
<p>What REST framework doesn't do is give you machine readable hypermedia formats such as <a href="http://stateless.co/hal_specification.html">HAL</a>, <a href="http://www.amundsen.com/media-types/collection/">Collection+JSON</a>, <a href="http://jsonapi.org/">JSON API</a> or HTML <a href="http://microformats.org/wiki/Main_Page">microformats</a> by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.</p>

View File

@ -373,21 +373,21 @@
<h1 id="third-party-resources">Third Party Resources</h1>
<h1 id="third-party-resources"><a class="toclink" href="#third-party-resources">Third Party Resources</a></h1>
<blockquote>
<p>Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.</p>
<p>&mdash; <a href="http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html">Jan Bosch</a>.</p>
</blockquote>
<h2 id="about-third-party-packages">About Third Party Packages</h2>
<h2 id="about-third-party-packages"><a class="toclink" href="#about-third-party-packages">About Third Party Packages</a></h2>
<p>Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.</p>
<p>We <strong>support</strong>, <strong>encourage</strong> and <strong>strongly favor</strong> the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.</p>
<p>We aim to make creating third party packages as easy as possible, whilst keeping a <strong>simple</strong> and <strong>well maintained</strong> core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.</p>
<p>If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the <a href="https://groups.google.com/forum/#!forum/django-rest-framework">Mailing List</a>.</p>
<h2 id="how-to-create-a-third-party-package">How to create a Third Party Package</h2>
<h3 id="creating-your-package">Creating your package</h3>
<h2 id="how-to-create-a-third-party-package"><a class="toclink" href="#how-to-create-a-third-party-package">How to create a Third Party Package</a></h2>
<h3 id="creating-your-package"><a class="toclink" href="#creating-your-package">Creating your package</a></h3>
<p>You can use <a href="https://github.com/jpadilla/cookiecutter-django-rest-framework">this cookiecutter template</a> for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.</p>
<p>Note: Let us know if you have an alternate cookiecuter package so we can also link to it.</p>
<h4 id="running-the-initial-cookiecutter-command">Running the initial cookiecutter command</h4>
<h4 id="running-the-initial-cookiecutter-command"><a class="toclink" href="#running-the-initial-cookiecutter-command">Running the initial cookiecutter command</a></h4>
<p>To run the initial cookiecutter command, you'll first need to install the Python <code>cookiecutter</code> package.</p>
<pre><code>$ pip install cookiecutter
</code></pre>
@ -405,13 +405,13 @@ project_short_description (default is "Your project description goes here")?
year (default is "2014")?
version (default is "0.1.0")?
</code></pre>
<h4 id="getting-it-onto-github">Getting it onto GitHub</h4>
<h4 id="getting-it-onto-github"><a class="toclink" href="#getting-it-onto-github">Getting it onto GitHub</a></h4>
<p>To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository <a href="https://github.com/new">here</a>. If you need help, check out the <a href="https://help.github.com/articles/create-a-repo/">Create A Repo</a> article on GitHub.</p>
<h4 id="adding-to-travis-ci">Adding to Travis CI</h4>
<h4 id="adding-to-travis-ci"><a class="toclink" href="#adding-to-travis-ci">Adding to Travis CI</a></h4>
<p>We recommend using <a href="https://travis-ci.org">Travis CI</a>, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.</p>
<p>To get started with Travis CI, <a href="https://travis-ci.org">sign in</a> with your GitHub account. Once you're signed in, go to your <a href="https://travis-ci.org/profile">profile page</a> and enable the service hook for the repository you want.</p>
<p>If you use the cookiecutter template, your project will already contain a <code>.travis.yml</code> file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.</p>
<h4 id="uploading-to-pypi">Uploading to PyPI</h4>
<h4 id="uploading-to-pypi"><a class="toclink" href="#uploading-to-pypi">Uploading to PyPI</a></h4>
<p>Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via <code>pip</code>.</p>
<p>You must <a href="https://pypi.python.org/pypi?%3Aaction=register_form">register</a> an account before publishing to PyPI.</p>
<p>To register your package on PyPI run the following command.</p>
@ -430,10 +430,10 @@ You probably want to also tag the version now:
</code></pre>
<p>After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.</p>
<p>We recommend to follow <a href="http://semver.org/">Semantic Versioning</a> for your package's versions.</p>
<h3 id="development">Development</h3>
<h4 id="version-requirements">Version requirements</h4>
<h3 id="development"><a class="toclink" href="#development">Development</a></h3>
<h4 id="version-requirements"><a class="toclink" href="#version-requirements">Version requirements</a></h4>
<p>The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, <code>tox.ini</code>, <code>.travis.yml</code>, and <code>setup.py</code> to match the set of versions you wish to support.</p>
<h4 id="tests">Tests</h4>
<h4 id="tests"><a class="toclink" href="#tests">Tests</a></h4>
<p>The cookiecutter template includes a <code>runtests.py</code> which uses the <code>pytest</code> package as a test runner.</p>
<p>Before running, you'll need to install a couple test requirements.</p>
<pre><code>$ pip install -r requirements.txt
@ -475,22 +475,22 @@ You probably want to also tag the version now:
<p><code>envlist</code> is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:</p>
<pre><code>$ tox -l
</code></pre>
<h4 id="version-compatibility">Version compatibility</h4>
<h4 id="version-compatibility"><a class="toclink" href="#version-compatibility">Version compatibility</a></h4>
<p>Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a <code>compat.py</code> module, and should provide a single common interface that the rest of the codebase can use.</p>
<p>Check out Django REST framework's <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/compat.py">compat.py</a> for an example.</p>
<h3 id="once-your-package-is-available">Once your package is available</h3>
<h3 id="once-your-package-is-available"><a class="toclink" href="#once-your-package-is-available">Once your package is available</a></h3>
<p>Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.</p>
<h4 id="adding-to-the-django-rest-framework-grid">Adding to the Django REST framework grid</h4>
<h4 id="adding-to-the-django-rest-framework-grid"><a class="toclink" href="#adding-to-the-django-rest-framework-grid">Adding to the Django REST framework grid</a></h4>
<p>We suggest adding your package to the <a href="https://www.djangopackages.com/grids/g/django-rest-framework/">REST Framework</a> grid on Django Packages.</p>
<h4 id="adding-to-the-django-rest-framework-docs">Adding to the Django REST framework docs</h4>
<h4 id="adding-to-the-django-rest-framework-docs"><a class="toclink" href="#adding-to-the-django-rest-framework-docs">Adding to the Django REST framework docs</a></h4>
<p>Create a <a href="https://github.com/tomchristie/django-rest-framework/compare">Pull Request</a> or <a href="https://github.com/tomchristie/django-rest-framework/issues/new">Issue</a> on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under <strong>Third party packages</strong> of the API Guide section that best applies, like <a href="../../api-guide/authentication/">Authentication</a> or <a href="../../api-guide/permissions/">Permissions</a>. You can also link your package under the <a href="../../topics/third-party-resources/#existing-third-party-packages">Third Party Resources</a> section.</p>
<h4 id="announce-on-the-discussion-group">Announce on the discussion group.</h4>
<h4 id="announce-on-the-discussion-group"><a class="toclink" href="#announce-on-the-discussion-group">Announce on the discussion group.</a></h4>
<p>You can also let others know about your package through the <a href="https://groups.google.com/forum/#!forum/django-rest-framework">discussion group</a>.</p>
<h2 id="existing-third-party-packages">Existing Third Party Packages</h2>
<h2 id="existing-third-party-packages"><a class="toclink" href="#existing-third-party-packages">Existing Third Party Packages</a></h2>
<p>Django REST Framework has a growing community of developers, packages, and resources.</p>
<p>Check out a grid detailing all the packages and ecosystem around Django REST Framework at <a href="https://www.djangopackages.com/grids/g/django-rest-framework/">Django Packages</a>.</p>
<p>To submit new content, <a href="https://github.com/tomchristie/django-rest-framework/issues/new">open an issue</a> or <a href="https://github.com/tomchristie/django-rest-framework/compare">create a pull request</a>.</p>
<h3 id="authentication">Authentication</h3>
<h3 id="authentication"><a class="toclink" href="#authentication">Authentication</a></h3>
<ul>
<li><a href="https://github.com/juanriaza/django-rest-framework-digestauth">djangorestframework-digestauth</a> - Provides Digest Access Authentication support.</li>
<li><a href="https://github.com/evonove/django-oauth-toolkit">django-oauth-toolkit</a> - Provides OAuth 2.0 support.</li>
@ -501,52 +501,52 @@ You probably want to also tag the version now:
<li><a href="https://github.com/sunscrapers/djoser">djoser</a> - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.</li>
<li><a href="https://github.com/Tivix/django-rest-auth/">django-rest-auth</a> - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.</li>
</ul>
<h3 id="permissions">Permissions</h3>
<h3 id="permissions"><a class="toclink" href="#permissions">Permissions</a></h3>
<ul>
<li><a href="https://github.com/kevin-brown/drf-any-permissions">drf-any-permissions</a> - Provides alternative permission handling.</li>
<li><a href="https://github.com/niwibe/djangorestframework-composed-permissions">djangorestframework-composed-permissions</a> - Provides a simple way to define complex permissions.</li>
<li><a href="https://github.com/caxap/rest_condition">rest_condition</a> - Another extension for building complex permissions in a simple and convenient way.</li>
<li><a href="https://github.com/Helioscene/dry-rest-permissions">dry-rest-permissions</a> - Provides a simple way to define permissions for individual api actions.</li>
</ul>
<h3 id="serializers">Serializers</h3>
<h3 id="serializers"><a class="toclink" href="#serializers">Serializers</a></h3>
<ul>
<li><a href="https://github.com/umutbozkurt/django-rest-framework-mongoengine">django-rest-framework-mongoengine</a> - Serializer class that supports using MongoDB as the storage layer for Django REST framework.</li>
<li><a href="https://github.com/djangonauts/django-rest-framework-gis">djangorestframework-gis</a> - Geographic add-ons</li>
<li><a href="https://github.com/djangonauts/django-rest-framework-hstore">djangorestframework-hstore</a> - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.</li>
</ul>
<h3 id="serializer-fields">Serializer fields</h3>
<h3 id="serializer-fields"><a class="toclink" href="#serializer-fields">Serializer fields</a></h3>
<ul>
<li><a href="https://github.com/estebistec/drf-compound-fields">drf-compound-fields</a> - Provides "compound" serializer fields, such as lists of simple values.</li>
<li><a href="https://github.com/Hipo/drf-extra-fields">django-extra-fields</a> - Provides extra serializer fields.</li>
<li><a href="https://github.com/WGBH/django-versatileimagefield">django-versatileimagefield</a> - Provides a drop-in replacement for Django's stock <code>ImageField</code> that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, <a href="http://django-versatileimagefield.readthedocs.org/en/latest/drf_integration.html">click here</a>.</li>
</ul>
<h3 id="views">Views</h3>
<h3 id="views"><a class="toclink" href="#views">Views</a></h3>
<ul>
<li><a href="https://github.com/miki725/django-rest-framework-bulk">djangorestframework-bulk</a> - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.</li>
<li><a href="https://github.com/Axiologue/DjangoRestMultipleModels">django-rest-multiple-models</a> - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.</li>
</ul>
<h3 id="routers">Routers</h3>
<h3 id="routers"><a class="toclink" href="#routers">Routers</a></h3>
<ul>
<li><a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers</a> - Provides routers and relationship fields for working with nested resources.</li>
<li><a href="http://wq.io/docs/about-rest">wq.db.rest</a> - Provides an admin-style model registration API with reasonable default URLs and viewsets.</li>
</ul>
<h3 id="parsers">Parsers</h3>
<h3 id="parsers"><a class="toclink" href="#parsers">Parsers</a></h3>
<ul>
<li><a href="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> - Provides MessagePack renderer and parser support.</li>
<li><a href="https://github.com/vbabiy/djangorestframework-camel-case">djangorestframework-camel-case</a> - Provides camel case JSON renderers and parsers.</li>
</ul>
<h3 id="renderers">Renderers</h3>
<h3 id="renderers"><a class="toclink" href="#renderers">Renderers</a></h3>
<ul>
<li><a href="https://github.com/mjumbewu/django-rest-framework-csv">djangorestframework-csv</a> - Provides CSV renderer support.</li>
<li><a href="https://github.com/gizmag/drf-ujson-renderer">drf_ujson</a> - Implements JSON rendering using the UJSON package.</li>
<li><a href="https://github.com/wq/django-rest-pandas">rest-pandas</a> - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.</li>
</ul>
<h3 id="filtering">Filtering</h3>
<h3 id="filtering"><a class="toclink" href="#filtering">Filtering</a></h3>
<ul>
<li><a href="https://github.com/philipn/django-rest-framework-chain">djangorestframework-chain</a> - Allows arbitrary chaining of both relations and lookup filters.</li>
<li><a href="https://github.com/miki725/django-url-filter">django-url-filter</a> - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.</li>
</ul>
<h3 id="misc">Misc</h3>
<h3 id="misc"><a class="toclink" href="#misc">Misc</a></h3>
<ul>
<li><a href="https://github.com/agconti/cookiecutter-django-rest">cookiecutter-django-rest</a> - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.</li>
<li><a href="https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project">djangorestrelationalhyperlink</a> - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.</li>
@ -559,9 +559,10 @@ You probably want to also tag the version now:
<li><a href="https://github.com/aschn/drf-tracking">drf-tracking</a> - Utilities to track requests to DRF API views.</li>
<li><a href="https://github.com/dealertrack/django-rest-framework-braces">django-rest-framework-braces</a> - Collection of utilities for working with Django Rest Framework. The most notable ones are <a href="https://django-rest-framework-braces.readthedocs.org/en/latest/overview.html#formserializer">FormSerializer</a> and <a href="https://django-rest-framework-braces.readthedocs.org/en/latest/overview.html#serializerform">SerializerForm</a>, which are adapters between DRF serializers and Django forms.</li>
<li><a href="http://drf-haystack.readthedocs.org/en/latest/">drf-haystack</a> - Haystack search for Django Rest Framework</li>
<li><a href="https://github.com/mrhwick/django-rest-framework-version-transforms">django-rest-framework-version-transforms</a> - Enables the use of delta transformations for versioning of DRF resource representations.</li>
</ul>
<h2 id="other-resources">Other Resources</h2>
<h3 id="tutorials">Tutorials</h3>
<h2 id="other-resources"><a class="toclink" href="#other-resources">Other Resources</a></h2>
<h3 id="tutorials"><a class="toclink" href="#tutorials">Tutorials</a></h3>
<ul>
<li><a href="http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786">Beginner's Guide to the Django Rest Framework</a></li>
<li><a href="http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html">Getting Started with Django Rest Framework and AngularJS</a></li>
@ -572,19 +573,19 @@ You probably want to also tag the version now:
<li><a href="http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/">Django Rest Framework User Endpoint</a></li>
<li><a href="http://richardtier.com/2014/03/06/110/">Check credentials using Django Rest Framework</a></li>
</ul>
<h3 id="videos">Videos</h3>
<h3 id="videos"><a class="toclink" href="#videos">Videos</a></h3>
<ul>
<li><a href="http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1">Ember and Django Part 1 (Video)</a></li>
<li><a href="http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1">Django Rest Framework Part 1 (Video)</a></li>
<li><a href="http://www.youtube.com/watch?v=e1zrehvxpbo">Pyowa July 2013 - Django Rest Framework (Video)</a></li>
<li><a href="http://www.youtube.com/watch?v=q8frbgtj020">django-rest-framework and angularjs (Video)</a></li>
</ul>
<h3 id="articles">Articles</h3>
<h3 id="articles"><a class="toclink" href="#articles">Articles</a></h3>
<ul>
<li><a href="http://dabapps.com/blog/api-performance-profiling-django-rest-framework/">Web API performance: profiling Django REST framework</a></li>
<li><a href="https://bnotions.com/api-development-with-django-and-django-rest-framework/">API Development with Django and Django REST Framework</a></li>
</ul>
<h3 id="documentations">Documentations</h3>
<h3 id="documentations"><a class="toclink" href="#documentations">Documentations</a></h3>
<ul>
<li><a href="http://www.cdrf.co">Classy Django REST Framework</a></li>
</ul>

View File

@ -397,14 +397,14 @@
<h1 id="tutorial-1-serialization">Tutorial 1: Serialization</h1>
<h2 id="introduction">Introduction</h2>
<h1 id="tutorial-1-serialization"><a class="toclink" href="#tutorial-1-serialization">Tutorial 1: Serialization</a></h1>
<h2 id="introduction"><a class="toclink" href="#introduction">Introduction</a></h2>
<p>This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.</p>
<p>The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the <a href="../quickstart/">quickstart</a> documentation instead.</p>
<hr />
<p><strong>Note</strong>: The code for this tutorial is available in the <a href="https://github.com/tomchristie/rest-framework-tutorial">tomchristie/rest-framework-tutorial</a> repository on GitHub. The completed implementation is also online as a sandbox version for testing, <a href="http://restframework.herokuapp.com/">available here</a>.</p>
<hr />
<h2 id="setting-up-a-new-environment">Setting up a new environment</h2>
<h2 id="setting-up-a-new-environment"><a class="toclink" href="#setting-up-a-new-environment">Setting up a new environment</a></h2>
<p>Before we do anything else we'll create a new virtual environment, using <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv</a>. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.</p>
<pre><code>virtualenv env
source env/bin/activate
@ -415,7 +415,7 @@ pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
</code></pre>
<p><strong>Note:</strong> To exit the virtualenv environment at any time, just type <code>deactivate</code>. For more information see the <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv documentation</a>.</p>
<h2 id="getting-started">Getting started</h2>
<h2 id="getting-started"><a class="toclink" href="#getting-started">Getting started</a></h2>
<p>Okay, we're ready to get coding.
To get started, let's create a new project to work with.</p>
<pre><code>cd ~
@ -438,7 +438,7 @@ cd tutorial
]
</code></pre>
<p>Okay, we're ready to roll.</p>
<h2 id="creating-a-model-to-work-with">Creating a model to work with</h2>
<h2 id="creating-a-model-to-work-with"><a class="toclink" href="#creating-a-model-to-work-with">Creating a model to work with</a></h2>
<p>For the purposes of this tutorial we're going to start by creating a simple <code>Snippet</code> model that is used to store code snippets. Go ahead and edit the <code>snippets/models.py</code> file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.</p>
<pre><code>from django.db import models
from pygments.lexers import get_all_lexers
@ -464,7 +464,7 @@ class Snippet(models.Model):
<pre><code>python manage.py makemigrations snippets
python manage.py migrate
</code></pre>
<h2 id="creating-a-serializer-class">Creating a Serializer class</h2>
<h2 id="creating-a-serializer-class"><a class="toclink" href="#creating-a-serializer-class">Creating a Serializer class</a></h2>
<p>The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as <code>json</code>. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the <code>snippets</code> directory named <code>serializers.py</code> and add the following.</p>
<pre><code>from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
@ -500,7 +500,7 @@ class SnippetSerializer(serializers.Serializer):
<p>A serializer class is very similar to a Django <code>Form</code> class, and includes similar validation flags on the various fields, such as <code>required</code>, <code>max_length</code> and <code>default</code>.</p>
<p>The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The <code>{'base_template': 'textarea.html'}</code> flag above is equivalent to using <code>widget=widgets.Textarea</code> on a Django <code>Form</code> class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.</p>
<p>We can actually also save ourselves some time by using the <code>ModelSerializer</code> class, as we'll see later, but for now we'll keep our serializer definition explicit.</p>
<h2 id="working-with-serializers">Working with Serializers</h2>
<h2 id="working-with-serializers"><a class="toclink" href="#working-with-serializers">Working with Serializers</a></h2>
<p>Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.</p>
<pre><code>python manage.py shell
</code></pre>
@ -547,7 +547,7 @@ serializer.save()
serializer.data
# [OrderedDict([('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
</code></pre>
<h2 id="using-modelserializers">Using ModelSerializers</h2>
<h2 id="using-modelserializers"><a class="toclink" href="#using-modelserializers">Using ModelSerializers</a></h2>
<p>Our <code>SnippetSerializer</code> class is replicating a lot of information that's also contained in the <code>Snippet</code> model. It would be nice if we could keep our code a bit more concise.</p>
<p>In the same way that Django provides both <code>Form</code> classes and <code>ModelForm</code> classes, REST framework includes both <code>Serializer</code> classes, and <code>ModelSerializer</code> classes.</p>
<p>Let's look at refactoring our serializer using the <code>ModelSerializer</code> class.
@ -574,7 +574,7 @@ SnippetSerializer():
<li>An automatically determined set of fields.</li>
<li>Simple default implementations for the <code>create()</code> and <code>update()</code> methods.</li>
</ul>
<h2 id="writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</h2>
<h2 id="writing-regular-django-views-using-our-serializer"><a class="toclink" href="#writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</a></h2>
<p>Let's see how we can write some API views using our new Serializer class.
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.</p>
<p>We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into <code>json</code>.</p>
@ -652,7 +652,7 @@ urlpatterns = [
]
</code></pre>
<p>It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed <code>json</code>, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.</p>
<h2 id="testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</h2>
<h2 id="testing-our-first-attempt-at-a-web-api"><a class="toclink" href="#testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</a></h2>
<p>Now we can start up a sample server that serves our snippets.</p>
<p>Quit out of the shell...</p>
<pre><code>quit()
@ -711,7 +711,7 @@ HTTP/1.1 200 OK
}
</code></pre>
<p>Similarly, you can have the same json displayed by visiting these URLs in a web browser.</p>
<h2 id="where-are-we-now">Where are we now</h2>
<h2 id="where-are-we-now"><a class="toclink" href="#where-are-we-now">Where are we now</a></h2>
<p>We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.</p>
<p>Our API views don't do anything particularly special at the moment, beyond serving <code>json</code> responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.</p>
<p>We'll see how we can start to improve things in <a href="../2-requests-and-responses/">part 2 of the tutorial</a>.</p>

View File

@ -389,21 +389,21 @@
<h1 id="tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</h1>
<h1 id="tutorial-2-requests-and-responses"><a class="toclink" href="#tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</a></h1>
<p>From this point we're going to really start covering the core of REST framework.
Let's introduce a couple of essential building blocks.</p>
<h2 id="request-objects">Request objects</h2>
<h2 id="request-objects"><a class="toclink" href="#request-objects">Request objects</a></h2>
<p>REST framework introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing. The core functionality of the <code>Request</code> object is the <code>request.data</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p>
<pre><code>request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
</code></pre>
<h2 id="response-objects">Response objects</h2>
<h2 id="response-objects"><a class="toclink" href="#response-objects">Response objects</a></h2>
<p>REST framework also introduces a <code>Response</code> object, which is a type of <code>TemplateResponse</code> that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.</p>
<pre><code>return Response(data) # Renders to content type as requested by the client.
</code></pre>
<h2 id="status-codes">Status codes</h2>
<h2 id="status-codes"><a class="toclink" href="#status-codes">Status codes</a></h2>
<p>Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as <code>HTTP_400_BAD_REQUEST</code> in the <code>status</code> module. It's a good idea to use these throughout rather than using numeric identifiers.</p>
<h2 id="wrapping-api-views">Wrapping API views</h2>
<h2 id="wrapping-api-views"><a class="toclink" href="#wrapping-api-views">Wrapping API views</a></h2>
<p>REST framework provides two wrappers you can use to write API views.</p>
<ol>
<li>The <code>@api_view</code> decorator for working with function based views.</li>
@ -411,7 +411,7 @@ request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' met
</ol>
<p>These wrappers provide a few bits of functionality such as making sure you receive <code>Request</code> instances in your view, and adding context to <code>Response</code> objects so that content negotiation can be performed.</p>
<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> exception that occurs when accessing <code>request.data</code> with malformed input.</p>
<h2 id="pulling-it-all-together">Pulling it all together</h2>
<h2 id="pulling-it-all-together"><a class="toclink" href="#pulling-it-all-together">Pulling it all together</a></h2>
<p>Okay, let's go ahead and start using these new components to write a few views.</p>
<p>We don't need our <code>JSONResponse</code> class in <code>views.py</code> anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.</p>
<pre><code>from rest_framework import status
@ -467,7 +467,7 @@ def snippet_detail(request, pk):
</code></pre>
<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p>
<p>Notice that we're no longer explicitly tying our requests or responses to a given content type. <code>request.data</code> can handle incoming <code>json</code> requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.</p>
<h2 id="adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</h2>
<h2 id="adding-optional-format-suffixes-to-our-urls"><a class="toclink" href="#adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</a></h2>
<p>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as <a href="http://example.com/api/items/4/.json">http://example.com/api/items/4/.json</a>.</p>
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p>
<pre><code>def snippet_list(request, format=None):
@ -488,7 +488,7 @@ urlpatterns = [
urlpatterns = format_suffix_patterns(urlpatterns)
</code></pre>
<p>We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.</p>
<h2 id="hows-it-looking">How's it looking?</h2>
<h2 id="hows-it-looking"><a class="toclink" href="#hows-it-looking">How's it looking?</a></h2>
<p>Go ahead and test the API from the command line, as we did in <a href="../1-serialization/">tutorial part 1</a>. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.</p>
<p>We can get a list of all of the snippets, as before.</p>
<pre><code>http http://127.0.0.1:8000/snippets/
@ -548,11 +548,11 @@ http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
}
</code></pre>
<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a>.</p>
<h3 id="browsability">Browsability</h3>
<h3 id="browsability"><a class="toclink" href="#browsability">Browsability</a></h3>
<p>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.</p>
<p>Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.</p>
<p>See the <a href="../../topics/browsable-api/">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p>
<h2 id="whats-next">What's next?</h2>
<h2 id="whats-next"><a class="toclink" href="#whats-next">What's next?</a></h2>
<p>In <a href="../3-class-based-views/">tutorial part 3</a>, we'll start using class based views, and see how generic views reduce the amount of code we need to write.</p>

View File

@ -369,9 +369,9 @@
<h1 id="tutorial-3-class-based-views">Tutorial 3: Class Based Views</h1>
<h1 id="tutorial-3-class-based-views"><a class="toclink" href="#tutorial-3-class-based-views">Tutorial 3: Class Based Views</a></h1>
<p>We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p>
<h2 id="rewriting-our-api-using-class-based-views">Rewriting our API using class based views</h2>
<h2 id="rewriting-our-api-using-class-based-views"><a class="toclink" href="#rewriting-our-api-using-class-based-views">Rewriting our API using class based views</a></h2>
<p>We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring of <code>views.py</code>.</p>
<pre><code>from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@ -440,7 +440,7 @@ urlpatterns = [
urlpatterns = format_suffix_patterns(urlpatterns)
</code></pre>
<p>Okay, we're done. If you run the development server everything should be working just as before.</p>
<h2 id="using-mixins">Using mixins</h2>
<h2 id="using-mixins"><a class="toclink" href="#using-mixins">Using mixins</a></h2>
<p>One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.</p>
<p>The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.</p>
<p>Let's take a look at how we can compose the views by using the mixin classes. Here's our <code>views.py</code> module again.</p>
@ -480,7 +480,7 @@ class SnippetList(mixins.ListModelMixin,
return self.destroy(request, *args, **kwargs)
</code></pre>
<p>Pretty similar. Again we're using the <code>GenericAPIView</code> class to provide the core functionality, and adding in mixins to provide the <code>.retrieve()</code>, <code>.update()</code> and <code>.destroy()</code> actions.</p>
<h2 id="using-generic-class-based-views">Using generic class based views</h2>
<h2 id="using-generic-class-based-views"><a class="toclink" href="#using-generic-class-based-views">Using generic class based views</a></h2>
<p>Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our <code>views.py</code> module even more.</p>
<pre><code>from snippets.models import Snippet
from snippets.serializers import SnippetSerializer

View File

@ -393,7 +393,7 @@
<h1 id="tutorial-4-authentication-permissions">Tutorial 4: Authentication &amp; Permissions</h1>
<h1 id="tutorial-4-authentication-permissions"><a class="toclink" href="#tutorial-4-authentication-permissions">Tutorial 4: Authentication &amp; Permissions</a></h1>
<p>Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:</p>
<ul>
<li>Code snippets are always associated with a creator.</li>
@ -401,7 +401,7 @@
<li>Only the creator of a snippet may update or delete it.</li>
<li>Unauthenticated requests should have full read-only access.</li>
</ul>
<h2 id="adding-information-to-our-model">Adding information to our model</h2>
<h2 id="adding-information-to-our-model"><a class="toclink" href="#adding-information-to-our-model">Adding information to our model</a></h2>
<p>We're going to make a couple of changes to our <code>Snippet</code> model class.
First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.</p>
<p>Add the following two fields to the <code>Snippet</code> model in <code>models.py</code>.</p>
@ -438,7 +438,7 @@ python manage.py migrate
<p>You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the <code>createsuperuser</code> command.</p>
<pre><code>python manage.py createsuperuser
</code></pre>
<h2 id="adding-endpoints-for-our-user-models">Adding endpoints for our User models</h2>
<h2 id="adding-endpoints-for-our-user-models"><a class="toclink" href="#adding-endpoints-for-our-user-models">Adding endpoints for our User models</a></h2>
<p>Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In <code>serializers.py</code> add:</p>
<pre><code>from django.contrib.auth.models import User
@ -470,7 +470,7 @@ class UserDetail(generics.RetrieveAPIView):
<pre><code>url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P&lt;pk&gt;[0-9]+)/$', views.UserDetail.as_view()),
</code></pre>
<h2 id="associating-snippets-with-users">Associating Snippets with Users</h2>
<h2 id="associating-snippets-with-users"><a class="toclink" href="#associating-snippets-with-users">Associating Snippets with Users</a></h2>
<p>Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.</p>
<p>The way we deal with that is by overriding a <code>.perform_create()</code> method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.</p>
<p>On the <code>SnippetList</code> view class, add the following method:</p>
@ -478,14 +478,14 @@ url(r'^users/(?P&lt;pk&gt;[0-9]+)/$', views.UserDetail.as_view()),
serializer.save(owner=self.request.user)
</code></pre>
<p>The <code>create()</code> method of our serializer will now be passed an additional <code>'owner'</code> field, along with the validated data from the request.</p>
<h2 id="updating-our-serializer">Updating our serializer</h2>
<h2 id="updating-our-serializer"><a class="toclink" href="#updating-our-serializer">Updating our serializer</a></h2>
<p>Now that snippets are associated with the user that created them, let's update our <code>SnippetSerializer</code> to reflect that. Add the following field to the serializer definition in <code>serializers.py</code>:</p>
<pre><code>owner = serializers.ReadOnlyField(source='owner.username')
</code></pre>
<p><strong>Note</strong>: Make sure you also add <code>'owner',</code> to the list of fields in the inner <code>Meta</code> class.</p>
<p>This field is doing something quite interesting. The <code>source</code> argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.</p>
<p>The field we've added is the untyped <code>ReadOnlyField</code> class, in contrast to the other typed fields, such as <code>CharField</code>, <code>BooleanField</code> etc... The untyped <code>ReadOnlyField</code> is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used <code>CharField(read_only=True)</code> here.</p>
<h2 id="adding-required-permissions-to-views">Adding required permissions to views</h2>
<h2 id="adding-required-permissions-to-views"><a class="toclink" href="#adding-required-permissions-to-views">Adding required permissions to views</a></h2>
<p>Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.</p>
<p>REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is <code>IsAuthenticatedOrReadOnly</code>, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.</p>
<p>First add the following import in the views module</p>
@ -494,7 +494,7 @@ url(r'^users/(?P&lt;pk&gt;[0-9]+)/$', views.UserDetail.as_view()),
<p>Then, add the following property to <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes.</p>
<pre><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
</code></pre>
<h2 id="adding-login-to-the-browsable-api">Adding login to the Browsable API</h2>
<h2 id="adding-login-to-the-browsable-api"><a class="toclink" href="#adding-login-to-the-browsable-api">Adding login to the Browsable API</a></h2>
<p>If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.</p>
<p>We can add a login view for use with the browsable API, by editing the URLconf in our project-level <code>urls.py</code> file.</p>
<p>Add the following import at the top of the file:</p>
@ -509,7 +509,7 @@ url(r'^users/(?P&lt;pk&gt;[0-9]+)/$', views.UserDetail.as_view()),
<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p>
<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p>
<p>Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.</p>
<h2 id="object-level-permissions">Object level permissions</h2>
<h2 id="object-level-permissions"><a class="toclink" href="#object-level-permissions">Object level permissions</a></h2>
<p>Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.</p>
<p>To do that we're going to need to create a custom permission.</p>
<p>In the snippets app, create a new file, <code>permissions.py</code></p>
@ -538,7 +538,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
<pre><code>from snippets.permissions import IsOwnerOrReadOnly
</code></pre>
<p>Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.</p>
<h2 id="authenticating-with-the-api">Authenticating with the API</h2>
<h2 id="authenticating-with-the-api"><a class="toclink" href="#authenticating-with-the-api">Authenticating with the API</a></h2>
<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any <a href="../../api-guide/authentication/">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p>
<p>When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.</p>
<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p>
@ -562,7 +562,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
"style": "friendly"
}
</code></pre>
<h2 id="summary">Summary</h2>
<h2 id="summary"><a class="toclink" href="#summary">Summary</a></h2>
<p>We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.</p>
<p>In <a href="../5-relationships-and-hyperlinked-apis/">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</p>

View File

@ -381,9 +381,9 @@
<h1 id="tutorial-5-relationships-hyperlinked-apis">Tutorial 5: Relationships &amp; Hyperlinked APIs</h1>
<h1 id="tutorial-5-relationships-hyperlinked-apis"><a class="toclink" href="#tutorial-5-relationships-hyperlinked-apis">Tutorial 5: Relationships &amp; Hyperlinked APIs</a></h1>
<p>At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.</p>
<h2 id="creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</h2>
<h2 id="creating-an-endpoint-for-the-root-of-our-api"><a class="toclink" href="#creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</a></h2>
<p>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the <code>@api_view</code> decorator we introduced earlier. In your <code>snippets/views.py</code> add:</p>
<pre><code>from rest_framework.decorators import api_view
from rest_framework.response import Response
@ -398,7 +398,7 @@ def api_root(request, format=None):
})
</code></pre>
<p>Two things should be noticed here. First, we're using REST framework's <code>reverse</code> function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our <code>snippets/urls.py</code>. </p>
<h2 id="creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</h2>
<h2 id="creating-an-endpoint-for-the-highlighted-snippets"><a class="toclink" href="#creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</a></h2>
<p>The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.</p>
<p>Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.</p>
<p>The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.</p>
@ -421,7 +421,7 @@ We'll add a url pattern for our new API root in <code>snippets/urls.py</code>:</
<p>And then add a url pattern for the snippet highlights:</p>
<pre><code>url(r'^snippets/(?P&lt;pk&gt;[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
</code></pre>
<h2 id="hyperlinking-our-api">Hyperlinking our API</h2>
<h2 id="hyperlinking-our-api"><a class="toclink" href="#hyperlinking-our-api">Hyperlinking our API</a></h2>
<p>Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:</p>
<ul>
<li>Using primary keys.</li>
@ -460,7 +460,7 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
</code></pre>
<p>Notice that we've also added a new <code>'highlight'</code> field. This field is of the same type as the <code>url</code> field, except that it points to the <code>'snippet-highlight'</code> url pattern, instead of the <code>'snippet-detail'</code> url pattern.</p>
<p>Because we've included format suffixed URLs such as <code>'.json'</code>, we also need to indicate on the <code>highlight</code> field that any format suffixed hyperlinks it returns should use the <code>'.html'</code> suffix.</p>
<h2 id="making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</h2>
<h2 id="making-sure-our-url-patterns-are-named"><a class="toclink" href="#making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</a></h2>
<p>If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.</p>
<ul>
<li>The root of our API refers to <code>'user-list'</code> and <code>'snippet-list'</code>.</li>
@ -499,7 +499,7 @@ urlpatterns += [
namespace='rest_framework')),
]
</code></pre>
<h2 id="adding-pagination">Adding pagination</h2>
<h2 id="adding-pagination"><a class="toclink" href="#adding-pagination">Adding pagination</a></h2>
<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p>
<p>We can change the default list style to use pagination, by modifying our <code>tutorial/settings.py</code> file slightly. Add the following setting:</p>
<pre><code>REST_FRAMEWORK = {
@ -508,7 +508,7 @@ urlpatterns += [
</code></pre>
<p>Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.</p>
<p>We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.</p>
<h2 id="browsing-the-api">Browsing the API</h2>
<h2 id="browsing-the-api"><a class="toclink" href="#browsing-the-api">Browsing the API</a></h2>
<p>If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.</p>
<p>You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.</p>
<p>In <a href="../6-viewsets-and-routers/">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</p>

View File

@ -381,11 +381,11 @@
<h1 id="tutorial-6-viewsets-routers">Tutorial 6: ViewSets &amp; Routers</h1>
<h1 id="tutorial-6-viewsets-routers"><a class="toclink" href="#tutorial-6-viewsets-routers">Tutorial 6: ViewSets &amp; Routers</a></h1>
<p>REST framework includes an abstraction for dealing with <code>ViewSets</code>, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.</p>
<p><code>ViewSet</code> classes are almost the same thing as <code>View</code> classes, except that they provide operations such as <code>read</code>, or <code>update</code>, and not method handlers such as <code>get</code> or <code>put</code>.</p>
<p>A <code>ViewSet</code> class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a <code>Router</code> class which handles the complexities of defining the URL conf for you.</p>
<h2 id="refactoring-to-use-viewsets">Refactoring to use ViewSets</h2>
<h2 id="refactoring-to-use-viewsets"><a class="toclink" href="#refactoring-to-use-viewsets">Refactoring to use ViewSets</a></h2>
<p>Let's take our current set of views, and refactor them into view sets.</p>
<p>First of all let's refactor our <code>UserList</code> and <code>UserDetail</code> views into a single <code>UserViewSet</code>. We can remove the two views, and replace them with a single class:</p>
<pre><code>from rest_framework import viewsets
@ -425,7 +425,7 @@ class SnippetViewSet(viewsets.ModelViewSet):
<p>Notice that we've also used the <code>@detail_route</code> decorator to create a custom action, named <code>highlight</code>. This decorator can be used to add any custom endpoints that don't fit into the standard <code>create</code>/<code>update</code>/<code>delete</code> style.</p>
<p>Custom actions which use the <code>@detail_route</code> decorator will respond to <code>GET</code> requests. We can use the <code>methods</code> argument if we wanted an action that responded to <code>POST</code> requests.</p>
<p>The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.</p>
<h2 id="binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</h2>
<h2 id="binding-viewsets-to-urls-explicitly"><a class="toclink" href="#binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</a></h2>
<p>The handler methods only get bound to the actions when we define the URLConf.
To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.</p>
<p>In the <code>urls.py</code> file we bind our <code>ViewSet</code> classes into a set of concrete views.</p>
@ -463,7 +463,7 @@ user_detail = UserViewSet.as_view({
url(r'^users/(?P&lt;pk&gt;[0-9]+)/$', user_detail, name='user-detail')
])
</code></pre>
<h2 id="using-routers">Using Routers</h2>
<h2 id="using-routers"><a class="toclink" href="#using-routers">Using Routers</a></h2>
<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class. All we need to do is register the appropriate view sets with a router, and let it do the rest.</p>
<p>Here's our re-wired <code>urls.py</code> file.</p>
<pre><code>from django.conf.urls import url, include
@ -484,14 +484,14 @@ urlpatterns = [
</code></pre>
<p>Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.</p>
<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p>
<h2 id="trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</h2>
<h2 id="trade-offs-between-views-vs-viewsets"><a class="toclink" href="#trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</a></h2>
<p>Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.</p>
<p>That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.</p>
<h2 id="reviewing-our-work">Reviewing our work</h2>
<h2 id="reviewing-our-work"><a class="toclink" href="#reviewing-our-work">Reviewing our work</a></h2>
<p>With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, and comes complete with authentication, per-object permissions, and multiple renderer formats.</p>
<p>We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.</p>
<p>You can review the final <a href="https://github.com/tomchristie/rest-framework-tutorial">tutorial code</a> on GitHub, or try out a live example in <a href="http://restframework.herokuapp.com/">the sandbox</a>.</p>
<h2 id="onwards-and-upwards">Onwards and upwards</h2>
<h2 id="onwards-and-upwards"><a class="toclink" href="#onwards-and-upwards">Onwards and upwards</a></h2>
<p>We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:</p>
<ul>
<li>Contribute on <a href="https://github.com/tomchristie/django-rest-framework">GitHub</a> by reviewing and submitting issues, and making pull requests.</li>

View File

@ -381,9 +381,9 @@
<h1 id="quickstart">Quickstart</h1>
<h1 id="quickstart"><a class="toclink" href="#quickstart">Quickstart</a></h1>
<p>We're going to create a simple API to allow admin users to view and edit the users and groups in the system.</p>
<h2 id="project-setup">Project setup</h2>
<h2 id="project-setup"><a class="toclink" href="#project-setup">Project setup</a></h2>
<p>Create a new Django project named <code>tutorial</code>, then start a new app called <code>quickstart</code>.</p>
<pre><code># Create the project directory
mkdir tutorial
@ -410,7 +410,7 @@ cd ..
<pre><code>python manage.py createsuperuser
</code></pre>
<p>Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...</p>
<h2 id="serializers">Serializers</h2>
<h2 id="serializers"><a class="toclink" href="#serializers">Serializers</a></h2>
<p>First up we're going to define some serializers. Let's create a new module named <code>tutorial/quickstart/serializers.py</code> that we'll use for our data representations.</p>
<pre><code>from django.contrib.auth.models import User, Group
from rest_framework import serializers
@ -428,7 +428,7 @@ class GroupSerializer(serializers.HyperlinkedModelSerializer):
fields = ('url', 'name')
</code></pre>
<p>Notice that we're using hyperlinked relations in this case, with <code>HyperlinkedModelSerializer</code>. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.</p>
<h2 id="views">Views</h2>
<h2 id="views"><a class="toclink" href="#views">Views</a></h2>
<p>Right, we'd better write some views then. Open <code>tutorial/quickstart/views.py</code> and get typing.</p>
<pre><code>from django.contrib.auth.models import User, Group
from rest_framework import viewsets
@ -452,7 +452,7 @@ class GroupViewSet(viewsets.ModelViewSet):
</code></pre>
<p>Rather than write multiple views we're grouping together all the common behavior into classes called <code>ViewSets</code>.</p>
<p>We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.</p>
<h2 id="urls">URLs</h2>
<h2 id="urls"><a class="toclink" href="#urls">URLs</a></h2>
<p>Okay, now let's wire up the API URLs. On to <code>tutorial/urls.py</code>...</p>
<pre><code>from django.conf.urls import url, include
from rest_framework import routers
@ -472,7 +472,7 @@ urlpatterns = [
<p>Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.</p>
<p>Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.</p>
<p>Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.</p>
<h2 id="settings">Settings</h2>
<h2 id="settings"><a class="toclink" href="#settings">Settings</a></h2>
<p>We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in <code>tutorial/settings.py</code></p>
<pre><code>INSTALLED_APPS = (
...
@ -486,7 +486,7 @@ REST_FRAMEWORK = {
</code></pre>
<p>Okay, we're done.</p>
<hr />
<h2 id="testing-our-api">Testing our API</h2>
<h2 id="testing-our-api"><a class="toclink" href="#testing-our-api">Testing our API</a></h2>
<p>We're now ready to test the API we've built. Let's fire up the server from the command line.</p>
<pre><code>python ./manage.py runserver
</code></pre>