diff --git a/api-guide/exceptions/index.html b/api-guide/exceptions/index.html index d52b3c874..4d8988cf3 100644 --- a/api-guide/exceptions/index.html +++ b/api-guide/exceptions/index.html @@ -520,52 +520,80 @@ def custom_exception_handler(exc, context):

APIException

Signature: APIException()

The base class for all exceptions raised inside an APIView class or @api_view.

-

To provide a custom exception, subclass APIException and set the .status_code and .default_detail properties on the class.

+

To provide a custom exception, subclass APIException and set the .status_code, .default_detail, and default_code attributes on the class.

For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:

from rest_framework.exceptions import APIException
 
 class ServiceUnavailable(APIException):
     status_code = 503
     default_detail = 'Service temporarily unavailable, try again later.'
+    default_code = 'service_unavailable'
+
+

Inspecting API exceptions

+

There are a number of different properties available for inspecting the status +of an API exception. You can use these to build custom exception handling +for your project.

+

The available attributes and methods are:

+ +

In most cases the error detail will be a simple item:

+
>>> print(exc.detail)
+You do not have permission to perform this action.
+>>> print(exc.get_codes())
+permission_denied
+>>> print(exc.full_details())
+{'message':'You do not have permission to perform this action.','code':'permission_denied'}
+
+

In the case of validation errors the error detail will be either a list or +dictionary of items:

+
>>> print(exc.detail)
+{"name":"This field is required.","age":"A valid integer is required."}
+>>> print(exc.get_codes())
+{"name":"required","age":"invalid"}
+>>> print(exc.get_full_details())
+{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
 

ParseError

-

Signature: ParseError(detail=None)

+

Signature: ParseError(detail=None, code=None)

Raised if the request contains malformed data when accessing request.data.

By default this exception results in a response with the HTTP status code "400 Bad Request".

AuthenticationFailed

-

Signature: AuthenticationFailed(detail=None)

+

Signature: AuthenticationFailed(detail=None, code=None)

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

NotAuthenticated

-

Signature: NotAuthenticated(detail=None)

+

Signature: NotAuthenticated(detail=None, code=None)

Raised when an unauthenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

PermissionDenied

-

Signature: PermissionDenied(detail=None)

+

Signature: PermissionDenied(detail=None, code=None)

Raised when an authenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "403 Forbidden".

NotFound

-

Signature: NotFound(detail=None)

+

Signature: NotFound(detail=None, code=None)

Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception.

By default this exception results in a response with the HTTP status code "404 Not Found".

MethodNotAllowed

-

Signature: MethodNotAllowed(method, detail=None)

+

Signature: MethodNotAllowed(method, detail=None, code=None)

Raised when an incoming request occurs that does not map to a handler method on the view.

By default this exception results in a response with the HTTP status code "405 Method Not Allowed".

NotAcceptable

-

Signature: NotAcceptable(detail=None)

+

Signature: NotAcceptable(detail=None, code=None)

Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers.

By default this exception results in a response with the HTTP status code "406 Not Acceptable".

UnsupportedMediaType

-

Signature: UnsupportedMediaType(media_type, detail=None)

+

Signature: UnsupportedMediaType(media_type, detail=None, code=None)

Raised if there are no parsers that can handle the content type of the request data when accessing request.data.

By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".

Throttled

-

Signature: Throttled(wait=None, detail=None)

+

Signature: Throttled(wait=None, detail=None, code=None)

Raised when an incoming request fails the throttling checks.

By default this exception results in a response with the HTTP status code "429 Too Many Requests".

ValidationError

-

Signature: ValidationError(detail)

+

Signature: ValidationError(detail, code=None)

The ValidationError exception is slightly different from the other APIException classes:

+

You can also control these globally using the settings HTML_SELECT_CUTOFF and HTML_SELECT_CUTOFF_TEXT.

In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the style keyword argument. For example:

assigned_to = serializers.SlugRelatedField(
    queryset=User.objects.all(),
diff --git a/api-guide/reverse/index.html b/api-guide/reverse/index.html
index 169630a34..d62960aad 100644
--- a/api-guide/reverse/index.html
+++ b/api-guide/reverse/index.html
@@ -412,7 +412,7 @@
 

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.

reverse

Signature: reverse(viewname, *args, **kwargs)

-

Has the same behavior as django.core.urlresolvers.reverse, except that it returns a fully qualified URL, using the request to determine the host and port.

+

Has the same behavior as django.urls.reverse, except that it returns a fully qualified URL, using the request to determine the host and port.

You should include the request as a keyword argument to the function, for example:

from rest_framework.reverse import reverse
 from rest_framework.views import APIView
@@ -429,7 +429,7 @@ class APIRootView(APIView):
 

reverse_lazy

Signature: reverse_lazy(viewname, *args, **kwargs)

-

Has the same behavior as django.core.urlresolvers.reverse_lazy, except that it returns a fully qualified URL, using the request to determine the host and port.

+

Has the same behavior as django.urls.reverse_lazy, except that it returns a fully qualified URL, using the request to determine the host and port.

As with the reverse function, you should include the request as a keyword argument to the function, for example:

api_root = reverse_lazy('api-root', request=request)
 
diff --git a/api-guide/schemas/index.html b/api-guide/schemas/index.html index 3b8885cb7..92552db0e 100644 --- a/api-guide/schemas/index.html +++ b/api-guide/schemas/index.html @@ -385,11 +385,11 @@
  • - Using DefaultRouter + The get_schema_view shortcut
  • - Using SchemaGenerator + Using an explicit schema view
  • @@ -401,6 +401,16 @@
  • +
  • + Schemas as documentation +
  • + + +
  • + Examples +
  • + +
  • Alternate schema formats
  • @@ -528,13 +538,18 @@ for REST framework.

    REST framework includes functionality for auto-generating a schema, or allows you to specify one explicitly. There are a few different ways to add a schema to your API, depending on exactly what you need.

    -

    Using DefaultRouter

    -

    If you're using DefaultRouter then you can include an auto-generated schema, -simply by adding a schema_title argument to the router.

    -
    router = DefaultRouter(schema_title='Server Monitoring API')
    +

    The get_schema_view shortcut

    +

    The simplest way to include a schema in your project is to use the +get_schema_view() function.

    +
    schema_view = get_schema_view(title="Server Monitoring API")
    +
    +urlpatterns = [
    +    url('^$', schema_view),
    +    ...
    +]
     
    -

    The schema will be included at the root URL, /, and presented to clients -that include the Core JSON media type in their Accept header.

    +

    Once the view has been added, you'll be able to make API requests to retrieve +the auto-generated schema definition.

    $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json
     HTTP/1.0 200 OK
     Allow: GET, HEAD, OPTIONS
    @@ -548,49 +563,47 @@ Content-Type: application/vnd.coreapi+json
         ...
     }
     
    -

    This is a great zero-configuration option for when you want to get up and -running really quickly.

    -

    The other available options to DefaultRouter are:

    -

    schema_renderers

    -

    May be used to pass the set of renderer classes that can be used to render schema output.

    +

    The arguments to get_schema_view() are:

    +

    title

    +

    May be used to provide a descriptive title for the schema definition.

    +

    url

    +

    May be used to pass a canonical URL for the schema.

    +
    schema_view = get_schema_view(
    +    title='Server Monitoring API',
    +    url='https://www.example.org/api/'
    +)
    +
    +

    renderer_classes

    +

    May be used to pass the set of renderer classes that can be used to render the API root endpoint.

    from rest_framework.renderers import CoreJSONRenderer
     from my_custom_package import APIBlueprintRenderer
     
    -router = DefaultRouter(schema_title='Server Monitoring API', schema_renderers=[
    -    CoreJSONRenderer, APIBlueprintRenderer
    -])
    -
    -

    schema_url

    -

    May be used to pass the root URL for the schema. This can either be used to ensure that -the schema URLs include a canonical hostname and schema, or to ensure that all the -schema URLs include a path prefix.

    -
    router = DefaultRouter(
    -    schema_title='Server Monitoring API',
    -    schema_url='https://www.example.org/api/'
    +schema_view = get_schema_view(
    +    title='Server Monitoring API',
    +    url='https://www.example.org/api/',
    +    renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]
     )
     
    -

    If you want more flexibility over the schema output then you'll need to consider -using SchemaGenerator instead.

    -

    root_renderers

    -

    May be used to pass the set of renderer classes that can be used to render the API root endpoint.

    -

    Using SchemaGenerator

    -

    The most common way to add a schema to your API is to use the SchemaGenerator -class to auto-generate the Document instance, and to return that from a view.

    +

    Using an explicit schema view

    +

    If you need a little more control than the get_schema_view() shortcut gives you, +then you can use the SchemaGenerator class directly to auto-generate the +Document instance, and to return that from a view.

    This option gives you the flexibility of setting up the schema endpoint -with whatever behavior you want. For example, you can apply different -permission, throttling or authentication policies to the schema endpoint.

    +with whatever behaviour you want. For example, you can apply different +permission, throttling, or authentication policies to the schema endpoint.

    Here's an example of using SchemaGenerator together with a view to return the schema.

    views.py:

    from rest_framework.decorators import api_view, renderer_classes
     from rest_framework import renderers, response, schemas
     
    +generator = schemas.SchemaGenerator(title='Bookings API')
     
     @api_view()
     @renderer_classes([renderers.CoreJSONRenderer])
     def schema_view(request):
    -    generator = schemas.SchemaGenerator(title='Bookings API')
    -    return response.Response(generator.get_schema())
    +    schema = generator.get_schema(request)
    +    return response.Response(schema)
     

    urls.py:

    urlpatterns = [
    @@ -642,6 +655,60 @@ of the available formats, such as Core JSON or Open API.

    rendered to one of many available formats, depending on the client request.
    +

    Schemas as documentation

    +

    One common usage of API schemas is to use them to build documentation pages.

    +

    The schema generation in REST framework uses docstrings to automatically +populate descriptions in the schema document.

    +

    These descriptions will be based on:

    +
      +
    • The corresponding method docstring if one exists.
    • +
    • A named section within the class docstring, which can be either single line or multi-line.
    • +
    • The class docstring.
    • +
    +

    Examples

    +

    An APIView, with an explicit method docstring.

    +
    class ListUsernames(APIView):
    +    def get(self, request):
    +        """
    +        Return a list of all user names in the system.
    +        """
    +        usernames = [user.username for user in User.objects.all()]
    +        return Response(usernames)
    +
    +

    A ViewSet, with an explict action docstring.

    +
    class ListUsernames(ViewSet):
    +    def list(self, request):
    +        """
    +        Return a list of all user names in the system.
    +        """
    +        usernames = [user.username for user in User.objects.all()]
    +        return Response(usernames)
    +
    +

    A generic view with sections in the class docstring, using single-line style.

    +
    class UserList(generics.ListCreateAPIView):
    +    """
    +    get: Create a new user.
    +    post: List all the users.
    +    """
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +    permission_classes = (IsAdminUser,)
    +
    +

    A generic viewset with sections in the class docstring, using multi-line style.

    +
    class UserViewSet(viewsets.ModelViewSet):
    +    """
    +    API endpoint that allows users to be viewed or edited.
    +
    +    retrieve:
    +    Return a user instance.
    +
    +    list:
    +    Return all users, ordered by most recently joined.
    +    """
    +    queryset = User.objects.all().order_by('-date_joined')
    +    serializer_class = UserSerializer
    +
    +

    Alternate schema formats

    In order to support an alternate schema format, you need to implement a custom renderer class that handles converting a Document instance into a bytestring representation.

    @@ -696,9 +763,9 @@ package that are used to represent an API schema.

    from the rest_framework package.

    Document

    Represents a container for the API schema.

    -

    title

    +

    title

    A name for the API.

    -

    url

    +

    url

    A canonical URL for the API.

    content

    A dictionary, containing the Link objects that the schema contains.

    @@ -719,7 +786,7 @@ may be nested, typically to a second level. For example:

    Represents an individual API endpoint.

    -

    url

    +

    url

    The URL of the endpoint. May be a URI template, such as /users/{username}/.

    action

    The HTTP method associated with the endpoint. Note that URLs that support diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html index 2d8c249fd..479ec4dc3 100644 --- a/api-guide/serializers/index.html +++ b/api-guide/serializers/index.html @@ -550,6 +550,10 @@ Dynamic REST +

  • + Dynamic Fields Mixin +
  • +
  • HTML JSON Forms
  • @@ -1418,6 +1422,8 @@ def all_high_scores(request):

    The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature.

    Dynamic REST

    The dynamic-rest package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.

    +

    Dynamic Fields Mixin

    +

    The drf-dynamic-fields package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.

    HTML JSON Forms

    The html-json-forms package provides an algorithm and serializer for processing <form> submissions per the (inactive) HTML JSON Form specification. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, <input name="items[0][id]" value="5"> will be interpreted as {"items": [{"id": "5"}]}.

    diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html index 8f77d41fd..110a0b61a 100644 --- a/api-guide/settings/index.html +++ b/api-guide/settings/index.html @@ -396,6 +396,10 @@ Test settings +
  • + Schema generation controls +
  • +
  • Content type controls
  • @@ -412,6 +416,10 @@ View names and descriptions +
  • + HTML Select Field cutoffs +
  • +
  • Miscellaneous settings
  • @@ -577,6 +585,20 @@ If set to None then generic filtering is disabled.

    )

    +

    Schema generation controls

    +

    SCHEMA_COERCE_PATH_PK

    +

    If set, this maps the 'pk' identifier in the URL conf onto the actual field +name when generating a schema path parameter. Typically this will be 'id'. +This gives a more suitable representation as "primary key" is an implementation +detail, wheras "identifier" is a more general concept.

    +

    Default: True

    +

    SCHEMA_COERCE_METHOD_NAMES

    +

    If set, this is used to map internal viewset method names onto external action +names used in the schema generation. This allows us to generate names that +are more suitable for an external representation than those that are used +internally in the codebase.

    +

    Default: {'retrieve': 'read', 'destroy': 'delete'}

    +

    Content type controls

    URL_FORMAT_OVERRIDE

    The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=… query parameter in the request URL.

    @@ -662,6 +684,14 @@ If set to None then generic filtering is disabled.

  • html: A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses.
  • Default: 'rest_framework.views.get_view_description'

    +

    HTML Select Field cutoffs

    +

    Global settings for select field cutoffs for rendering relational fields in the browsable API.

    +

    HTML_SELECT_CUTOFF

    +

    Global setting for the html_cutoff value. Must be an integer.

    +

    Default: 1000

    +

    HTML_SELECT_CUTOFF_TEXT

    +

    A string representing a global setting for html_cutoff_text.

    +

    Default: "More than {count} items..."


    Miscellaneous settings

    EXCEPTION_HANDLER

    diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html index 43c637ef5..44bbd1461 100644 --- a/api-guide/testing/index.html +++ b/api-guide/testing/index.html @@ -403,6 +403,34 @@ +
  • + RequestsClient +
  • + + +
  • + Headers & Authentication +
  • + +
  • + CSRF +
  • + +
  • + Live tests +
  • + + +
  • + CoreAPIClient +
  • + + +
  • + Headers & Authentication +
  • + +
  • Test cases
  • @@ -593,6 +621,80 @@ client.force_authenticate(user=user)

    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 login().


    +

    RequestsClient

    +

    REST framework also includes a client for interacting with your application +using the popular Python library, requests.

    +

    This exposes exactly the same interface as if you were using a requests session +directly.

    +
    client = RequestsClient()
    +response = client.get('http://testserver/users/')
    +
    +

    Note that the requests client requires you to pass fully qualified URLs.

    +

    Headers & Authentication

    +

    Custom headers and authentication credentials can be provided in the same way +as when using a standard requests.Session instance.

    +
    from requests.auth import HTTPBasicAuth
    +
    +client.auth = HTTPBasicAuth('user', 'pass')
    +client.headers.update({'x-test': 'true'})
    +
    +

    CSRF

    +

    If you're using SessionAuthentication then you'll need to include a CSRF token +for any POST, PUT, PATCH or DELETE requests.

    +

    You can do so by following the same flow that a JavaScript based client would use. +First make a GET request in order to obtain a CRSF token, then present that +token in the following request.

    +

    For example...

    +
    client = RequestsClient()
    +
    +# Obtain a CSRF token.
    +response = client.get('/homepage/')
    +assert response.status_code == 200
    +csrftoken = response.cookies['csrftoken']
    +
    +# Interact with the API.
    +response = client.post('/organisations/', json={
    +    'name': 'MegaCorp',
    +    'status': 'active'
    +}, headers={'X-CSRFToken': csrftoken})
    +assert response.status_code == 200
    +
    +

    Live tests

    +

    With careful usage both the RequestsClient and the CoreAPIClient provide +the ability to write test cases that can run either in development, or be run +directly against your staging server or production environment.

    +

    Using this style to create basic tests of a few core piece of functionality is +a powerful way to validate your live service. Doing so may require some careful +attention to setup and teardown to ensure that the tests run in a way that they +do not directly affect customer data.

    +
    +

    CoreAPIClient

    +

    The CoreAPIClient allows you to interact with your API using the Python +coreapi client library.

    +
    # Fetch the API schema
    +url = reverse('schema')
    +client = CoreAPIClient()
    +schema = client.get(url)
    +
    +# Create a new organisation
    +params = {'name': 'MegaCorp', 'status': 'active'}
    +client.action(schema, ['organisations', 'create'], params)
    +
    +# Ensure that the organisation exists in the listing
    +data = client.action(schema, ['organisations', 'list'])
    +assert(len(data) == 1)
    +assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
    +
    +

    Headers & Authentication

    +

    Custom headers and authentication may be used with CoreAPIClient in a +similar way as with RequestsClient.

    +
    from requests.auth import HTTPBasicAuth
    +
    +client = CoreAPIClient()
    +client.session.auth = HTTPBasicAuth('user', 'pass')
    +client.session.headers.update({'x-test': 'true'})
    +
    +

    Test cases

    REST framework includes the following test case classes, that mirror the existing Django test case classes, but use APIClient instead of Django's default Client.

    Example

    You can use any of REST framework's test case classes as you would for the regular Django test case classes. The self.client attribute will be an APIClient instance.

    -
    from django.core.urlresolvers import reverse
    +
    from django.urls import reverse
     from rest_framework import status
     from rest_framework.test import APITestCase
     from myproject.apps.core.models import Account
    diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html
    index b6d0d30df..395b66287 100644
    --- a/api-guide/validators/index.html
    +++ b/api-guide/validators/index.html
    @@ -504,6 +504,7 @@ It takes a single required argument, and an optional messages argum
     
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • message - The error message that should be used when validation fails.
    • +
    • lookup - The lookup used to find an existing instance with the value being validated. Defaults to 'exact'.

    This validator should be applied to serializer fields, like so:

    from rest_framework.validators import UniqueValidator
    diff --git a/api-guide/views/index.html b/api-guide/views/index.html
    index 506faba18..4db79efca 100644
    --- a/api-guide/views/index.html
    +++ b/api-guide/views/index.html
    @@ -503,7 +503,7 @@ This method is used to enforce permissions and throttling, and perform content n
     
     

    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 Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.

    @api_view()

    -

    Signature: @api_view(http_method_names=['GET'])

    +

    Signature: @api_view(http_method_names=['GET'], exclude_from_schema=False)

    The core of this functionality is the api_view 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:

    from rest_framework.decorators import api_view
     
    @@ -512,13 +512,19 @@ def hello_world(request):
         return Response({"message": "Hello, world!"})
     

    This view will use the default renderers, parsers, authentication classes etc specified in the settings.

    -

    By default only GET methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:

    +

    By default only GET methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:

    @api_view(['GET', 'POST'])
     def hello_world(request):
         if request.method == 'POST':
             return Response({"message": "Got some data!", "data": request.data})
         return Response({"message": "Hello, world!"})
     
    +

    You can also mark an API view as being omitted from any auto-generated schema, +using the exclude_from_schema argument.:

    +
    @api_view(['GET'], exclude_from_schema=True)
    +def api_docs(request):
    +    ...
    +

    API policy decorators

    To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:

    from rest_framework.decorators import api_view, throttle_classes
    diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json
    index b78dac3d0..643eb2f97 100644
    --- a/mkdocs/search_index.json
    +++ b/mkdocs/search_index.json
    @@ -107,7 +107,7 @@
             }, 
             {
                 "location": "/tutorial/1-serialization/", 
    -            "text": "Tutorial 1: Serialization\n\n\nIntroduction\n\n\nThis 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.\n\n\nThe 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 \nquickstart\n documentation instead.\n\n\n\n\nNote\n: The code for this tutorial is available in the \ntomchristie/rest-framework-tutorial\n repository on GitHub.  The completed implementation is also online as a sandbox version for testing, \navailable here\n.\n\n\n\n\nSetting up a new environment\n\n\nBefore we do anything else we'll create a new virtual environment, using \nvirtualenv\n.  This will make sure our package configuration is kept nicely isolated from any other projects we're working on.\n\n\nvirtualenv env\nsource env/bin/activate\n\n\n\nNow that we're inside a virtualenv environment, we can install our package requirements.\n\n\npip install django\npip install djangorestframework\npip install pygments  # We'll be using this for the code highlighting\n\n\n\nNote:\n To exit the virtualenv environment at any time, just type \ndeactivate\n.  For more information see the \nvirtualenv documentation\n.\n\n\nGetting started\n\n\nOkay, we're ready to get coding.\nTo get started, let's create a new project to work with.\n\n\ncd ~\ndjango-admin.py startproject tutorial\ncd tutorial\n\n\n\nOnce that's done we can create an app that we'll use to create a simple Web API.\n\n\npython manage.py startapp snippets\n\n\n\nWe'll need to add our new \nsnippets\n app and the \nrest_framework\n app to \nINSTALLED_APPS\n. Let's edit the \ntutorial/settings.py\n file:\n\n\nINSTALLED_APPS = (\n    ...\n    'rest_framework',\n    'snippets.apps.SnippetsConfig',\n)\n\n\n\nOkay, we're ready to roll.\n\n\nCreating a model to work with\n\n\nFor the purposes of this tutorial we're going to start by creating a simple \nSnippet\n model that is used to store code snippets.  Go ahead and edit the \nsnippets/models.py\n 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.\n\n\nfrom django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted((item, item) for item in get_all_styles())\n\n\nclass Snippet(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    title = models.CharField(max_length=100, blank=True, default='')\n    code = models.TextField()\n    linenos = models.BooleanField(default=False)\n    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)\n    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)\n\n    class Meta:\n        ordering = ('created',)\n\n\n\nWe'll also need to create an initial migration for our snippet model, and sync the database for the first time.\n\n\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nCreating a Serializer class\n\n\nThe 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 \njson\n.  We can do this by declaring serializers that work very similar to Django's forms.  Create a file in the \nsnippets\n directory named \nserializers.py\n and add the following.\n\n\nfrom rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n    pk = serializers.IntegerField(read_only=True)\n    title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n    code = serializers.CharField(style={'base_template': 'textarea.html'})\n    linenos = serializers.BooleanField(required=False)\n    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n    def create(self, validated_data):\n        \"\"\"\n        Create and return a new `Snippet` instance, given the validated data.\n        \"\"\"\n        return Snippet.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        \"\"\"\n        Update and return an existing `Snippet` instance, given the validated data.\n        \"\"\"\n        instance.title = validated_data.get('title', instance.title)\n        instance.code = validated_data.get('code', instance.code)\n        instance.linenos = validated_data.get('linenos', instance.linenos)\n        instance.language = validated_data.get('language', instance.language)\n        instance.style = validated_data.get('style', instance.style)\n        instance.save()\n        return instance\n\n\n\nThe first part of the serializer class defines the fields that get serialized/deserialized.  The \ncreate()\n and \nupdate()\n methods define how fully fledged instances are created or modified when calling \nserializer.save()\n\n\nA serializer class is very similar to a Django \nForm\n class, and includes similar validation flags on the various fields, such as \nrequired\n, \nmax_length\n and \ndefault\n.\n\n\nThe field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The \n{'base_template': 'textarea.html'}\n flag above is equivalent to using \nwidget=widgets.Textarea\n on a Django \nForm\n class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.\n\n\nWe can actually also save ourselves some time by using the \nModelSerializer\n class, as we'll see later, but for now we'll keep our serializer definition explicit.\n\n\nWorking with Serializers\n\n\nBefore we go any further we'll familiarize ourselves with using our new Serializer class.  Let's drop into the Django shell.\n\n\npython manage.py shell\n\n\n\nOkay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()\n\n\n\nWe've now got a few snippet instances to play with.  Let's take a look at serializing one of those instances.\n\n\nserializer = SnippetSerializer(snippet)\nserializer.data\n# {'pk': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes.  To finalize the serialization process we render the data into \njson\n.\n\n\ncontent = JSONRenderer().render(serializer.data)\ncontent\n# '{\"pk\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'\n\n\n\nDeserialization is similar.  First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a fully populated object instance.\n\n\nserializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n# \nSnippet: Snippet object\n\n\n\n\nNotice how similar the API is to working with forms.  The similarity should become even more apparent when we start writing views that use our serializer.\n\n\nWe can also serialize querysets instead of model instances.  To do so we simply add a \nmany=True\n flag to the serializer arguments.\n\n\nserializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [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')])]\n\n\n\nUsing ModelSerializers\n\n\nOur \nSnippetSerializer\n class is replicating a lot of information that's also contained in the \nSnippet\n model.  It would be nice if we could keep our code a bit  more concise.\n\n\nIn the same way that Django provides both \nForm\n classes and \nModelForm\n classes, REST framework includes both \nSerializer\n classes, and \nModelSerializer\n classes.\n\n\nLet's look at refactoring our serializer using the \nModelSerializer\n class.\nOpen the file \nsnippets/serializers.py\n again, and replace the \nSnippetSerializer\n class with the following.\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Snippet\n        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')\n\n\n\nOne nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with \npython manage.py shell\n, then try the following:\n\n\nfrom snippets.serializers import SnippetSerializer\nserializer = SnippetSerializer()\nprint(repr(serializer))\n# SnippetSerializer():\n#    id = IntegerField(label='ID', read_only=True)\n#    title = CharField(allow_blank=True, max_length=100, required=False)\n#    code = CharField(style={'base_template': 'textarea.html'})\n#    linenos = BooleanField(required=False)\n#    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n#    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n\n\n\nIt's important to remember that \nModelSerializer\n classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:\n\n\n\n\nAn automatically determined set of fields.\n\n\nSimple default implementations for the \ncreate()\n and \nupdate()\n methods.\n\n\n\n\nWriting regular Django views using our Serializer\n\n\nLet's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.\n\n\nWe'll start off by creating a subclass of HttpResponse that we can use to render any data we return into \njson\n.\n\n\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n    \"\"\"\n    An HttpResponse that renders its content into JSON.\n    \"\"\"\n    def __init__(self, data, **kwargs):\n        content = JSONRenderer().render(data)\n        kwargs['content_type'] = 'application/json'\n        super(JSONResponse, self).__init__(content, **kwargs)\n\n\n\nThe root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.\n\n\n@csrf_exempt\ndef snippet_list(request):\n    \"\"\"\n    List all code snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'POST':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data, status=201)\n        return JSONResponse(serializer.errors, status=400)\n\n\n\nNote that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as \ncsrf_exempt\n.  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.\n\n\nWe'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.\n\n\n@csrf_exempt\ndef snippet_detail(request, pk):\n    \"\"\"\n    Retrieve, update or delete a code snippet.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(pk=pk)\n    except Snippet.DoesNotExist:\n        return HttpResponse(status=404)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'PUT':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(snippet, data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data)\n        return JSONResponse(serializer.errors, status=400)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return HttpResponse(status=204)\n\n\n\nFinally we need to wire these views up.  Create the \nsnippets/urls.py\n file:\n\n\nfrom django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P\npk\n[0-9]+)/$', views.snippet_detail),\n]\n\n\n\nWe also need to wire up the root urlconf, in the \ntutorial/urls.py\n file, to include our snippet app's URLs.\n\n\nfrom django.conf.urls import url, include\n\nurlpatterns = [\n    url(r'^', include('snippets.urls')),\n]\n\n\n\nIt's worth noting that there are a couple of edge cases we're not dealing with properly at the moment.  If we send malformed \njson\n, 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.\n\n\nTesting our first attempt at a Web API\n\n\nNow we can start up a sample server that serves our snippets.\n\n\nQuit out of the shell...\n\n\nquit()\n\n\n\n...and start up Django's development server.\n\n\npython manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 1.8.3, using settings 'tutorial.settings'\nDevelopment server is running at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n\n\n\nIn another terminal window, we can test the server.\n\n\nWe can test our API using \ncurl\n or \nhttpie\n. Httpie is a user friendly http client that's written in Python. Let's install that.\n\n\nYou can install httpie using pip:\n\n\npip install httpie\n\n\n\nFinally, we can get a list of all of the snippets:\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n  {\n    \"id\": 1,\n    \"title\": \"\",\n    \"code\": \"foo = \\\"bar\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"\",\n    \"code\": \"print \\\"hello, world\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  }\n]\n\n\n\nOr we can get a particular snippet by referencing its id:\n\n\nhttp http://127.0.0.1:8000/snippets/2/\n\nHTTP/1.1 200 OK\n...\n{\n  \"id\": 2,\n  \"title\": \"\",\n  \"code\": \"print \\\"hello, world\\\"\\n\",\n  \"linenos\": false,\n  \"language\": \"python\",\n  \"style\": \"friendly\"\n}\n\n\n\nSimilarly, you can have the same json displayed by visiting these URLs in a web browser.\n\n\nWhere are we now\n\n\nWe'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.\n\n\nOur API views don't do anything particularly special at the moment, beyond serving \njson\n responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.\n\n\nWe'll see how we can start to improve things in \npart 2 of the tutorial\n.", 
    +            "text": "Tutorial 1: Serialization\n\n\nIntroduction\n\n\nThis 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.\n\n\nThe 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 \nquickstart\n documentation instead.\n\n\n\n\nNote\n: The code for this tutorial is available in the \ntomchristie/rest-framework-tutorial\n repository on GitHub.  The completed implementation is also online as a sandbox version for testing, \navailable here\n.\n\n\n\n\nSetting up a new environment\n\n\nBefore we do anything else we'll create a new virtual environment, using \nvirtualenv\n.  This will make sure our package configuration is kept nicely isolated from any other projects we're working on.\n\n\nvirtualenv env\nsource env/bin/activate\n\n\n\nNow that we're inside a virtualenv environment, we can install our package requirements.\n\n\npip install django\npip install djangorestframework\npip install pygments  # We'll be using this for the code highlighting\n\n\n\nNote:\n To exit the virtualenv environment at any time, just type \ndeactivate\n.  For more information see the \nvirtualenv documentation\n.\n\n\nGetting started\n\n\nOkay, we're ready to get coding.\nTo get started, let's create a new project to work with.\n\n\ncd ~\ndjango-admin.py startproject tutorial\ncd tutorial\n\n\n\nOnce that's done we can create an app that we'll use to create a simple Web API.\n\n\npython manage.py startapp snippets\n\n\n\nWe'll need to add our new \nsnippets\n app and the \nrest_framework\n app to \nINSTALLED_APPS\n. Let's edit the \ntutorial/settings.py\n file:\n\n\nINSTALLED_APPS = (\n    ...\n    'rest_framework',\n    'snippets.apps.SnippetsConfig',\n)\n\n\n\nOkay, we're ready to roll.\n\n\nCreating a model to work with\n\n\nFor the purposes of this tutorial we're going to start by creating a simple \nSnippet\n model that is used to store code snippets.  Go ahead and edit the \nsnippets/models.py\n 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.\n\n\nfrom django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted((item, item) for item in get_all_styles())\n\n\nclass Snippet(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    title = models.CharField(max_length=100, blank=True, default='')\n    code = models.TextField()\n    linenos = models.BooleanField(default=False)\n    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)\n    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)\n\n    class Meta:\n        ordering = ('created',)\n\n\n\nWe'll also need to create an initial migration for our snippet model, and sync the database for the first time.\n\n\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nCreating a Serializer class\n\n\nThe 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 \njson\n.  We can do this by declaring serializers that work very similar to Django's forms.  Create a file in the \nsnippets\n directory named \nserializers.py\n and add the following.\n\n\nfrom rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n    id = serializers.IntegerField(read_only=True)\n    title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n    code = serializers.CharField(style={'base_template': 'textarea.html'})\n    linenos = serializers.BooleanField(required=False)\n    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n    def create(self, validated_data):\n        \"\"\"\n        Create and return a new `Snippet` instance, given the validated data.\n        \"\"\"\n        return Snippet.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        \"\"\"\n        Update and return an existing `Snippet` instance, given the validated data.\n        \"\"\"\n        instance.title = validated_data.get('title', instance.title)\n        instance.code = validated_data.get('code', instance.code)\n        instance.linenos = validated_data.get('linenos', instance.linenos)\n        instance.language = validated_data.get('language', instance.language)\n        instance.style = validated_data.get('style', instance.style)\n        instance.save()\n        return instance\n\n\n\nThe first part of the serializer class defines the fields that get serialized/deserialized.  The \ncreate()\n and \nupdate()\n methods define how fully fledged instances are created or modified when calling \nserializer.save()\n\n\nA serializer class is very similar to a Django \nForm\n class, and includes similar validation flags on the various fields, such as \nrequired\n, \nmax_length\n and \ndefault\n.\n\n\nThe field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The \n{'base_template': 'textarea.html'}\n flag above is equivalent to using \nwidget=widgets.Textarea\n on a Django \nForm\n class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.\n\n\nWe can actually also save ourselves some time by using the \nModelSerializer\n class, as we'll see later, but for now we'll keep our serializer definition explicit.\n\n\nWorking with Serializers\n\n\nBefore we go any further we'll familiarize ourselves with using our new Serializer class.  Let's drop into the Django shell.\n\n\npython manage.py shell\n\n\n\nOkay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()\n\n\n\nWe've now got a few snippet instances to play with.  Let's take a look at serializing one of those instances.\n\n\nserializer = SnippetSerializer(snippet)\nserializer.data\n# {'id': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes.  To finalize the serialization process we render the data into \njson\n.\n\n\ncontent = JSONRenderer().render(serializer.data)\ncontent\n# '{\"id\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'\n\n\n\nDeserialization is similar.  First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a fully populated object instance.\n\n\nserializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n# \nSnippet: Snippet object\n\n\n\n\nNotice how similar the API is to working with forms.  The similarity should become even more apparent when we start writing views that use our serializer.\n\n\nWe can also serialize querysets instead of model instances.  To do so we simply add a \nmany=True\n flag to the serializer arguments.\n\n\nserializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = \"bar\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print \"hello, world\"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]\n\n\n\nUsing ModelSerializers\n\n\nOur \nSnippetSerializer\n class is replicating a lot of information that's also contained in the \nSnippet\n model.  It would be nice if we could keep our code a bit  more concise.\n\n\nIn the same way that Django provides both \nForm\n classes and \nModelForm\n classes, REST framework includes both \nSerializer\n classes, and \nModelSerializer\n classes.\n\n\nLet's look at refactoring our serializer using the \nModelSerializer\n class.\nOpen the file \nsnippets/serializers.py\n again, and replace the \nSnippetSerializer\n class with the following.\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Snippet\n        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')\n\n\n\nOne nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with \npython manage.py shell\n, then try the following:\n\n\nfrom snippets.serializers import SnippetSerializer\nserializer = SnippetSerializer()\nprint(repr(serializer))\n# SnippetSerializer():\n#    id = IntegerField(label='ID', read_only=True)\n#    title = CharField(allow_blank=True, max_length=100, required=False)\n#    code = CharField(style={'base_template': 'textarea.html'})\n#    linenos = BooleanField(required=False)\n#    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n#    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n\n\n\nIt's important to remember that \nModelSerializer\n classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:\n\n\n\n\nAn automatically determined set of fields.\n\n\nSimple default implementations for the \ncreate()\n and \nupdate()\n methods.\n\n\n\n\nWriting regular Django views using our Serializer\n\n\nLet's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.\n\n\nWe'll start off by creating a subclass of HttpResponse that we can use to render any data we return into \njson\n.\n\n\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n    \"\"\"\n    An HttpResponse that renders its content into JSON.\n    \"\"\"\n    def __init__(self, data, **kwargs):\n        content = JSONRenderer().render(data)\n        kwargs['content_type'] = 'application/json'\n        super(JSONResponse, self).__init__(content, **kwargs)\n\n\n\nThe root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.\n\n\n@csrf_exempt\ndef snippet_list(request):\n    \"\"\"\n    List all code snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'POST':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data, status=201)\n        return JSONResponse(serializer.errors, status=400)\n\n\n\nNote that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as \ncsrf_exempt\n.  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.\n\n\nWe'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.\n\n\n@csrf_exempt\ndef snippet_detail(request, id):\n    \"\"\"\n    Retrieve, update or delete a code snippet.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(id=id)\n    except Snippet.DoesNotExist:\n        return HttpResponse(status=404)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'PUT':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(snippet, data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data)\n        return JSONResponse(serializer.errors, status=400)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return HttpResponse(status=204)\n\n\n\nFinally we need to wire these views up.  Create the \nsnippets/urls.py\n file:\n\n\nfrom django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P\nid\n[0-9]+)/$', views.snippet_detail),\n]\n\n\n\nWe also need to wire up the root urlconf, in the \ntutorial/urls.py\n file, to include our snippet app's URLs.\n\n\nfrom django.conf.urls import url, include\n\nurlpatterns = [\n    url(r'^', include('snippets.urls')),\n]\n\n\n\nIt's worth noting that there are a couple of edge cases we're not dealing with properly at the moment.  If we send malformed \njson\n, 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.\n\n\nTesting our first attempt at a Web API\n\n\nNow we can start up a sample server that serves our snippets.\n\n\nQuit out of the shell...\n\n\nquit()\n\n\n\n...and start up Django's development server.\n\n\npython manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 1.8.3, using settings 'tutorial.settings'\nDevelopment server is running at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n\n\n\nIn another terminal window, we can test the server.\n\n\nWe can test our API using \ncurl\n or \nhttpie\n. Httpie is a user friendly http client that's written in Python. Let's install that.\n\n\nYou can install httpie using pip:\n\n\npip install httpie\n\n\n\nFinally, we can get a list of all of the snippets:\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n  {\n    \"id\": 1,\n    \"title\": \"\",\n    \"code\": \"foo = \\\"bar\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"\",\n    \"code\": \"print \\\"hello, world\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  }\n]\n\n\n\nOr we can get a particular snippet by referencing its id:\n\n\nhttp http://127.0.0.1:8000/snippets/2/\n\nHTTP/1.1 200 OK\n...\n{\n  \"id\": 2,\n  \"title\": \"\",\n  \"code\": \"print \\\"hello, world\\\"\\n\",\n  \"linenos\": false,\n  \"language\": \"python\",\n  \"style\": \"friendly\"\n}\n\n\n\nSimilarly, you can have the same json displayed by visiting these URLs in a web browser.\n\n\nWhere are we now\n\n\nWe'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.\n\n\nOur API views don't do anything particularly special at the moment, beyond serving \njson\n responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.\n\n\nWe'll see how we can start to improve things in \npart 2 of the tutorial\n.", 
                 "title": "1 - Serialization"
             }, 
             {
    @@ -137,12 +137,12 @@
             }, 
             {
                 "location": "/tutorial/1-serialization/#creating-a-serializer-class", 
    -            "text": "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  json .  We can do this by declaring serializers that work very similar to Django's forms.  Create a file in the  snippets  directory named  serializers.py  and add the following.  from rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n    pk = serializers.IntegerField(read_only=True)\n    title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n    code = serializers.CharField(style={'base_template': 'textarea.html'})\n    linenos = serializers.BooleanField(required=False)\n    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n    def create(self, validated_data):\n        \"\"\"\n        Create and return a new `Snippet` instance, given the validated data.\n        \"\"\"\n        return Snippet.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        \"\"\"\n        Update and return an existing `Snippet` instance, given the validated data.\n        \"\"\"\n        instance.title = validated_data.get('title', instance.title)\n        instance.code = validated_data.get('code', instance.code)\n        instance.linenos = validated_data.get('linenos', instance.linenos)\n        instance.language = validated_data.get('language', instance.language)\n        instance.style = validated_data.get('style', instance.style)\n        instance.save()\n        return instance  The first part of the serializer class defines the fields that get serialized/deserialized.  The  create()  and  update()  methods define how fully fledged instances are created or modified when calling  serializer.save()  A serializer class is very similar to a Django  Form  class, and includes similar validation flags on the various fields, such as  required ,  max_length  and  default .  The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The  {'base_template': 'textarea.html'}  flag above is equivalent to using  widget=widgets.Textarea  on a Django  Form  class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.  We can actually also save ourselves some time by using the  ModelSerializer  class, as we'll see later, but for now we'll keep our serializer definition explicit.", 
    +            "text": "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  json .  We can do this by declaring serializers that work very similar to Django's forms.  Create a file in the  snippets  directory named  serializers.py  and add the following.  from rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n    id = serializers.IntegerField(read_only=True)\n    title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n    code = serializers.CharField(style={'base_template': 'textarea.html'})\n    linenos = serializers.BooleanField(required=False)\n    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n    def create(self, validated_data):\n        \"\"\"\n        Create and return a new `Snippet` instance, given the validated data.\n        \"\"\"\n        return Snippet.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        \"\"\"\n        Update and return an existing `Snippet` instance, given the validated data.\n        \"\"\"\n        instance.title = validated_data.get('title', instance.title)\n        instance.code = validated_data.get('code', instance.code)\n        instance.linenos = validated_data.get('linenos', instance.linenos)\n        instance.language = validated_data.get('language', instance.language)\n        instance.style = validated_data.get('style', instance.style)\n        instance.save()\n        return instance  The first part of the serializer class defines the fields that get serialized/deserialized.  The  create()  and  update()  methods define how fully fledged instances are created or modified when calling  serializer.save()  A serializer class is very similar to a Django  Form  class, and includes similar validation flags on the various fields, such as  required ,  max_length  and  default .  The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The  {'base_template': 'textarea.html'}  flag above is equivalent to using  widget=widgets.Textarea  on a Django  Form  class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.  We can actually also save ourselves some time by using the  ModelSerializer  class, as we'll see later, but for now we'll keep our serializer definition explicit.", 
                 "title": "Creating a Serializer class"
             }, 
             {
                 "location": "/tutorial/1-serialization/#working-with-serializers", 
    -            "text": "Before we go any further we'll familiarize ourselves with using our new Serializer class.  Let's drop into the Django shell.  python manage.py shell  Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.  from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()  We've now got a few snippet instances to play with.  Let's take a look at serializing one of those instances.  serializer = SnippetSerializer(snippet)\nserializer.data\n# {'pk': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}  At this point we've translated the model instance into Python native datatypes.  To finalize the serialization process we render the data into  json .  content = JSONRenderer().render(serializer.data)\ncontent\n# '{\"pk\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'  Deserialization is similar.  First we parse a stream into Python native datatypes...  from django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)  ...then we restore those native datatypes into a fully populated object instance.  serializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n#  Snippet: Snippet object   Notice how similar the API is to working with forms.  The similarity should become even more apparent when we start writing views that use our serializer.  We can also serialize querysets instead of model instances.  To do so we simply add a  many=True  flag to the serializer arguments.  serializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [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')])]", 
    +            "text": "Before we go any further we'll familiarize ourselves with using our new Serializer class.  Let's drop into the Django shell.  python manage.py shell  Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.  from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()  We've now got a few snippet instances to play with.  Let's take a look at serializing one of those instances.  serializer = SnippetSerializer(snippet)\nserializer.data\n# {'id': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}  At this point we've translated the model instance into Python native datatypes.  To finalize the serialization process we render the data into  json .  content = JSONRenderer().render(serializer.data)\ncontent\n# '{\"id\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'  Deserialization is similar.  First we parse a stream into Python native datatypes...  from django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)  ...then we restore those native datatypes into a fully populated object instance.  serializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n#  Snippet: Snippet object   Notice how similar the API is to working with forms.  The similarity should become even more apparent when we start writing views that use our serializer.  We can also serialize querysets instead of model instances.  To do so we simply add a  many=True  flag to the serializer arguments.  serializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = \"bar\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print \"hello, world\"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]", 
                 "title": "Working with Serializers"
             }, 
             {
    @@ -152,7 +152,7 @@
             }, 
             {
                 "location": "/tutorial/1-serialization/#writing-regular-django-views-using-our-serializer", 
    -            "text": "Let's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.  We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into  json .  Edit the  snippets/views.py  file, and add the following.  from django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n    \"\"\"\n    An HttpResponse that renders its content into JSON.\n    \"\"\"\n    def __init__(self, data, **kwargs):\n        content = JSONRenderer().render(data)\n        kwargs['content_type'] = 'application/json'\n        super(JSONResponse, self).__init__(content, **kwargs)  The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.  @csrf_exempt\ndef snippet_list(request):\n    \"\"\"\n    List all code snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'POST':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data, status=201)\n        return JSONResponse(serializer.errors, status=400)  Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as  csrf_exempt .  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.  We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.  @csrf_exempt\ndef snippet_detail(request, pk):\n    \"\"\"\n    Retrieve, update or delete a code snippet.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(pk=pk)\n    except Snippet.DoesNotExist:\n        return HttpResponse(status=404)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'PUT':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(snippet, data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data)\n        return JSONResponse(serializer.errors, status=400)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return HttpResponse(status=204)  Finally we need to wire these views up.  Create the  snippets/urls.py  file:  from django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P pk [0-9]+)/$', views.snippet_detail),\n]  We also need to wire up the root urlconf, in the  tutorial/urls.py  file, to include our snippet app's URLs.  from django.conf.urls import url, include\n\nurlpatterns = [\n    url(r'^', include('snippets.urls')),\n]  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  json , 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.", 
    +            "text": "Let's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.  We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into  json .  Edit the  snippets/views.py  file, and add the following.  from django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n    \"\"\"\n    An HttpResponse that renders its content into JSON.\n    \"\"\"\n    def __init__(self, data, **kwargs):\n        content = JSONRenderer().render(data)\n        kwargs['content_type'] = 'application/json'\n        super(JSONResponse, self).__init__(content, **kwargs)  The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.  @csrf_exempt\ndef snippet_list(request):\n    \"\"\"\n    List all code snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'POST':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data, status=201)\n        return JSONResponse(serializer.errors, status=400)  Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as  csrf_exempt .  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.  We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.  @csrf_exempt\ndef snippet_detail(request, id):\n    \"\"\"\n    Retrieve, update or delete a code snippet.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(id=id)\n    except Snippet.DoesNotExist:\n        return HttpResponse(status=404)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return JSONResponse(serializer.data)\n\n    elif request.method == 'PUT':\n        data = JSONParser().parse(request)\n        serializer = SnippetSerializer(snippet, data=data)\n        if serializer.is_valid():\n            serializer.save()\n            return JSONResponse(serializer.data)\n        return JSONResponse(serializer.errors, status=400)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return HttpResponse(status=204)  Finally we need to wire these views up.  Create the  snippets/urls.py  file:  from django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P id [0-9]+)/$', views.snippet_detail),\n]  We also need to wire up the root urlconf, in the  tutorial/urls.py  file, to include our snippet app's URLs.  from django.conf.urls import url, include\n\nurlpatterns = [\n    url(r'^', include('snippets.urls')),\n]  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  json , 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.", 
                 "title": "Writing regular Django views using our Serializer"
             }, 
             {
    @@ -167,7 +167,7 @@
             }, 
             {
                 "location": "/tutorial/2-requests-and-responses/", 
    -            "text": "Tutorial 2: Requests and Responses\n\n\nFrom this point we're going to really start covering the core of REST framework.\nLet's introduce a couple of essential building blocks.\n\n\nRequest objects\n\n\nREST framework introduces a \nRequest\n object that extends the regular \nHttpRequest\n, and provides more flexible request parsing.  The core functionality of the \nRequest\n object is the \nrequest.data\n attribute, which is similar to \nrequest.POST\n, but more useful for working with Web APIs.\n\n\nrequest.POST  # Only handles form data.  Only works for 'POST' method.\nrequest.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.\n\n\n\nResponse objects\n\n\nREST framework also introduces a \nResponse\n object, which is a type of \nTemplateResponse\n that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.\n\n\nreturn Response(data)  # Renders to content type as requested by the client.\n\n\n\nStatus codes\n\n\nUsing 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 \nHTTP_400_BAD_REQUEST\n in the \nstatus\n module.  It's a good idea to use these throughout rather than using numeric identifiers.\n\n\nWrapping API views\n\n\nREST framework provides two wrappers you can use to write API views.\n\n\n\n\nThe \n@api_view\n decorator for working with function based views.\n\n\nThe \nAPIView\n class for working with class-based views.\n\n\n\n\nThese wrappers provide a few bits of functionality such as making sure you receive \nRequest\n instances in your view, and adding context to \nResponse\n objects so that content negotiation can be performed.\n\n\nThe wrappers also provide behaviour such as returning \n405 Method Not Allowed\n responses when appropriate, and handling any \nParseError\n exception that occurs when accessing \nrequest.data\n with malformed input.\n\n\nPulling it all together\n\n\nOkay, let's go ahead and start using these new components to write a few views.\n\n\nWe don't need our \nJSONResponse\n class in \nviews.py\n anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    elif request.method == 'POST':\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nOur instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.\n\n\nHere is the view for an individual snippet, in the \nviews.py\n module.\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, pk):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(pk=pk)\n    except Snippet.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    elif request.method == 'PUT':\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThis should all feel very familiar - it is not a lot different from working with regular Django views.\n\n\nNotice that we're no longer explicitly tying our requests or responses to a given content type.  \nrequest.data\n can handle incoming \njson\n 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.\n\n\nAdding optional format suffixes to our URLs\n\n\nTo 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 \nhttp://example.com/api/items/4.json\n.\n\n\nStart by adding a \nformat\n keyword argument to both of the views, like so.\n\n\ndef snippet_list(request, format=None):\n\n\n\nand\n\n\ndef snippet_detail(request, pk, format=None):\n\n\n\nNow update the \nurls.py\n file slightly, to append a set of \nformat_suffix_patterns\n in addition to the existing URLs.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P\npk\n[0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nWe 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.\n\n\nHow's it looking?\n\n\nGo ahead and test the API from the command line, as we did in \ntutorial part 1\n.  Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.\n\n\nWe can get a list of all of the snippets, as before.\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n  {\n    \"id\": 1,\n    \"title\": \"\",\n    \"code\": \"foo = \\\"bar\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"\",\n    \"code\": \"print \\\"hello, world\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  }\n]\n\n\n\nWe can control the format of the response that we get back, either by using the \nAccept\n header:\n\n\nhttp http://127.0.0.1:8000/snippets/ Accept:application/json  # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html         # Request HTML\n\n\n\nOr by appending a format suffix:\n\n\nhttp http://127.0.0.1:8000/snippets.json  # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api   # Browsable API suffix\n\n\n\nSimilarly, we can control the format of the request that we send, using the \nContent-Type\n header.\n\n\n# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n  \"id\": 3,\n  \"title\": \"\",\n  \"code\": \"print 123\",\n  \"linenos\": false,\n  \"language\": \"python\",\n  \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n    \"id\": 4,\n    \"title\": \"\",\n    \"code\": \"print 456\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nIf you add a \n--debug\n switch to the \nhttp\n requests above, you will be able to see the request type in request headers.\n\n\nNow go and open the API in a web browser, by visiting \nhttp://127.0.0.1:8000/snippets/\n.\n\n\nBrowsability\n\n\nBecause 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.\n\n\nHaving 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.\n\n\nSee the \nbrowsable api\n topic for more information about the browsable API feature and how to customize it.\n\n\nWhat's next?\n\n\nIn \ntutorial part 3\n, we'll start using class-based views, and see how generic views reduce the amount of code we need to write.", 
    +            "text": "Tutorial 2: Requests and Responses\n\n\nFrom this point we're going to really start covering the core of REST framework.\nLet's introduce a couple of essential building blocks.\n\n\nRequest objects\n\n\nREST framework introduces a \nRequest\n object that extends the regular \nHttpRequest\n, and provides more flexible request parsing.  The core functionality of the \nRequest\n object is the \nrequest.data\n attribute, which is similar to \nrequest.POST\n, but more useful for working with Web APIs.\n\n\nrequest.POST  # Only handles form data.  Only works for 'POST' method.\nrequest.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.\n\n\n\nResponse objects\n\n\nREST framework also introduces a \nResponse\n object, which is a type of \nTemplateResponse\n that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.\n\n\nreturn Response(data)  # Renders to content type as requested by the client.\n\n\n\nStatus codes\n\n\nUsing 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 \nHTTP_400_BAD_REQUEST\n in the \nstatus\n module.  It's a good idea to use these throughout rather than using numeric identifiers.\n\n\nWrapping API views\n\n\nREST framework provides two wrappers you can use to write API views.\n\n\n\n\nThe \n@api_view\n decorator for working with function based views.\n\n\nThe \nAPIView\n class for working with class-based views.\n\n\n\n\nThese wrappers provide a few bits of functionality such as making sure you receive \nRequest\n instances in your view, and adding context to \nResponse\n objects so that content negotiation can be performed.\n\n\nThe wrappers also provide behaviour such as returning \n405 Method Not Allowed\n responses when appropriate, and handling any \nParseError\n exception that occurs when accessing \nrequest.data\n with malformed input.\n\n\nPulling it all together\n\n\nOkay, let's go ahead and start using these new components to write a few views.\n\n\nWe don't need our \nJSONResponse\n class in \nviews.py\n anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    elif request.method == 'POST':\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nOur instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.\n\n\nHere is the view for an individual snippet, in the \nviews.py\n module.\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, id):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(id=id)\n    except Snippet.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    elif request.method == 'PUT':\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThis should all feel very familiar - it is not a lot different from working with regular Django views.\n\n\nNotice that we're no longer explicitly tying our requests or responses to a given content type.  \nrequest.data\n can handle incoming \njson\n 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.\n\n\nAdding optional format suffixes to our URLs\n\n\nTo 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 \nhttp://example.com/api/items/4.json\n.\n\n\nStart by adding a \nformat\n keyword argument to both of the views, like so.\n\n\ndef snippet_list(request, format=None):\n\n\n\nand\n\n\ndef snippet_detail(request, id, format=None):\n\n\n\nNow update the \nurls.py\n file slightly, to append a set of \nformat_suffix_patterns\n in addition to the existing URLs.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P\nid\n[0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nWe 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.\n\n\nHow's it looking?\n\n\nGo ahead and test the API from the command line, as we did in \ntutorial part 1\n.  Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.\n\n\nWe can get a list of all of the snippets, as before.\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n  {\n    \"id\": 1,\n    \"title\": \"\",\n    \"code\": \"foo = \\\"bar\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  },\n  {\n    \"id\": 2,\n    \"title\": \"\",\n    \"code\": \"print \\\"hello, world\\\"\\n\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n  }\n]\n\n\n\nWe can control the format of the response that we get back, either by using the \nAccept\n header:\n\n\nhttp http://127.0.0.1:8000/snippets/ Accept:application/json  # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html         # Request HTML\n\n\n\nOr by appending a format suffix:\n\n\nhttp http://127.0.0.1:8000/snippets.json  # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api   # Browsable API suffix\n\n\n\nSimilarly, we can control the format of the request that we send, using the \nContent-Type\n header.\n\n\n# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n  \"id\": 3,\n  \"title\": \"\",\n  \"code\": \"print 123\",\n  \"linenos\": false,\n  \"language\": \"python\",\n  \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n    \"id\": 4,\n    \"title\": \"\",\n    \"code\": \"print 456\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nIf you add a \n--debug\n switch to the \nhttp\n requests above, you will be able to see the request type in request headers.\n\n\nNow go and open the API in a web browser, by visiting \nhttp://127.0.0.1:8000/snippets/\n.\n\n\nBrowsability\n\n\nBecause 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.\n\n\nHaving 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.\n\n\nSee the \nbrowsable api\n topic for more information about the browsable API feature and how to customize it.\n\n\nWhat's next?\n\n\nIn \ntutorial part 3\n, we'll start using class-based views, and see how generic views reduce the amount of code we need to write.", 
                 "title": "2 - Requests and responses"
             }, 
             {
    @@ -197,12 +197,12 @@
             }, 
             {
                 "location": "/tutorial/2-requests-and-responses/#pulling-it-all-together", 
    -            "text": "Okay, let's go ahead and start using these new components to write a few views.  We don't need our  JSONResponse  class in  views.py  anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.  from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    elif request.method == 'POST':\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  Our instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.  Here is the view for an individual snippet, in the  views.py  module.  @api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, pk):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(pk=pk)\n    except Snippet.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    elif request.method == 'PUT':\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)  This should all feel very familiar - it is not a lot different from working with regular Django views.  Notice that we're no longer explicitly tying our requests or responses to a given content type.   request.data  can handle incoming  json  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.", 
    +            "text": "Okay, let's go ahead and start using these new components to write a few views.  We don't need our  JSONResponse  class in  views.py  anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.  from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    if request.method == 'GET':\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    elif request.method == 'POST':\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  Our instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.  Here is the view for an individual snippet, in the  views.py  module.  @api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, id):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    try:\n        snippet = Snippet.objects.get(id=id)\n    except Snippet.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    if request.method == 'GET':\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    elif request.method == 'PUT':\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'DELETE':\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)  This should all feel very familiar - it is not a lot different from working with regular Django views.  Notice that we're no longer explicitly tying our requests or responses to a given content type.   request.data  can handle incoming  json  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.", 
                 "title": "Pulling it all together"
             }, 
             {
                 "location": "/tutorial/2-requests-and-responses/#adding-optional-format-suffixes-to-our-urls", 
    -            "text": "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  http://example.com/api/items/4.json .  Start by adding a  format  keyword argument to both of the views, like so.  def snippet_list(request, format=None):  and  def snippet_detail(request, pk, format=None):  Now update the  urls.py  file slightly, to append a set of  format_suffix_patterns  in addition to the existing URLs.  from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P pk [0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)  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.", 
    +            "text": "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  http://example.com/api/items/4.json .  Start by adding a  format  keyword argument to both of the views, like so.  def snippet_list(request, format=None):  and  def snippet_detail(request, id, format=None):  Now update the  urls.py  file slightly, to append a set of  format_suffix_patterns  in addition to the existing URLs.  from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.snippet_list),\n    url(r'^snippets/(?P id [0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)  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.", 
                 "title": "Adding optional format suffixes to our URLs"
             }, 
             {
    @@ -222,7 +222,7 @@
             }, 
             {
                 "location": "/tutorial/3-class-based-views/", 
    -            "text": "Tutorial 3: Class-based Views\n\n\nWe 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 \nDRY\n.\n\n\nRewriting our API using class-based views\n\n\nWe'll start by rewriting the root view as a class-based view.  All this involves is a little bit of refactoring of \nviews.py\n.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    def get(self, request, format=None):\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    def post(self, request, format=None):\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nSo far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in \nviews.py\n.\n\n\nclass SnippetDetail(APIView):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    def get_object(self, pk):\n        try:\n            return Snippet.objects.get(pk=pk)\n        except Snippet.DoesNotExist:\n            raise Http404\n\n    def get(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    def put(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    def delete(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThat's looking good.  Again, it's still pretty similar to the function based view right now.\n\n\nWe'll also need to refactor our \nurls.py\n slightly now we're using class-based views.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.SnippetList.as_view()),\n    url(r'^snippets/(?P\npk\n[0-9]+)/$', views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nOkay, we're done.  If you run the development server everything should be working just as before.\n\n\nUsing mixins\n\n\nOne of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.\n\n\nThe 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.\n\n\nLet's take a look at how we can compose the views by using the mixin classes.  Here's our \nviews.py\n module again.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import mixins\nfrom rest_framework import generics\n\nclass SnippetList(mixins.ListModelMixin,\n                  mixins.CreateModelMixin,\n                  generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n    def get(self, request, *args, **kwargs):\n        return self.list(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        return self.create(request, *args, **kwargs)\n\n\n\nWe'll take a moment to examine exactly what's happening here.  We're building our view using \nGenericAPIView\n, and adding in \nListModelMixin\n and \nCreateModelMixin\n.\n\n\nThe base class provides the core functionality, and the mixin classes provide the \n.list()\n and \n.create()\n actions.  We're then explicitly binding the \nget\n and \npost\n methods to the appropriate actions.  Simple enough stuff so far.\n\n\nclass SnippetDetail(mixins.RetrieveModelMixin,\n                    mixins.UpdateModelMixin,\n                    mixins.DestroyModelMixin,\n                    generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n    def get(self, request, *args, **kwargs):\n        return self.retrieve(request, *args, **kwargs)\n\n    def put(self, request, *args, **kwargs):\n        return self.update(request, *args, **kwargs)\n\n    def delete(self, request, *args, **kwargs):\n        return self.destroy(request, *args, **kwargs)\n\n\n\nPretty similar.  Again we're using the \nGenericAPIView\n class to provide the core functionality, and adding in mixins to provide the \n.retrieve()\n, \n.update()\n and \n.destroy()\n actions.\n\n\nUsing generic class-based views\n\n\nUsing 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 \nviews.py\n module even more.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import generics\n\n\nclass SnippetList(generics.ListCreateAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n\nclass SnippetDetail(generics.RetrieveUpdateDestroyAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n\n\nWow, that's pretty concise.  We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.\n\n\nNext we'll move onto \npart 4 of the tutorial\n, where we'll take a look at how we can deal with authentication and permissions for our API.", 
    +            "text": "Tutorial 3: Class-based Views\n\n\nWe 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 \nDRY\n.\n\n\nRewriting our API using class-based views\n\n\nWe'll start by rewriting the root view as a class-based view.  All this involves is a little bit of refactoring of \nviews.py\n.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    def get(self, request, format=None):\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    def post(self, request, format=None):\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nSo far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in \nviews.py\n.\n\n\nclass SnippetDetail(APIView):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    def get_object(self, id):\n        try:\n            return Snippet.objects.get(id=id)\n        except Snippet.DoesNotExist:\n            raise Http404\n\n    def get(self, request, id, format=None):\n        snippet = self.get_object(id)\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    def put(self, request, id, format=None):\n        snippet = self.get_object(id)\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    def delete(self, request, id, format=None):\n        snippet = self.get_object(id)\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThat's looking good.  Again, it's still pretty similar to the function based view right now.\n\n\nWe'll also need to refactor our \nurls.py\n slightly now we're using class-based views.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.SnippetList.as_view()),\n    url(r'^snippets/(?P\nid\n[0-9]+)/$', views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nOkay, we're done.  If you run the development server everything should be working just as before.\n\n\nUsing mixins\n\n\nOne of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.\n\n\nThe 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.\n\n\nLet's take a look at how we can compose the views by using the mixin classes.  Here's our \nviews.py\n module again.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import mixins\nfrom rest_framework import generics\n\nclass SnippetList(mixins.ListModelMixin,\n                  mixins.CreateModelMixin,\n                  generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n    def get(self, request, *args, **kwargs):\n        return self.list(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        return self.create(request, *args, **kwargs)\n\n\n\nWe'll take a moment to examine exactly what's happening here.  We're building our view using \nGenericAPIView\n, and adding in \nListModelMixin\n and \nCreateModelMixin\n.\n\n\nThe base class provides the core functionality, and the mixin classes provide the \n.list()\n and \n.create()\n actions.  We're then explicitly binding the \nget\n and \npost\n methods to the appropriate actions.  Simple enough stuff so far.\n\n\nclass SnippetDetail(mixins.RetrieveModelMixin,\n                    mixins.UpdateModelMixin,\n                    mixins.DestroyModelMixin,\n                    generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n    def get(self, request, *args, **kwargs):\n        return self.retrieve(request, *args, **kwargs)\n\n    def put(self, request, *args, **kwargs):\n        return self.update(request, *args, **kwargs)\n\n    def delete(self, request, *args, **kwargs):\n        return self.destroy(request, *args, **kwargs)\n\n\n\nPretty similar.  Again we're using the \nGenericAPIView\n class to provide the core functionality, and adding in mixins to provide the \n.retrieve()\n, \n.update()\n and \n.destroy()\n actions.\n\n\nUsing generic class-based views\n\n\nUsing 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 \nviews.py\n module even more.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import generics\n\n\nclass SnippetList(generics.ListCreateAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n\nclass SnippetDetail(generics.RetrieveUpdateDestroyAPIView):\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n\n\n\nWow, that's pretty concise.  We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.\n\n\nNext we'll move onto \npart 4 of the tutorial\n, where we'll take a look at how we can deal with authentication and permissions for our API.", 
                 "title": "3 - Class based views"
             }, 
             {
    @@ -232,7 +232,7 @@
             }, 
             {
                 "location": "/tutorial/3-class-based-views/#rewriting-our-api-using-class-based-views", 
    -            "text": "We'll start by rewriting the root view as a class-based view.  All this involves is a little bit of refactoring of  views.py .  from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    def get(self, request, format=None):\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    def post(self, request, format=None):\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  So far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in  views.py .  class SnippetDetail(APIView):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    def get_object(self, pk):\n        try:\n            return Snippet.objects.get(pk=pk)\n        except Snippet.DoesNotExist:\n            raise Http404\n\n    def get(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    def put(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    def delete(self, request, pk, format=None):\n        snippet = self.get_object(pk)\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)  That's looking good.  Again, it's still pretty similar to the function based view right now.  We'll also need to refactor our  urls.py  slightly now we're using class-based views.  from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.SnippetList.as_view()),\n    url(r'^snippets/(?P pk [0-9]+)/$', views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)  Okay, we're done.  If you run the development server everything should be working just as before.", 
    +            "text": "We'll start by rewriting the root view as a class-based view.  All this involves is a little bit of refactoring of  views.py .  from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n    \"\"\"\n    List all snippets, or create a new snippet.\n    \"\"\"\n    def get(self, request, format=None):\n        snippets = Snippet.objects.all()\n        serializer = SnippetSerializer(snippets, many=True)\n        return Response(serializer.data)\n\n    def post(self, request, format=None):\n        serializer = SnippetSerializer(data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  So far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in  views.py .  class SnippetDetail(APIView):\n    \"\"\"\n    Retrieve, update or delete a snippet instance.\n    \"\"\"\n    def get_object(self, id):\n        try:\n            return Snippet.objects.get(id=id)\n        except Snippet.DoesNotExist:\n            raise Http404\n\n    def get(self, request, id, format=None):\n        snippet = self.get_object(id)\n        serializer = SnippetSerializer(snippet)\n        return Response(serializer.data)\n\n    def put(self, request, id, format=None):\n        snippet = self.get_object(id)\n        serializer = SnippetSerializer(snippet, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    def delete(self, request, id, format=None):\n        snippet = self.get_object(id)\n        snippet.delete()\n        return Response(status=status.HTTP_204_NO_CONTENT)  That's looking good.  Again, it's still pretty similar to the function based view right now.  We'll also need to refactor our  urls.py  slightly now we're using class-based views.  from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n    url(r'^snippets/$', views.SnippetList.as_view()),\n    url(r'^snippets/(?P id [0-9]+)/$', views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)  Okay, we're done.  If you run the development server everything should be working just as before.", 
                 "title": "Rewriting our API using class-based views"
             }, 
             {
    @@ -247,7 +247,7 @@
             }, 
             {
                 "location": "/tutorial/4-authentication-and-permissions/", 
    -            "text": "Tutorial 4: Authentication \n Permissions\n\n\nCurrently 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:\n\n\n\n\nCode snippets are always associated with a creator.\n\n\nOnly authenticated users may create snippets.\n\n\nOnly the creator of a snippet may update or delete it.\n\n\nUnauthenticated requests should have full read-only access.\n\n\n\n\nAdding information to our model\n\n\nWe're going to make a couple of changes to our \nSnippet\n model class.\nFirst, 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.\n\n\nAdd the following two fields to the \nSnippet\n model in \nmodels.py\n.\n\n\nowner = models.ForeignKey('auth.User', related_name='snippets')\nhighlighted = models.TextField()\n\n\n\nWe'd also need to make sure that when the model is saved, that we populate the highlighted field, using the \npygments\n code highlighting library.\n\n\nWe'll need some extra imports:\n\n\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.formatters.html import HtmlFormatter\nfrom pygments import highlight\n\n\n\nAnd now we can add a \n.save()\n method to our model class:\n\n\ndef save(self, *args, **kwargs):\n    \"\"\"\n    Use the `pygments` library to create a highlighted HTML\n    representation of the code snippet.\n    \"\"\"\n    lexer = get_lexer_by_name(self.language)\n    linenos = self.linenos and 'table' or False\n    options = self.title and {'title': self.title} or {}\n    formatter = HtmlFormatter(style=self.style, linenos=linenos,\n                              full=True, **options)\n    self.highlighted = highlight(self.code, lexer, formatter)\n    super(Snippet, self).save(*args, **kwargs)\n\n\n\nWhen that's all done we'll need to update our database tables.\nNormally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.\n\n\nrm -f tmp.db db.sqlite3\nrm -r snippets/migrations\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nYou 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 \ncreatesuperuser\n command.\n\n\npython manage.py createsuperuser\n\n\n\nAdding endpoints for our User models\n\n\nNow 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 \nserializers.py\n add:\n\n\nfrom django.contrib.auth.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n\n    class Meta:\n        model = User\n        fields = ('id', 'username', 'snippets')\n\n\n\nBecause \n'snippets'\n is a \nreverse\n relationship on the User model, it will not be included by default when using the \nModelSerializer\n class, so we needed to add an explicit field for it.\n\n\nWe'll also add a couple of views to \nviews.py\n.  We'd like to just use read-only views for the user representations, so we'll use the \nListAPIView\n and \nRetrieveAPIView\n generic class-based views.\n\n\nfrom django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\n\nMake sure to also import the \nUserSerializer\n class\n\n\nfrom snippets.serializers import UserSerializer\n\n\n\nFinally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in \nurls.py\n.\n\n\nurl(r'^users/$', views.UserList.as_view()),\nurl(r'^users/(?P\npk\n[0-9]+)/$', views.UserDetail.as_view()),\n\n\n\nAssociating Snippets with Users\n\n\nRight 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.\n\n\nThe way we deal with that is by overriding a \n.perform_create()\n 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.\n\n\nOn the \nSnippetList\n view class, add the following method:\n\n\ndef perform_create(self, serializer):\n    serializer.save(owner=self.request.user)\n\n\n\nThe \ncreate()\n method of our serializer will now be passed an additional \n'owner'\n field, along with the validated data from the request.\n\n\nUpdating our serializer\n\n\nNow that snippets are associated with the user that created them, let's update our \nSnippetSerializer\n to reflect that.  Add the following field to the serializer definition in \nserializers.py\n:\n\n\nowner = serializers.ReadOnlyField(source='owner.username')\n\n\n\nNote\n: Make sure you also add \n'owner',\n to the list of fields in the inner \nMeta\n class.\n\n\nThis field is doing something quite interesting.  The \nsource\n 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.\n\n\nThe field we've added is the untyped \nReadOnlyField\n class, in contrast to the other typed fields, such as \nCharField\n, \nBooleanField\n etc...  The untyped \nReadOnlyField\n 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 \nCharField(read_only=True)\n here.\n\n\nAdding required permissions to views\n\n\nNow 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.\n\n\nREST 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 \nIsAuthenticatedOrReadOnly\n, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.\n\n\nFirst add the following import in the views module\n\n\nfrom rest_framework import permissions\n\n\n\nThen, add the following property to \nboth\n the \nSnippetList\n and \nSnippetDetail\n view classes.\n\n\npermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\n\nAdding login to the Browsable API\n\n\nIf 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.\n\n\nWe can add a login view for use with the browsable API, by editing the URLconf in our project-level \nurls.py\n file.\n\n\nAdd the following import at the top of the file:\n\n\nfrom django.conf.urls import include\n\n\n\nAnd, at the end of the file, add a pattern to include the login and logout views for the browsable API.\n\n\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]\n\n\n\nThe \nr'^api-auth/'\n part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the \n'rest_framework'\n namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.\n\n\nNow 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.\n\n\nOnce 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.\n\n\nObject level permissions\n\n\nReally 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.\n\n\nTo do that we're going to need to create a custom permission.\n\n\nIn the snippets app, create a new file, \npermissions.py\n\n\nfrom rest_framework import permissions\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n    \"\"\"\n    Custom permission to only allow owners of an object to edit it.\n    \"\"\"\n\n    def has_object_permission(self, request, view, obj):\n        # Read permissions are allowed to any request,\n        # so we'll always allow GET, HEAD or OPTIONS requests.\n        if request.method in permissions.SAFE_METHODS:\n            return True\n\n        # Write permissions are only allowed to the owner of the snippet.\n        return obj.owner == request.user\n\n\n\nNow we can add that custom permission to our snippet instance endpoint, by editing the \npermission_classes\n property on the \nSnippetDetail\n view class:\n\n\npermission_classes = (permissions.IsAuthenticatedOrReadOnly,\n                      IsOwnerOrReadOnly,)\n\n\n\nMake sure to also import the \nIsOwnerOrReadOnly\n class.\n\n\nfrom snippets.permissions import IsOwnerOrReadOnly\n\n\n\nNow, 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.\n\n\nAuthenticating with the API\n\n\nBecause 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 \nauthentication classes\n, so the defaults are currently applied, which are \nSessionAuthentication\n and \nBasicAuthentication\n.\n\n\nWhen 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.\n\n\nIf we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.\n\n\nIf we try to create a snippet without authenticating, we'll get an error:\n\n\nhttp POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n    \"detail\": \"Authentication credentials were not provided.\"\n}\n\n\n\nWe can make a successful request by including the username and password of one of the users we created earlier.\n\n\nhttp -a tom:password123 POST http://127.0.0.1:8000/snippets/ code=\"print 789\"\n\n{\n    \"id\": 5,\n    \"owner\": \"tom\",\n    \"title\": \"foo\",\n    \"code\": \"print 789\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nSummary\n\n\nWe'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.\n\n\nIn \npart 5\n 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.", 
    +            "text": "Tutorial 4: Authentication \n Permissions\n\n\nCurrently 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:\n\n\n\n\nCode snippets are always associated with a creator.\n\n\nOnly authenticated users may create snippets.\n\n\nOnly the creator of a snippet may update or delete it.\n\n\nUnauthenticated requests should have full read-only access.\n\n\n\n\nAdding information to our model\n\n\nWe're going to make a couple of changes to our \nSnippet\n model class.\nFirst, 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.\n\n\nAdd the following two fields to the \nSnippet\n model in \nmodels.py\n.\n\n\nowner = models.ForeignKey('auth.User', related_name='snippets')\nhighlighted = models.TextField()\n\n\n\nWe'd also need to make sure that when the model is saved, that we populate the highlighted field, using the \npygments\n code highlighting library.\n\n\nWe'll need some extra imports:\n\n\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.formatters.html import HtmlFormatter\nfrom pygments import highlight\n\n\n\nAnd now we can add a \n.save()\n method to our model class:\n\n\ndef save(self, *args, **kwargs):\n    \"\"\"\n    Use the `pygments` library to create a highlighted HTML\n    representation of the code snippet.\n    \"\"\"\n    lexer = get_lexer_by_name(self.language)\n    linenos = self.linenos and 'table' or False\n    options = self.title and {'title': self.title} or {}\n    formatter = HtmlFormatter(style=self.style, linenos=linenos,\n                              full=True, **options)\n    self.highlighted = highlight(self.code, lexer, formatter)\n    super(Snippet, self).save(*args, **kwargs)\n\n\n\nWhen that's all done we'll need to update our database tables.\nNormally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.\n\n\nrm -f tmp.db db.sqlite3\nrm -r snippets/migrations\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nYou 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 \ncreatesuperuser\n command.\n\n\npython manage.py createsuperuser\n\n\n\nAdding endpoints for our User models\n\n\nNow 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 \nserializers.py\n add:\n\n\nfrom django.contrib.auth.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n\n    class Meta:\n        model = User\n        fields = ('id', 'username', 'snippets')\n\n\n\nBecause \n'snippets'\n is a \nreverse\n relationship on the User model, it will not be included by default when using the \nModelSerializer\n class, so we needed to add an explicit field for it.\n\n\nWe'll also add a couple of views to \nviews.py\n.  We'd like to just use read-only views for the user representations, so we'll use the \nListAPIView\n and \nRetrieveAPIView\n generic class-based views.\n\n\nfrom django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\n\nMake sure to also import the \nUserSerializer\n class\n\n\nfrom snippets.serializers import UserSerializer\n\n\n\nFinally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in \nurls.py\n.\n\n\nurl(r'^users/$', views.UserList.as_view()),\nurl(r'^users/(?P\nid\n[0-9]+)/$', views.UserDetail.as_view()),\n\n\n\nAssociating Snippets with Users\n\n\nRight 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.\n\n\nThe way we deal with that is by overriding a \n.perform_create()\n 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.\n\n\nOn the \nSnippetList\n view class, add the following method:\n\n\ndef perform_create(self, serializer):\n    serializer.save(owner=self.request.user)\n\n\n\nThe \ncreate()\n method of our serializer will now be passed an additional \n'owner'\n field, along with the validated data from the request.\n\n\nUpdating our serializer\n\n\nNow that snippets are associated with the user that created them, let's update our \nSnippetSerializer\n to reflect that.  Add the following field to the serializer definition in \nserializers.py\n:\n\n\nowner = serializers.ReadOnlyField(source='owner.username')\n\n\n\nNote\n: Make sure you also add \n'owner',\n to the list of fields in the inner \nMeta\n class.\n\n\nThis field is doing something quite interesting.  The \nsource\n 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.\n\n\nThe field we've added is the untyped \nReadOnlyField\n class, in contrast to the other typed fields, such as \nCharField\n, \nBooleanField\n etc...  The untyped \nReadOnlyField\n 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 \nCharField(read_only=True)\n here.\n\n\nAdding required permissions to views\n\n\nNow 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.\n\n\nREST 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 \nIsAuthenticatedOrReadOnly\n, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.\n\n\nFirst add the following import in the views module\n\n\nfrom rest_framework import permissions\n\n\n\nThen, add the following property to \nboth\n the \nSnippetList\n and \nSnippetDetail\n view classes.\n\n\npermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\n\nAdding login to the Browsable API\n\n\nIf 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.\n\n\nWe can add a login view for use with the browsable API, by editing the URLconf in our project-level \nurls.py\n file.\n\n\nAdd the following import at the top of the file:\n\n\nfrom django.conf.urls import include\n\n\n\nAnd, at the end of the file, add a pattern to include the login and logout views for the browsable API.\n\n\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]\n\n\n\nThe \nr'^api-auth/'\n part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the \n'rest_framework'\n namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.\n\n\nNow 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.\n\n\nOnce you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.\n\n\nObject level permissions\n\n\nReally 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.\n\n\nTo do that we're going to need to create a custom permission.\n\n\nIn the snippets app, create a new file, \npermissions.py\n\n\nfrom rest_framework import permissions\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n    \"\"\"\n    Custom permission to only allow owners of an object to edit it.\n    \"\"\"\n\n    def has_object_permission(self, request, view, obj):\n        # Read permissions are allowed to any request,\n        # so we'll always allow GET, HEAD or OPTIONS requests.\n        if request.method in permissions.SAFE_METHODS:\n            return True\n\n        # Write permissions are only allowed to the owner of the snippet.\n        return obj.owner == request.user\n\n\n\nNow we can add that custom permission to our snippet instance endpoint, by editing the \npermission_classes\n property on the \nSnippetDetail\n view class:\n\n\npermission_classes = (permissions.IsAuthenticatedOrReadOnly,\n                      IsOwnerOrReadOnly,)\n\n\n\nMake sure to also import the \nIsOwnerOrReadOnly\n class.\n\n\nfrom snippets.permissions import IsOwnerOrReadOnly\n\n\n\nNow, 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.\n\n\nAuthenticating with the API\n\n\nBecause 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 \nauthentication classes\n, so the defaults are currently applied, which are \nSessionAuthentication\n and \nBasicAuthentication\n.\n\n\nWhen 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.\n\n\nIf we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.\n\n\nIf we try to create a snippet without authenticating, we'll get an error:\n\n\nhttp POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n    \"detail\": \"Authentication credentials were not provided.\"\n}\n\n\n\nWe can make a successful request by including the username and password of one of the users we created earlier.\n\n\nhttp -a tom:password123 POST http://127.0.0.1:8000/snippets/ code=\"print 789\"\n\n{\n    \"id\": 5,\n    \"owner\": \"tom\",\n    \"title\": \"foo\",\n    \"code\": \"print 789\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nSummary\n\n\nWe'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.\n\n\nIn \npart 5\n 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.", 
                 "title": "4 - Authentication and permissions"
             }, 
             {
    @@ -262,7 +262,7 @@
             }, 
             {
                 "location": "/tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models", 
    -            "text": "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  serializers.py  add:  from django.contrib.auth.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n\n    class Meta:\n        model = User\n        fields = ('id', 'username', 'snippets')  Because  'snippets'  is a  reverse  relationship on the User model, it will not be included by default when using the  ModelSerializer  class, so we needed to add an explicit field for it.  We'll also add a couple of views to  views.py .  We'd like to just use read-only views for the user representations, so we'll use the  ListAPIView  and  RetrieveAPIView  generic class-based views.  from django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer  Make sure to also import the  UserSerializer  class  from snippets.serializers import UserSerializer  Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in  urls.py .  url(r'^users/$', views.UserList.as_view()),\nurl(r'^users/(?P pk [0-9]+)/$', views.UserDetail.as_view()),", 
    +            "text": "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  serializers.py  add:  from django.contrib.auth.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n\n    class Meta:\n        model = User\n        fields = ('id', 'username', 'snippets')  Because  'snippets'  is a  reverse  relationship on the User model, it will not be included by default when using the  ModelSerializer  class, so we needed to add an explicit field for it.  We'll also add a couple of views to  views.py .  We'd like to just use read-only views for the user representations, so we'll use the  ListAPIView  and  RetrieveAPIView  generic class-based views.  from django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer  Make sure to also import the  UserSerializer  class  from snippets.serializers import UserSerializer  Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in  urls.py .  url(r'^users/$', views.UserList.as_view()),\nurl(r'^users/(?P id [0-9]+)/$', views.UserDetail.as_view()),", 
                 "title": "Adding endpoints for our User models"
             }, 
             {
    @@ -282,7 +282,7 @@
             }, 
             {
                 "location": "/tutorial/4-authentication-and-permissions/#adding-login-to-the-browsable-api", 
    -            "text": "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.  We can add a login view for use with the browsable API, by editing the URLconf in our project-level  urls.py  file.  Add the following import at the top of the file:  from django.conf.urls import include  And, at the end of the file, add a pattern to include the login and logout views for the browsable API.  urlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]  The  r'^api-auth/'  part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the  'rest_framework'  namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.  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.  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.", 
    +            "text": "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.  We can add a login view for use with the browsable API, by editing the URLconf in our project-level  urls.py  file.  Add the following import at the top of the file:  from django.conf.urls import include  And, at the end of the file, add a pattern to include the login and logout views for the browsable API.  urlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]  The  r'^api-auth/'  part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the  'rest_framework'  namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.  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.  Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.", 
                 "title": "Adding login to the Browsable API"
             }, 
             {
    @@ -302,7 +302,7 @@
             }, 
             {
                 "location": "/tutorial/5-relationships-and-hyperlinked-apis/", 
    -            "text": "Tutorial 5: Relationships \n Hyperlinked APIs\n\n\nAt 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.\n\n\nCreating an endpoint for the root of our API\n\n\nRight 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 \n@api_view\n decorator we introduced earlier. In your \nsnippets/views.py\n add:\n\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\n\n@api_view(['GET'])\ndef api_root(request, format=None):\n    return Response({\n        'users': reverse('user-list', request=request, format=format),\n        'snippets': reverse('snippet-list', request=request, format=format)\n    })\n\n\n\nTwo things should be noticed here. First, we're using REST framework's \nreverse\n function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our \nsnippets/urls.py\n.\n\n\nCreating an endpoint for the highlighted snippets\n\n\nThe other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.\n\n\nUnlike 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.\n\n\nThe 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.\n\n\nInstead of using a concrete generic view, we'll use the base class for representing instances, and create our own \n.get()\n method.  In your \nsnippets/views.py\n add:\n\n\nfrom rest_framework import renderers\nfrom rest_framework.response import Response\n\nclass SnippetHighlight(generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    renderer_classes = (renderers.StaticHTMLRenderer,)\n\n    def get(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)\n\n\n\nAs usual we need to add the new views that we've created in to our URLconf.\nWe'll add a url pattern for our new API root in \nsnippets/urls.py\n:\n\n\nurl(r'^$', views.api_root),\n\n\n\nAnd then add a url pattern for the snippet highlights:\n\n\nurl(r'^snippets/(?P\npk\n[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),\n\n\n\nHyperlinking our API\n\n\nDealing 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:\n\n\n\n\nUsing primary keys.\n\n\nUsing hyperlinking between entities.\n\n\nUsing a unique identifying slug field on the related entity.\n\n\nUsing the default string representation of the related entity.\n\n\nNesting the related entity inside the parent representation.\n\n\nSome other custom representation.\n\n\n\n\nREST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.\n\n\nIn this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend \nHyperlinkedModelSerializer\n instead of the existing \nModelSerializer\n.\n\n\nThe \nHyperlinkedModelSerializer\n has the following differences from \nModelSerializer\n:\n\n\n\n\nIt does not include the \npk\n field by default.\n\n\nIt includes a \nurl\n field, using \nHyperlinkedIdentityField\n.\n\n\nRelationships use \nHyperlinkedRelatedField\n,\n  instead of \nPrimaryKeyRelatedField\n.\n\n\n\n\nWe can easily re-write our existing serializers to use hyperlinking. In your \nsnippets/serializers.py\n add:\n\n\nclass SnippetSerializer(serializers.HyperlinkedModelSerializer):\n    owner = serializers.ReadOnlyField(source='owner.username')\n    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')\n\n    class Meta:\n        model = Snippet\n        fields = ('url', 'pk', 'highlight', 'owner',\n                  'title', 'code', 'linenos', 'language', 'style')\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)\n\n    class Meta:\n        model = User\n        fields = ('url', 'pk', 'username', 'snippets')\n\n\n\nNotice that we've also added a new \n'highlight'\n field.  This field is of the same type as the \nurl\n field, except that it points to the \n'snippet-highlight'\n url pattern, instead of the \n'snippet-detail'\n url pattern.\n\n\nBecause we've included format suffixed URLs such as \n'.json'\n, we also need to indicate on the \nhighlight\n field that any format suffixed hyperlinks it returns should use the \n'.html'\n suffix.\n\n\nMaking sure our URL patterns are named\n\n\nIf 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.\n\n\n\n\nThe root of our API refers to \n'user-list'\n and \n'snippet-list'\n.\n\n\nOur snippet serializer includes a field that refers to \n'snippet-highlight'\n.\n\n\nOur user serializer includes a field that refers to \n'snippet-detail'\n.\n\n\nOur snippet and user serializers include \n'url'\n fields that by default will refer to \n'{model_name}-detail'\n, which in this case will be \n'snippet-detail'\n and \n'user-detail'\n.\n\n\n\n\nAfter adding all those names into our URLconf, our final \nsnippets/urls.py\n file should look like this:\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns([\n    url(r'^$', views.api_root),\n    url(r'^snippets/$',\n        views.SnippetList.as_view(),\n        name='snippet-list'),\n    url(r'^snippets/(?P\npk\n[0-9]+)/$',\n        views.SnippetDetail.as_view(),\n        name='snippet-detail'),\n    url(r'^snippets/(?P\npk\n[0-9]+)/highlight/$',\n        views.SnippetHighlight.as_view(),\n        name='snippet-highlight'),\n    url(r'^users/$',\n        views.UserList.as_view(),\n        name='user-list'),\n    url(r'^users/(?P\npk\n[0-9]+)/$',\n        views.UserDetail.as_view(),\n        name='user-detail')\n])\n\n# Login and logout views for the browsable API\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]\n\n\n\nAdding pagination\n\n\nThe 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.\n\n\nWe can change the default list style to use pagination, by modifying our \ntutorial/settings.py\n file slightly.  Add the following setting:\n\n\nREST_FRAMEWORK = {\n    'PAGE_SIZE': 10\n}\n\n\n\nNote 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.\n\n\nWe could also customize the pagination style if we needed too, but in this case we'll just stick with the default.\n\n\nBrowsing the API\n\n\nIf 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.\n\n\nYou'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.\n\n\nIn \npart 6\n 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.", 
    +            "text": "Tutorial 5: Relationships \n Hyperlinked APIs\n\n\nAt 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.\n\n\nCreating an endpoint for the root of our API\n\n\nRight 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 \n@api_view\n decorator we introduced earlier. In your \nsnippets/views.py\n add:\n\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\n\n@api_view(['GET'])\ndef api_root(request, format=None):\n    return Response({\n        'users': reverse('user-list', request=request, format=format),\n        'snippets': reverse('snippet-list', request=request, format=format)\n    })\n\n\n\nTwo things should be noticed here. First, we're using REST framework's \nreverse\n function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our \nsnippets/urls.py\n.\n\n\nCreating an endpoint for the highlighted snippets\n\n\nThe other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.\n\n\nUnlike 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.\n\n\nThe 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.\n\n\nInstead of using a concrete generic view, we'll use the base class for representing instances, and create our own \n.get()\n method.  In your \nsnippets/views.py\n add:\n\n\nfrom rest_framework import renderers\nfrom rest_framework.response import Response\n\nclass SnippetHighlight(generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    renderer_classes = (renderers.StaticHTMLRenderer,)\n\n    def get(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)\n\n\n\nAs usual we need to add the new views that we've created in to our URLconf.\nWe'll add a url pattern for our new API root in \nsnippets/urls.py\n:\n\n\nurl(r'^$', views.api_root),\n\n\n\nAnd then add a url pattern for the snippet highlights:\n\n\nurl(r'^snippets/(?P\nid\n[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),\n\n\n\nHyperlinking our API\n\n\nDealing 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:\n\n\n\n\nUsing primary keys.\n\n\nUsing hyperlinking between entities.\n\n\nUsing a unique identifying slug field on the related entity.\n\n\nUsing the default string representation of the related entity.\n\n\nNesting the related entity inside the parent representation.\n\n\nSome other custom representation.\n\n\n\n\nREST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.\n\n\nIn this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend \nHyperlinkedModelSerializer\n instead of the existing \nModelSerializer\n.\n\n\nThe \nHyperlinkedModelSerializer\n has the following differences from \nModelSerializer\n:\n\n\n\n\nIt does not include the \nid\n field by default.\n\n\nIt includes a \nurl\n field, using \nHyperlinkedIdentityField\n.\n\n\nRelationships use \nHyperlinkedRelatedField\n,\n  instead of \nPrimaryKeyRelatedField\n.\n\n\n\n\nWe can easily re-write our existing serializers to use hyperlinking. In your \nsnippets/serializers.py\n add:\n\n\nclass SnippetSerializer(serializers.HyperlinkedModelSerializer):\n    owner = serializers.ReadOnlyField(source='owner.username')\n    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')\n\n    class Meta:\n        model = Snippet\n        fields = ('url', 'id', 'highlight', 'owner',\n                  'title', 'code', 'linenos', 'language', 'style')\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)\n\n    class Meta:\n        model = User\n        fields = ('url', 'id', 'username', 'snippets')\n\n\n\nNotice that we've also added a new \n'highlight'\n field.  This field is of the same type as the \nurl\n field, except that it points to the \n'snippet-highlight'\n url pattern, instead of the \n'snippet-detail'\n url pattern.\n\n\nBecause we've included format suffixed URLs such as \n'.json'\n, we also need to indicate on the \nhighlight\n field that any format suffixed hyperlinks it returns should use the \n'.html'\n suffix.\n\n\nMaking sure our URL patterns are named\n\n\nIf 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.\n\n\n\n\nThe root of our API refers to \n'user-list'\n and \n'snippet-list'\n.\n\n\nOur snippet serializer includes a field that refers to \n'snippet-highlight'\n.\n\n\nOur user serializer includes a field that refers to \n'snippet-detail'\n.\n\n\nOur snippet and user serializers include \n'url'\n fields that by default will refer to \n'{model_name}-detail'\n, which in this case will be \n'snippet-detail'\n and \n'user-detail'\n.\n\n\n\n\nAfter adding all those names into our URLconf, our final \nsnippets/urls.py\n file should look like this:\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns([\n    url(r'^$', views.api_root),\n    url(r'^snippets/$',\n        views.SnippetList.as_view(),\n        name='snippet-list'),\n    url(r'^snippets/(?P\nid\n[0-9]+)/$',\n        views.SnippetDetail.as_view(),\n        name='snippet-detail'),\n    url(r'^snippets/(?P\nid\n[0-9]+)/highlight/$',\n        views.SnippetHighlight.as_view(),\n        name='snippet-highlight'),\n    url(r'^users/$',\n        views.UserList.as_view(),\n        name='user-list'),\n    url(r'^users/(?P\nid\n[0-9]+)/$',\n        views.UserDetail.as_view(),\n        name='user-detail')\n])\n\n# Login and logout views for the browsable API\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]\n\n\n\nAdding pagination\n\n\nThe 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.\n\n\nWe can change the default list style to use pagination, by modifying our \ntutorial/settings.py\n file slightly.  Add the following setting:\n\n\nREST_FRAMEWORK = {\n    'PAGE_SIZE': 10\n}\n\n\n\nNote 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.\n\n\nWe could also customize the pagination style if we needed too, but in this case we'll just stick with the default.\n\n\nBrowsing the API\n\n\nIf 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.\n\n\nYou'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.\n\n\nIn \npart 6\n 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.", 
                 "title": "5 - Relationships and hyperlinked APIs"
             }, 
             {
    @@ -317,17 +317,17 @@
             }, 
             {
                 "location": "/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-highlighted-snippets", 
    -            "text": "The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.  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.  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.  Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own  .get()  method.  In your  snippets/views.py  add:  from rest_framework import renderers\nfrom rest_framework.response import Response\n\nclass SnippetHighlight(generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    renderer_classes = (renderers.StaticHTMLRenderer,)\n\n    def get(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)  As usual we need to add the new views that we've created in to our URLconf.\nWe'll add a url pattern for our new API root in  snippets/urls.py :  url(r'^$', views.api_root),  And then add a url pattern for the snippet highlights:  url(r'^snippets/(?P pk [0-9]+)/highlight/$', views.SnippetHighlight.as_view()),", 
    +            "text": "The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.  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.  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.  Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own  .get()  method.  In your  snippets/views.py  add:  from rest_framework import renderers\nfrom rest_framework.response import Response\n\nclass SnippetHighlight(generics.GenericAPIView):\n    queryset = Snippet.objects.all()\n    renderer_classes = (renderers.StaticHTMLRenderer,)\n\n    def get(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)  As usual we need to add the new views that we've created in to our URLconf.\nWe'll add a url pattern for our new API root in  snippets/urls.py :  url(r'^$', views.api_root),  And then add a url pattern for the snippet highlights:  url(r'^snippets/(?P id [0-9]+)/highlight/$', views.SnippetHighlight.as_view()),", 
                 "title": "Creating an endpoint for the highlighted snippets"
             }, 
             {
                 "location": "/tutorial/5-relationships-and-hyperlinked-apis/#hyperlinking-our-api", 
    -            "text": "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:   Using primary keys.  Using hyperlinking between entities.  Using a unique identifying slug field on the related entity.  Using the default string representation of the related entity.  Nesting the related entity inside the parent representation.  Some other custom representation.   REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.  In this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend  HyperlinkedModelSerializer  instead of the existing  ModelSerializer .  The  HyperlinkedModelSerializer  has the following differences from  ModelSerializer :   It does not include the  pk  field by default.  It includes a  url  field, using  HyperlinkedIdentityField .  Relationships use  HyperlinkedRelatedField ,\n  instead of  PrimaryKeyRelatedField .   We can easily re-write our existing serializers to use hyperlinking. In your  snippets/serializers.py  add:  class SnippetSerializer(serializers.HyperlinkedModelSerializer):\n    owner = serializers.ReadOnlyField(source='owner.username')\n    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')\n\n    class Meta:\n        model = Snippet\n        fields = ('url', 'pk', 'highlight', 'owner',\n                  'title', 'code', 'linenos', 'language', 'style')\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)\n\n    class Meta:\n        model = User\n        fields = ('url', 'pk', 'username', 'snippets')  Notice that we've also added a new  'highlight'  field.  This field is of the same type as the  url  field, except that it points to the  'snippet-highlight'  url pattern, instead of the  'snippet-detail'  url pattern.  Because we've included format suffixed URLs such as  '.json' , we also need to indicate on the  highlight  field that any format suffixed hyperlinks it returns should use the  '.html'  suffix.", 
    +            "text": "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:   Using primary keys.  Using hyperlinking between entities.  Using a unique identifying slug field on the related entity.  Using the default string representation of the related entity.  Nesting the related entity inside the parent representation.  Some other custom representation.   REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.  In this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend  HyperlinkedModelSerializer  instead of the existing  ModelSerializer .  The  HyperlinkedModelSerializer  has the following differences from  ModelSerializer :   It does not include the  id  field by default.  It includes a  url  field, using  HyperlinkedIdentityField .  Relationships use  HyperlinkedRelatedField ,\n  instead of  PrimaryKeyRelatedField .   We can easily re-write our existing serializers to use hyperlinking. In your  snippets/serializers.py  add:  class SnippetSerializer(serializers.HyperlinkedModelSerializer):\n    owner = serializers.ReadOnlyField(source='owner.username')\n    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')\n\n    class Meta:\n        model = Snippet\n        fields = ('url', 'id', 'highlight', 'owner',\n                  'title', 'code', 'linenos', 'language', 'style')\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)\n\n    class Meta:\n        model = User\n        fields = ('url', 'id', 'username', 'snippets')  Notice that we've also added a new  'highlight'  field.  This field is of the same type as the  url  field, except that it points to the  'snippet-highlight'  url pattern, instead of the  'snippet-detail'  url pattern.  Because we've included format suffixed URLs such as  '.json' , we also need to indicate on the  highlight  field that any format suffixed hyperlinks it returns should use the  '.html'  suffix.", 
                 "title": "Hyperlinking our API"
             }, 
             {
                 "location": "/tutorial/5-relationships-and-hyperlinked-apis/#making-sure-our-url-patterns-are-named", 
    -            "text": "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.   The root of our API refers to  'user-list'  and  'snippet-list' .  Our snippet serializer includes a field that refers to  'snippet-highlight' .  Our user serializer includes a field that refers to  'snippet-detail' .  Our snippet and user serializers include  'url'  fields that by default will refer to  '{model_name}-detail' , which in this case will be  'snippet-detail'  and  'user-detail' .   After adding all those names into our URLconf, our final  snippets/urls.py  file should look like this:  from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns([\n    url(r'^$', views.api_root),\n    url(r'^snippets/$',\n        views.SnippetList.as_view(),\n        name='snippet-list'),\n    url(r'^snippets/(?P pk [0-9]+)/$',\n        views.SnippetDetail.as_view(),\n        name='snippet-detail'),\n    url(r'^snippets/(?P pk [0-9]+)/highlight/$',\n        views.SnippetHighlight.as_view(),\n        name='snippet-highlight'),\n    url(r'^users/$',\n        views.UserList.as_view(),\n        name='user-list'),\n    url(r'^users/(?P pk [0-9]+)/$',\n        views.UserDetail.as_view(),\n        name='user-detail')\n])\n\n# Login and logout views for the browsable API\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]", 
    +            "text": "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.   The root of our API refers to  'user-list'  and  'snippet-list' .  Our snippet serializer includes a field that refers to  'snippet-highlight' .  Our user serializer includes a field that refers to  'snippet-detail' .  Our snippet and user serializers include  'url'  fields that by default will refer to  '{model_name}-detail' , which in this case will be  'snippet-detail'  and  'user-detail' .   After adding all those names into our URLconf, our final  snippets/urls.py  file should look like this:  from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns([\n    url(r'^$', views.api_root),\n    url(r'^snippets/$',\n        views.SnippetList.as_view(),\n        name='snippet-list'),\n    url(r'^snippets/(?P id [0-9]+)/$',\n        views.SnippetDetail.as_view(),\n        name='snippet-detail'),\n    url(r'^snippets/(?P id [0-9]+)/highlight/$',\n        views.SnippetHighlight.as_view(),\n        name='snippet-highlight'),\n    url(r'^users/$',\n        views.UserList.as_view(),\n        name='user-list'),\n    url(r'^users/(?P id [0-9]+)/$',\n        views.UserDetail.as_view(),\n        name='user-detail')\n])\n\n# Login and logout views for the browsable API\nurlpatterns += [\n    url(r'^api-auth/', include('rest_framework.urls',\n                               namespace='rest_framework')),\n]", 
                 "title": "Making sure our URL patterns are named"
             }, 
             {
    @@ -342,7 +342,7 @@
             }, 
             {
                 "location": "/tutorial/6-viewsets-and-routers/", 
    -            "text": "Tutorial 6: ViewSets \n Routers\n\n\nREST framework includes an abstraction for dealing with \nViewSets\n, 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.\n\n\nViewSet\n classes are almost the same thing as \nView\n classes, except that they provide operations such as \nread\n, or \nupdate\n, and not method handlers such as \nget\n or \nput\n.\n\n\nA \nViewSet\n 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 \nRouter\n class which handles the complexities of defining the URL conf for you.\n\n\nRefactoring to use ViewSets\n\n\nLet's take our current set of views, and refactor them into view sets.\n\n\nFirst of all let's refactor our \nUserList\n and \nUserDetail\n views into a single \nUserViewSet\n.  We can remove the two views, and replace them with a single class:\n\n\nfrom rest_framework import viewsets\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n    \"\"\"\n    This viewset automatically provides `list` and `detail` actions.\n    \"\"\"\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\n\nHere we've used the \nReadOnlyModelViewSet\n class to automatically provide the default 'read-only' operations.  We're still setting the \nqueryset\n and \nserializer_class\n attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.\n\n\nNext we're going to replace the \nSnippetList\n, \nSnippetDetail\n and \nSnippetHighlight\n view classes.  We can remove the three views, and again replace them with a single class.\n\n\nfrom rest_framework.decorators import detail_route\n\nclass SnippetViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    This viewset automatically provides `list`, `create`, `retrieve`,\n    `update` and `destroy` actions.\n\n    Additionally we also provide an extra `highlight` action.\n    \"\"\"\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n    permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n                          IsOwnerOrReadOnly,)\n\n    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])\n    def highlight(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)\n\n    def perform_create(self, serializer):\n        serializer.save(owner=self.request.user)\n\n\n\nThis time we've used the \nModelViewSet\n class in order to get the complete set of default read and write operations.\n\n\nNotice that we've also used the \n@detail_route\n decorator to create a custom action, named \nhighlight\n.  This decorator can be used to add any custom endpoints that don't fit into the standard \ncreate\n/\nupdate\n/\ndelete\n style.\n\n\nCustom actions which use the \n@detail_route\n decorator will respond to \nGET\n requests.  We can use the \nmethods\n argument if we wanted an action that responded to \nPOST\n requests.\n\n\nThe 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.\n\n\nBinding ViewSets to URLs explicitly\n\n\nThe handler methods only get bound to the actions when we define the URLConf.\nTo see what's going on under the hood let's first explicitly create a set of views from our ViewSets.\n\n\nIn the \nurls.py\n file we bind our \nViewSet\n classes into a set of concrete views.\n\n\nfrom snippets.views import SnippetViewSet, UserViewSet, api_root\nfrom rest_framework import renderers\n\nsnippet_list = SnippetViewSet.as_view({\n    'get': 'list',\n    'post': 'create'\n})\nsnippet_detail = SnippetViewSet.as_view({\n    'get': 'retrieve',\n    'put': 'update',\n    'patch': 'partial_update',\n    'delete': 'destroy'\n})\nsnippet_highlight = SnippetViewSet.as_view({\n    'get': 'highlight'\n}, renderer_classes=[renderers.StaticHTMLRenderer])\nuser_list = UserViewSet.as_view({\n    'get': 'list'\n})\nuser_detail = UserViewSet.as_view({\n    'get': 'retrieve'\n})\n\n\n\nNotice how we're creating multiple views from each \nViewSet\n class, by binding the http methods to the required action for each view.\n\n\nNow that we've bound our resources into concrete views, we can register the views with the URL conf as usual.\n\n\nurlpatterns = format_suffix_patterns([\n    url(r'^$', api_root),\n    url(r'^snippets/$', snippet_list, name='snippet-list'),\n    url(r'^snippets/(?P\npk\n[0-9]+)/$', snippet_detail, name='snippet-detail'),\n    url(r'^snippets/(?P\npk\n[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n    url(r'^users/$', user_list, name='user-list'),\n    url(r'^users/(?P\npk\n[0-9]+)/$', user_detail, name='user-detail')\n])\n\n\n\nUsing Routers\n\n\nBecause we're using \nViewSet\n classes rather than \nView\n 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 \nRouter\n class.  All we need to do is register the appropriate view sets with a router, and let it do the rest.\n\n\nHere's our re-wired \nurls.py\n file.\n\n\nfrom django.conf.urls import url, include\nfrom snippets import views\nfrom rest_framework.routers import DefaultRouter\n\n# Create a router and register our viewsets with it.\nrouter = DefaultRouter()\nrouter.register(r'snippets', views.SnippetViewSet)\nrouter.register(r'users', views.UserViewSet)\n\n# The API URLs are now determined automatically by the router.\n# Additionally, we include the login URLs for the browsable API.\nurlpatterns = [\n    url(r'^', include(router.urls)),\n    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nRegistering 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.\n\n\nThe \nDefaultRouter\n class we're using also automatically creates the API root view for us, so we can now delete the \napi_root\n method from our \nviews\n module.\n\n\nTrade-offs between views vs viewsets\n\n\nUsing 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.\n\n\nThat 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.\n\n\nIn \npart 7\n of the tutorial we'll look at how we can add an API schema,\nand interact with our API using a client library or command line tool.", 
    +            "text": "Tutorial 6: ViewSets \n Routers\n\n\nREST framework includes an abstraction for dealing with \nViewSets\n, 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.\n\n\nViewSet\n classes are almost the same thing as \nView\n classes, except that they provide operations such as \nread\n, or \nupdate\n, and not method handlers such as \nget\n or \nput\n.\n\n\nA \nViewSet\n 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 \nRouter\n class which handles the complexities of defining the URL conf for you.\n\n\nRefactoring to use ViewSets\n\n\nLet's take our current set of views, and refactor them into view sets.\n\n\nFirst of all let's refactor our \nUserList\n and \nUserDetail\n views into a single \nUserViewSet\n.  We can remove the two views, and replace them with a single class:\n\n\nfrom rest_framework import viewsets\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n    \"\"\"\n    This viewset automatically provides `list` and `detail` actions.\n    \"\"\"\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n\n\nHere we've used the \nReadOnlyModelViewSet\n class to automatically provide the default 'read-only' operations.  We're still setting the \nqueryset\n and \nserializer_class\n attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.\n\n\nNext we're going to replace the \nSnippetList\n, \nSnippetDetail\n and \nSnippetHighlight\n view classes.  We can remove the three views, and again replace them with a single class.\n\n\nfrom rest_framework.decorators import detail_route\n\nclass SnippetViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    This viewset automatically provides `list`, `create`, `retrieve`,\n    `update` and `destroy` actions.\n\n    Additionally we also provide an extra `highlight` action.\n    \"\"\"\n    queryset = Snippet.objects.all()\n    serializer_class = SnippetSerializer\n    permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n                          IsOwnerOrReadOnly,)\n\n    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])\n    def highlight(self, request, *args, **kwargs):\n        snippet = self.get_object()\n        return Response(snippet.highlighted)\n\n    def perform_create(self, serializer):\n        serializer.save(owner=self.request.user)\n\n\n\nThis time we've used the \nModelViewSet\n class in order to get the complete set of default read and write operations.\n\n\nNotice that we've also used the \n@detail_route\n decorator to create a custom action, named \nhighlight\n.  This decorator can be used to add any custom endpoints that don't fit into the standard \ncreate\n/\nupdate\n/\ndelete\n style.\n\n\nCustom actions which use the \n@detail_route\n decorator will respond to \nGET\n requests.  We can use the \nmethods\n argument if we wanted an action that responded to \nPOST\n requests.\n\n\nThe 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.\n\n\nBinding ViewSets to URLs explicitly\n\n\nThe handler methods only get bound to the actions when we define the URLConf.\nTo see what's going on under the hood let's first explicitly create a set of views from our ViewSets.\n\n\nIn the \nurls.py\n file we bind our \nViewSet\n classes into a set of concrete views.\n\n\nfrom snippets.views import SnippetViewSet, UserViewSet, api_root\nfrom rest_framework import renderers\n\nsnippet_list = SnippetViewSet.as_view({\n    'get': 'list',\n    'post': 'create'\n})\nsnippet_detail = SnippetViewSet.as_view({\n    'get': 'retrieve',\n    'put': 'update',\n    'patch': 'partial_update',\n    'delete': 'destroy'\n})\nsnippet_highlight = SnippetViewSet.as_view({\n    'get': 'highlight'\n}, renderer_classes=[renderers.StaticHTMLRenderer])\nuser_list = UserViewSet.as_view({\n    'get': 'list'\n})\nuser_detail = UserViewSet.as_view({\n    'get': 'retrieve'\n})\n\n\n\nNotice how we're creating multiple views from each \nViewSet\n class, by binding the http methods to the required action for each view.\n\n\nNow that we've bound our resources into concrete views, we can register the views with the URL conf as usual.\n\n\nurlpatterns = format_suffix_patterns([\n    url(r'^$', api_root),\n    url(r'^snippets/$', snippet_list, name='snippet-list'),\n    url(r'^snippets/(?P\nid\n[0-9]+)/$', snippet_detail, name='snippet-detail'),\n    url(r'^snippets/(?P\nid\n[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n    url(r'^users/$', user_list, name='user-list'),\n    url(r'^users/(?P\nid\n[0-9]+)/$', user_detail, name='user-detail')\n])\n\n\n\nUsing Routers\n\n\nBecause we're using \nViewSet\n classes rather than \nView\n 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 \nRouter\n class.  All we need to do is register the appropriate view sets with a router, and let it do the rest.\n\n\nHere's our re-wired \nurls.py\n file.\n\n\nfrom django.conf.urls import url, include\nfrom snippets import views\nfrom rest_framework.routers import DefaultRouter\n\n# Create a router and register our viewsets with it.\nrouter = DefaultRouter()\nrouter.register(r'snippets', views.SnippetViewSet)\nrouter.register(r'users', views.UserViewSet)\n\n# The API URLs are now determined automatically by the router.\n# Additionally, we include the login URLs for the browsable API.\nurlpatterns = [\n    url(r'^', include(router.urls)),\n    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nRegistering 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.\n\n\nThe \nDefaultRouter\n class we're using also automatically creates the API root view for us, so we can now delete the \napi_root\n method from our \nviews\n module.\n\n\nTrade-offs between views vs viewsets\n\n\nUsing 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.\n\n\nThat 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.\n\n\nIn \npart 7\n of the tutorial we'll look at how we can add an API schema,\nand interact with our API using a client library or command line tool.", 
                 "title": "6 - Viewsets and routers"
             }, 
             {
    @@ -357,7 +357,7 @@
             }, 
             {
                 "location": "/tutorial/6-viewsets-and-routers/#binding-viewsets-to-urls-explicitly", 
    -            "text": "The handler methods only get bound to the actions when we define the URLConf.\nTo see what's going on under the hood let's first explicitly create a set of views from our ViewSets.  In the  urls.py  file we bind our  ViewSet  classes into a set of concrete views.  from snippets.views import SnippetViewSet, UserViewSet, api_root\nfrom rest_framework import renderers\n\nsnippet_list = SnippetViewSet.as_view({\n    'get': 'list',\n    'post': 'create'\n})\nsnippet_detail = SnippetViewSet.as_view({\n    'get': 'retrieve',\n    'put': 'update',\n    'patch': 'partial_update',\n    'delete': 'destroy'\n})\nsnippet_highlight = SnippetViewSet.as_view({\n    'get': 'highlight'\n}, renderer_classes=[renderers.StaticHTMLRenderer])\nuser_list = UserViewSet.as_view({\n    'get': 'list'\n})\nuser_detail = UserViewSet.as_view({\n    'get': 'retrieve'\n})  Notice how we're creating multiple views from each  ViewSet  class, by binding the http methods to the required action for each view.  Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.  urlpatterns = format_suffix_patterns([\n    url(r'^$', api_root),\n    url(r'^snippets/$', snippet_list, name='snippet-list'),\n    url(r'^snippets/(?P pk [0-9]+)/$', snippet_detail, name='snippet-detail'),\n    url(r'^snippets/(?P pk [0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n    url(r'^users/$', user_list, name='user-list'),\n    url(r'^users/(?P pk [0-9]+)/$', user_detail, name='user-detail')\n])", 
    +            "text": "The handler methods only get bound to the actions when we define the URLConf.\nTo see what's going on under the hood let's first explicitly create a set of views from our ViewSets.  In the  urls.py  file we bind our  ViewSet  classes into a set of concrete views.  from snippets.views import SnippetViewSet, UserViewSet, api_root\nfrom rest_framework import renderers\n\nsnippet_list = SnippetViewSet.as_view({\n    'get': 'list',\n    'post': 'create'\n})\nsnippet_detail = SnippetViewSet.as_view({\n    'get': 'retrieve',\n    'put': 'update',\n    'patch': 'partial_update',\n    'delete': 'destroy'\n})\nsnippet_highlight = SnippetViewSet.as_view({\n    'get': 'highlight'\n}, renderer_classes=[renderers.StaticHTMLRenderer])\nuser_list = UserViewSet.as_view({\n    'get': 'list'\n})\nuser_detail = UserViewSet.as_view({\n    'get': 'retrieve'\n})  Notice how we're creating multiple views from each  ViewSet  class, by binding the http methods to the required action for each view.  Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.  urlpatterns = format_suffix_patterns([\n    url(r'^$', api_root),\n    url(r'^snippets/$', snippet_list, name='snippet-list'),\n    url(r'^snippets/(?P id [0-9]+)/$', snippet_detail, name='snippet-detail'),\n    url(r'^snippets/(?P id [0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n    url(r'^users/$', user_list, name='user-list'),\n    url(r'^users/(?P id [0-9]+)/$', user_detail, name='user-detail')\n])", 
                 "title": "Binding ViewSets to URLs explicitly"
             }, 
             {
    @@ -372,7 +372,7 @@
             }, 
             {
                 "location": "/tutorial/7-schemas-and-client-libraries/", 
    -            "text": "Tutorial 7: Schemas \n client libraries\n\n\nA schema is a machine-readable document that describes the available API\nendpoints, their URLS, and what operations they support.\n\n\nSchemas can be a useful tool for auto-generated documentation, and can also\nbe used to drive dynamic client libraries that can interact with the API.\n\n\nCore API\n\n\nIn order to provide schema support REST framework uses \nCore API\n.\n\n\nCore API is a document specification for describing APIs. It is used to provide\nan internal representation format of the available endpoints and possible\ninteractions that an API exposes. It can either be used server-side, or\nclient-side.\n\n\nWhen used server-side, Core API allows an API to support rendering to a wide\nrange of schema or hypermedia formats.\n\n\nWhen used client-side, Core API allows for dynamically driven client libraries\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nAdding a schema\n\n\nREST framework supports either explicitly defined schema views, or\nautomatically generated schemas. Since we're using viewsets and routers,\nwe can simply use the automatic schema generation.\n\n\nYou'll need to install the \ncoreapi\n python package in order to include an\nAPI schema.\n\n\n$ pip install coreapi\n\n\n\nWe can now include a schema for our API, by adding a \nschema_title\n argument to\nthe router instantiation.\n\n\nrouter = DefaultRouter(schema_title='Pastebin API')\n\n\n\nIf you visit the API root endpoint in a browser you should now see \ncorejson\n\nrepresentation become available as an option.\n\n\n\n\nWe can also request the schema from the command line, by specifying the desired\ncontent type in the \nAccept\n header.\n\n\n$ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Pastebin API\"\n    },\n    \"_type\": \"document\",\n    ...\n\n\n\nThe default output style is to use the \nCore JSON\n encoding.\n\n\nOther schema formats, such as \nOpen API\n (formerly Swagger) are\nalso supported.\n\n\nUsing a command line client\n\n\nNow that our API is exposing a schema endpoint, we can use a dynamic client\nlibrary to interact with the API. To demonstrate this, let's use the\nCore API command line client.\n\n\nThe command line client is available as the \ncoreapi-cli\n package:\n\n\n$ pip install coreapi-cli\n\n\n\nNow check that it is available on the command line...\n\n\n$ coreapi\nUsage: coreapi [OPTIONS] COMMAND [ARGS]...\n\n  Command line client for interacting with CoreAPI services.\n\n  Visit http://www.coreapi.org for more information.\n\nOptions:\n  --version  Display the package version number.\n  --help     Show this message and exit.\n\nCommands:\n...\n\n\n\nFirst we'll load the API schema using the command line client.\n\n\n$ coreapi get http://127.0.0.1:8000/\n\nPastebin API \"http://127.0.0.1:8000/\"\n\n    snippets: {\n        highlight(pk)\n        list()\n        retrieve(pk)\n    }\n    users: {\n        list()\n        retrieve(pk)\n    }\n\n\n\nWe haven't authenticated yet, so right now we're only able to see the read only\nendpoints, in line with how we've set up the permissions on the API.\n\n\nLet's try listing the existing snippets, using the command line client:\n\n\n$ coreapi action snippets list\n[\n    {\n        \"url\": \"http://127.0.0.1:8000/snippets/1/\",\n        \"pk\": 1,\n        \"highlight\": \"http://127.0.0.1:8000/snippets/1/highlight/\",\n        \"owner\": \"lucy\",\n        \"title\": \"Example\",\n        \"code\": \"print('hello, world!')\",\n        \"linenos\": true,\n        \"language\": \"python\",\n        \"style\": \"friendly\"\n    },\n    ...\n\n\n\nSome of the API endpoints require named parameters. For example, to get back\nthe highlight HTML for a particular snippet we need to provide an id.\n\n\n$ coreapi action snippets highlight --param pk=1\n\n!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"\n\n\n\nhtml\n\n\nhead\n\n  \ntitle\nExample\n/title\n\n  ...\n\n\n\nAuthenticating our client\n\n\nIf we want to be able to create, edit and delete snippets, we'll need to\nauthenticate as a valid user. In this case we'll just use basic auth.\n\n\nMake sure to replace the \nusername\n and \npassword\n below with your\nactual username and password.\n\n\n$ coreapi credentials add 127.0.0.1 \nusername\n:\npassword\n --auth basic\nAdded credentials\n127.0.0.1 \"Basic \n...\n\"\n\n\n\nNow if we fetch the schema again, we should be able to see the full\nset of available interactions.\n\n\n$ coreapi reload\nPastebin API \"http://127.0.0.1:8000/\"\n\n    snippets: {\n        create(code, [title], [linenos], [language], [style])\n        destroy(pk)\n        highlight(pk)\n        list()\n        partial_update(pk, [title], [code], [linenos], [language], [style])\n        retrieve(pk)\n        update(pk, code, [title], [linenos], [language], [style])\n    }\n    users: {\n        list()\n        retrieve(pk)\n    }\n\n\n\nWe're now able to interact with these endpoints. For example, to create a new\nsnippet:\n\n\n$ coreapi action snippets create --param title=\"Example\" --param code=\"print('hello, world')\"\n{\n    \"url\": \"http://127.0.0.1:8000/snippets/7/\",\n    \"pk\": 7,\n    \"highlight\": \"http://127.0.0.1:8000/snippets/7/highlight/\",\n    \"owner\": \"lucy\",\n    \"title\": \"Example\",\n    \"code\": \"print('hello, world')\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nAnd to delete a snippet:\n\n\n$ coreapi action snippets destroy --param pk=7\n\n\n\nAs well as the command line client, developers can also interact with your\nAPI using client libraries. The Python client library is the first of these\nto be available, and a Javascript client library is planned to be released\nsoon.\n\n\nFor more details on customizing schema generation and using Core API\nclient libraries you'll need to refer to the full documentation.\n\n\nReviewing our work\n\n\nWith an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.\n\n\nWe'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.\n\n\nYou can review the final \ntutorial code\n on GitHub, or try out a live example in \nthe sandbox\n.\n\n\nOnwards and upwards\n\n\nWe'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:\n\n\n\n\nContribute on \nGitHub\n by reviewing and submitting issues, and making pull requests.\n\n\nJoin the \nREST framework discussion group\n, and help build the community.\n\n\nFollow \nthe author\n on Twitter and say hi.\n\n\n\n\nNow go build awesome things.", 
    +            "text": "Tutorial 7: Schemas \n client libraries\n\n\nA schema is a machine-readable document that describes the available API\nendpoints, their URLS, and what operations they support.\n\n\nSchemas can be a useful tool for auto-generated documentation, and can also\nbe used to drive dynamic client libraries that can interact with the API.\n\n\nCore API\n\n\nIn order to provide schema support REST framework uses \nCore API\n.\n\n\nCore API is a document specification for describing APIs. It is used to provide\nan internal representation format of the available endpoints and possible\ninteractions that an API exposes. It can either be used server-side, or\nclient-side.\n\n\nWhen used server-side, Core API allows an API to support rendering to a wide\nrange of schema or hypermedia formats.\n\n\nWhen used client-side, Core API allows for dynamically driven client libraries\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nAdding a schema\n\n\nREST framework supports either explicitly defined schema views, or\nautomatically generated schemas. Since we're using viewsets and routers,\nwe can simply use the automatic schema generation.\n\n\nYou'll need to install the \ncoreapi\n python package in order to include an\nAPI schema.\n\n\n$ pip install coreapi\n\n\n\nWe can now include a schema for our API, by including an autogenerated schema\nview in our URL configuration.\n\n\nfrom rest_framework.schemas import get_schema_view\n\nschema_view = get_schema_view(title='Pastebin API')\n\nurlpatterns = [\n    url('^schema/$', schema_view),\n    ...\n]\n\n\n\nIf you visit the API root endpoint in a browser you should now see \ncorejson\n\nrepresentation become available as an option.\n\n\n\n\nWe can also request the schema from the command line, by specifying the desired\ncontent type in the \nAccept\n header.\n\n\n$ http http://127.0.0.1:8000/schema/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Pastebin API\"\n    },\n    \"_type\": \"document\",\n    ...\n\n\n\nThe default output style is to use the \nCore JSON\n encoding.\n\n\nOther schema formats, such as \nOpen API\n (formerly Swagger) are\nalso supported.\n\n\nUsing a command line client\n\n\nNow that our API is exposing a schema endpoint, we can use a dynamic client\nlibrary to interact with the API. To demonstrate this, let's use the\nCore API command line client.\n\n\nThe command line client is available as the \ncoreapi-cli\n package:\n\n\n$ pip install coreapi-cli\n\n\n\nNow check that it is available on the command line...\n\n\n$ coreapi\nUsage: coreapi [OPTIONS] COMMAND [ARGS]...\n\n  Command line client for interacting with CoreAPI services.\n\n  Visit http://www.coreapi.org for more information.\n\nOptions:\n  --version  Display the package version number.\n  --help     Show this message and exit.\n\nCommands:\n...\n\n\n\nFirst we'll load the API schema using the command line client.\n\n\n$ coreapi get http://127.0.0.1:8000/schema/\n\nPastebin API \"http://127.0.0.1:8000/schema/\"\n\n    snippets: {\n        highlight(id)\n        list()\n        read(id)\n    }\n    users: {\n        list()\n        read(id)\n    }\n\n\n\nWe haven't authenticated yet, so right now we're only able to see the read only\nendpoints, in line with how we've set up the permissions on the API.\n\n\nLet's try listing the existing snippets, using the command line client:\n\n\n$ coreapi action snippets list\n[\n    {\n        \"url\": \"http://127.0.0.1:8000/snippets/1/\",\n        \"id\": 1,\n        \"highlight\": \"http://127.0.0.1:8000/snippets/1/highlight/\",\n        \"owner\": \"lucy\",\n        \"title\": \"Example\",\n        \"code\": \"print('hello, world!')\",\n        \"linenos\": true,\n        \"language\": \"python\",\n        \"style\": \"friendly\"\n    },\n    ...\n\n\n\nSome of the API endpoints require named parameters. For example, to get back\nthe highlight HTML for a particular snippet we need to provide an id.\n\n\n$ coreapi action snippets highlight --param id=1\n\n!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"\n\n\n\nhtml\n\n\nhead\n\n  \ntitle\nExample\n/title\n\n  ...\n\n\n\nAuthenticating our client\n\n\nIf we want to be able to create, edit and delete snippets, we'll need to\nauthenticate as a valid user. In this case we'll just use basic auth.\n\n\nMake sure to replace the \nusername\n and \npassword\n below with your\nactual username and password.\n\n\n$ coreapi credentials add 127.0.0.1 \nusername\n:\npassword\n --auth basic\nAdded credentials\n127.0.0.1 \"Basic \n...\n\"\n\n\n\nNow if we fetch the schema again, we should be able to see the full\nset of available interactions.\n\n\n$ coreapi reload\nPastebin API \"http://127.0.0.1:8000/schema/\"\n\n    snippets: {\n        create(code, [title], [linenos], [language], [style])\n        delete(id)\n        highlight(id)\n        list()\n        partial_update(id, [title], [code], [linenos], [language], [style])\n        read(id)\n        update(id, code, [title], [linenos], [language], [style])\n    }\n    users: {\n        list()\n        read(id)\n    }\n\n\n\nWe're now able to interact with these endpoints. For example, to create a new\nsnippet:\n\n\n$ coreapi action snippets create --param title=\"Example\" --param code=\"print('hello, world')\"\n{\n    \"url\": \"http://127.0.0.1:8000/snippets/7/\",\n    \"id\": 7,\n    \"highlight\": \"http://127.0.0.1:8000/snippets/7/highlight/\",\n    \"owner\": \"lucy\",\n    \"title\": \"Example\",\n    \"code\": \"print('hello, world')\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}\n\n\n\nAnd to delete a snippet:\n\n\n$ coreapi action snippets delete --param id=7\n\n\n\nAs well as the command line client, developers can also interact with your\nAPI using client libraries. The Python client library is the first of these\nto be available, and a Javascript client library is planned to be released\nsoon.\n\n\nFor more details on customizing schema generation and using Core API\nclient libraries you'll need to refer to the full documentation.\n\n\nReviewing our work\n\n\nWith an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.\n\n\nWe'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.\n\n\nYou can review the final \ntutorial code\n on GitHub, or try out a live example in \nthe sandbox\n.\n\n\nOnwards and upwards\n\n\nWe'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:\n\n\n\n\nContribute on \nGitHub\n by reviewing and submitting issues, and making pull requests.\n\n\nJoin the \nREST framework discussion group\n, and help build the community.\n\n\nFollow \nthe author\n on Twitter and say hi.\n\n\n\n\nNow go build awesome things.", 
                 "title": "7 - Schemas and client libraries"
             }, 
             {
    @@ -387,17 +387,17 @@
             }, 
             {
                 "location": "/tutorial/7-schemas-and-client-libraries/#adding-a-schema", 
    -            "text": "REST framework supports either explicitly defined schema views, or\nautomatically generated schemas. Since we're using viewsets and routers,\nwe can simply use the automatic schema generation.  You'll need to install the  coreapi  python package in order to include an\nAPI schema.  $ pip install coreapi  We can now include a schema for our API, by adding a  schema_title  argument to\nthe router instantiation.  router = DefaultRouter(schema_title='Pastebin API')  If you visit the API root endpoint in a browser you should now see  corejson \nrepresentation become available as an option.   We can also request the schema from the command line, by specifying the desired\ncontent type in the  Accept  header.  $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Pastebin API\"\n    },\n    \"_type\": \"document\",\n    ...  The default output style is to use the  Core JSON  encoding.  Other schema formats, such as  Open API  (formerly Swagger) are\nalso supported.", 
    +            "text": "REST framework supports either explicitly defined schema views, or\nautomatically generated schemas. Since we're using viewsets and routers,\nwe can simply use the automatic schema generation.  You'll need to install the  coreapi  python package in order to include an\nAPI schema.  $ pip install coreapi  We can now include a schema for our API, by including an autogenerated schema\nview in our URL configuration.  from rest_framework.schemas import get_schema_view\n\nschema_view = get_schema_view(title='Pastebin API')\n\nurlpatterns = [\n    url('^schema/$', schema_view),\n    ...\n]  If you visit the API root endpoint in a browser you should now see  corejson \nrepresentation become available as an option.   We can also request the schema from the command line, by specifying the desired\ncontent type in the  Accept  header.  $ http http://127.0.0.1:8000/schema/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Pastebin API\"\n    },\n    \"_type\": \"document\",\n    ...  The default output style is to use the  Core JSON  encoding.  Other schema formats, such as  Open API  (formerly Swagger) are\nalso supported.", 
                 "title": "Adding a schema"
             }, 
             {
                 "location": "/tutorial/7-schemas-and-client-libraries/#using-a-command-line-client", 
    -            "text": "Now that our API is exposing a schema endpoint, we can use a dynamic client\nlibrary to interact with the API. To demonstrate this, let's use the\nCore API command line client.  The command line client is available as the  coreapi-cli  package:  $ pip install coreapi-cli  Now check that it is available on the command line...  $ coreapi\nUsage: coreapi [OPTIONS] COMMAND [ARGS]...\n\n  Command line client for interacting with CoreAPI services.\n\n  Visit http://www.coreapi.org for more information.\n\nOptions:\n  --version  Display the package version number.\n  --help     Show this message and exit.\n\nCommands:\n...  First we'll load the API schema using the command line client.  $ coreapi get http://127.0.0.1:8000/ Pastebin API \"http://127.0.0.1:8000/\" \n    snippets: {\n        highlight(pk)\n        list()\n        retrieve(pk)\n    }\n    users: {\n        list()\n        retrieve(pk)\n    }  We haven't authenticated yet, so right now we're only able to see the read only\nendpoints, in line with how we've set up the permissions on the API.  Let's try listing the existing snippets, using the command line client:  $ coreapi action snippets list\n[\n    {\n        \"url\": \"http://127.0.0.1:8000/snippets/1/\",\n        \"pk\": 1,\n        \"highlight\": \"http://127.0.0.1:8000/snippets/1/highlight/\",\n        \"owner\": \"lucy\",\n        \"title\": \"Example\",\n        \"code\": \"print('hello, world!')\",\n        \"linenos\": true,\n        \"language\": \"python\",\n        \"style\": \"friendly\"\n    },\n    ...  Some of the API endpoints require named parameters. For example, to get back\nthe highlight HTML for a particular snippet we need to provide an id.  $ coreapi action snippets highlight --param pk=1 !DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"  html  head \n   title Example /title \n  ...", 
    +            "text": "Now that our API is exposing a schema endpoint, we can use a dynamic client\nlibrary to interact with the API. To demonstrate this, let's use the\nCore API command line client.  The command line client is available as the  coreapi-cli  package:  $ pip install coreapi-cli  Now check that it is available on the command line...  $ coreapi\nUsage: coreapi [OPTIONS] COMMAND [ARGS]...\n\n  Command line client for interacting with CoreAPI services.\n\n  Visit http://www.coreapi.org for more information.\n\nOptions:\n  --version  Display the package version number.\n  --help     Show this message and exit.\n\nCommands:\n...  First we'll load the API schema using the command line client.  $ coreapi get http://127.0.0.1:8000/schema/ Pastebin API \"http://127.0.0.1:8000/schema/\" \n    snippets: {\n        highlight(id)\n        list()\n        read(id)\n    }\n    users: {\n        list()\n        read(id)\n    }  We haven't authenticated yet, so right now we're only able to see the read only\nendpoints, in line with how we've set up the permissions on the API.  Let's try listing the existing snippets, using the command line client:  $ coreapi action snippets list\n[\n    {\n        \"url\": \"http://127.0.0.1:8000/snippets/1/\",\n        \"id\": 1,\n        \"highlight\": \"http://127.0.0.1:8000/snippets/1/highlight/\",\n        \"owner\": \"lucy\",\n        \"title\": \"Example\",\n        \"code\": \"print('hello, world!')\",\n        \"linenos\": true,\n        \"language\": \"python\",\n        \"style\": \"friendly\"\n    },\n    ...  Some of the API endpoints require named parameters. For example, to get back\nthe highlight HTML for a particular snippet we need to provide an id.  $ coreapi action snippets highlight --param id=1 !DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"  html  head \n   title Example /title \n  ...", 
                 "title": "Using a command line client"
             }, 
             {
                 "location": "/tutorial/7-schemas-and-client-libraries/#authenticating-our-client", 
    -            "text": "If we want to be able to create, edit and delete snippets, we'll need to\nauthenticate as a valid user. In this case we'll just use basic auth.  Make sure to replace the  username  and  password  below with your\nactual username and password.  $ coreapi credentials add 127.0.0.1  username : password  --auth basic\nAdded credentials\n127.0.0.1 \"Basic  ... \"  Now if we fetch the schema again, we should be able to see the full\nset of available interactions.  $ coreapi reload\nPastebin API \"http://127.0.0.1:8000/\" \n    snippets: {\n        create(code, [title], [linenos], [language], [style])\n        destroy(pk)\n        highlight(pk)\n        list()\n        partial_update(pk, [title], [code], [linenos], [language], [style])\n        retrieve(pk)\n        update(pk, code, [title], [linenos], [language], [style])\n    }\n    users: {\n        list()\n        retrieve(pk)\n    }  We're now able to interact with these endpoints. For example, to create a new\nsnippet:  $ coreapi action snippets create --param title=\"Example\" --param code=\"print('hello, world')\"\n{\n    \"url\": \"http://127.0.0.1:8000/snippets/7/\",\n    \"pk\": 7,\n    \"highlight\": \"http://127.0.0.1:8000/snippets/7/highlight/\",\n    \"owner\": \"lucy\",\n    \"title\": \"Example\",\n    \"code\": \"print('hello, world')\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}  And to delete a snippet:  $ coreapi action snippets destroy --param pk=7  As well as the command line client, developers can also interact with your\nAPI using client libraries. The Python client library is the first of these\nto be available, and a Javascript client library is planned to be released\nsoon.  For more details on customizing schema generation and using Core API\nclient libraries you'll need to refer to the full documentation.", 
    +            "text": "If we want to be able to create, edit and delete snippets, we'll need to\nauthenticate as a valid user. In this case we'll just use basic auth.  Make sure to replace the  username  and  password  below with your\nactual username and password.  $ coreapi credentials add 127.0.0.1  username : password  --auth basic\nAdded credentials\n127.0.0.1 \"Basic  ... \"  Now if we fetch the schema again, we should be able to see the full\nset of available interactions.  $ coreapi reload\nPastebin API \"http://127.0.0.1:8000/schema/\" \n    snippets: {\n        create(code, [title], [linenos], [language], [style])\n        delete(id)\n        highlight(id)\n        list()\n        partial_update(id, [title], [code], [linenos], [language], [style])\n        read(id)\n        update(id, code, [title], [linenos], [language], [style])\n    }\n    users: {\n        list()\n        read(id)\n    }  We're now able to interact with these endpoints. For example, to create a new\nsnippet:  $ coreapi action snippets create --param title=\"Example\" --param code=\"print('hello, world')\"\n{\n    \"url\": \"http://127.0.0.1:8000/snippets/7/\",\n    \"id\": 7,\n    \"highlight\": \"http://127.0.0.1:8000/snippets/7/highlight/\",\n    \"owner\": \"lucy\",\n    \"title\": \"Example\",\n    \"code\": \"print('hello, world')\",\n    \"linenos\": false,\n    \"language\": \"python\",\n    \"style\": \"friendly\"\n}  And to delete a snippet:  $ coreapi action snippets delete --param id=7  As well as the command line client, developers can also interact with your\nAPI using client libraries. The Python client library is the first of these\nto be available, and a Javascript client library is planned to be released\nsoon.  For more details on customizing schema generation and using Core API\nclient libraries you'll need to refer to the full documentation.", 
                 "title": "Authenticating our client"
             }, 
             {
    @@ -572,7 +572,7 @@
             }, 
             {
                 "location": "/api-guide/views/", 
    -            "text": "Class-based Views\n\n\n\n\nDjango's class-based views are a welcome departure from the old-style views.\n\n\n \nReinout van Rees\n\n\n\n\nREST framework provides an \nAPIView\n class, which subclasses Django's \nView\n class.\n\n\nAPIView\n classes are different from regular \nView\n classes in the following ways:\n\n\n\n\nRequests passed to the handler methods will be REST framework's \nRequest\n instances, not Django's \nHttpRequest\n instances.\n\n\nHandler methods may return REST framework's \nResponse\n, instead of Django's \nHttpResponse\n.  The view will manage content negotiation and setting the correct renderer on the response.\n\n\nAny \nAPIException\n exceptions will be caught and mediated into appropriate responses.\n\n\nIncoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.\n\n\n\n\nUsing the \nAPIView\n class is pretty much the same as using a regular \nView\n class, as usual, the incoming request is dispatched to an appropriate handler method such as \n.get()\n or \n.post()\n.  Additionally, a number of attributes may be set on the class that control various aspects of the API policy.\n\n\nFor example:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\n\nclass ListUsers(APIView):\n    \"\"\"\n    View to list all users in the system.\n\n    * Requires token authentication.\n    * Only admin users are able to access this view.\n    \"\"\"\n    authentication_classes = (authentication.TokenAuthentication,)\n    permission_classes = (permissions.IsAdminUser,)\n\n    def get(self, request, format=None):\n        \"\"\"\n        Return a list of all users.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)\n\n\n\nAPI policy attributes\n\n\nThe following attributes control the pluggable aspects of API views.\n\n\n.renderer_classes\n\n\n.parser_classes\n\n\n.authentication_classes\n\n\n.throttle_classes\n\n\n.permission_classes\n\n\n.content_negotiation_class\n\n\nAPI policy instantiation methods\n\n\nThe following methods are used by REST framework to instantiate the various pluggable API policies.  You won't typically need to override these methods.\n\n\n.get_renderers(self)\n\n\n.get_parsers(self)\n\n\n.get_authenticators(self)\n\n\n.get_throttles(self)\n\n\n.get_permissions(self)\n\n\n.get_content_negotiator(self)\n\n\nAPI policy implementation methods\n\n\nThe following methods are called before dispatching to the handler method.\n\n\n.check_permissions(self, request)\n\n\n.check_throttles(self, request)\n\n\n.perform_content_negotiation(self, request, force=False)\n\n\nDispatch methods\n\n\nThe following methods are called directly by the view's \n.dispatch()\n method.\nThese perform any actions that need to occur before or after calling the handler methods such as \n.get()\n, \n.post()\n, \nput()\n, \npatch()\n and \n.delete()\n.\n\n\n.initial(self, request, *args, **kwargs)\n\n\nPerforms any actions that need to occur before the handler method gets called.\nThis method is used to enforce permissions and throttling, and perform content negotiation.\n\n\nYou won't typically need to override this method.\n\n\n.handle_exception(self, exc)\n\n\nAny exception thrown by the handler method will be passed to this method, which either returns a \nResponse\n instance, or re-raises the exception.\n\n\nThe default implementation handles any subclass of \nrest_framework.exceptions.APIException\n, as well as Django's \nHttp404\n and \nPermissionDenied\n exceptions, and returns an appropriate error response.\n\n\nIf you need to customize the error responses your API returns you should subclass this method.\n\n\n.initialize_request(self, request, *args, **kwargs)\n\n\nEnsures that the request object that is passed to the handler method is an instance of \nRequest\n, rather than the usual Django \nHttpRequest\n.\n\n\nYou won't typically need to override this method.\n\n\n.finalize_response(self, request, response, *args, **kwargs)\n\n\nEnsures that any \nResponse\n object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.\n\n\nYou won't typically need to override this method.\n\n\n\n\nFunction Based Views\n\n\n\n\nSaying [that class-based views] is always the superior solution is a mistake.\n\n\n \nNick Coghlan\n\n\n\n\nREST 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 \nRequest\n (rather than the usual Django \nHttpRequest\n) and allows them to return a \nResponse\n (instead of a Django \nHttpResponse\n), and allow you to configure how the request is processed.\n\n\n@api_view()\n\n\nSignature:\n \n@api_view(http_method_names=['GET'])\n\n\nThe core of this functionality is the \napi_view\n 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:\n\n\nfrom rest_framework.decorators import api_view\n\n@api_view()\ndef hello_world(request):\n    return Response({\"message\": \"Hello, world!\"})\n\n\n\nThis view will use the default renderers, parsers, authentication classes etc specified in the \nsettings\n.\n\n\nBy default only \nGET\n methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behavior, specify which methods the view allows, like so:\n\n\n@api_view(['GET', 'POST'])\ndef hello_world(request):\n    if request.method == 'POST':\n        return Response({\"message\": \"Got some data!\", \"data\": request.data})\n    return Response({\"message\": \"Hello, world!\"})\n\n\n\nAPI policy decorators\n\n\nTo override the default settings, REST framework provides a set of additional decorators which can be added to your views.  These must come \nafter\n (below) the \n@api_view\n decorator.  For example, to create a view that uses a \nthrottle\n to ensure it can only be called once per day by a particular user, use the \n@throttle_classes\n decorator, passing a list of throttle classes:\n\n\nfrom rest_framework.decorators import api_view, throttle_classes\nfrom rest_framework.throttling import UserRateThrottle\n\nclass OncePerDayUserThrottle(UserRateThrottle):\n        rate = '1/day'\n\n@api_view(['GET'])\n@throttle_classes([OncePerDayUserThrottle])\ndef view(request):\n    return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n\n\n\nThese decorators correspond to the attributes set on \nAPIView\n subclasses, described above.\n\n\nThe available decorators are:\n\n\n\n\n@renderer_classes(...)\n\n\n@parser_classes(...)\n\n\n@authentication_classes(...)\n\n\n@throttle_classes(...)\n\n\n@permission_classes(...)\n\n\n\n\nEach of these decorators takes a single argument which must be a list or tuple of classes.", 
    +            "text": "Class-based Views\n\n\n\n\nDjango's class-based views are a welcome departure from the old-style views.\n\n\n \nReinout van Rees\n\n\n\n\nREST framework provides an \nAPIView\n class, which subclasses Django's \nView\n class.\n\n\nAPIView\n classes are different from regular \nView\n classes in the following ways:\n\n\n\n\nRequests passed to the handler methods will be REST framework's \nRequest\n instances, not Django's \nHttpRequest\n instances.\n\n\nHandler methods may return REST framework's \nResponse\n, instead of Django's \nHttpResponse\n.  The view will manage content negotiation and setting the correct renderer on the response.\n\n\nAny \nAPIException\n exceptions will be caught and mediated into appropriate responses.\n\n\nIncoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.\n\n\n\n\nUsing the \nAPIView\n class is pretty much the same as using a regular \nView\n class, as usual, the incoming request is dispatched to an appropriate handler method such as \n.get()\n or \n.post()\n.  Additionally, a number of attributes may be set on the class that control various aspects of the API policy.\n\n\nFor example:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\n\nclass ListUsers(APIView):\n    \"\"\"\n    View to list all users in the system.\n\n    * Requires token authentication.\n    * Only admin users are able to access this view.\n    \"\"\"\n    authentication_classes = (authentication.TokenAuthentication,)\n    permission_classes = (permissions.IsAdminUser,)\n\n    def get(self, request, format=None):\n        \"\"\"\n        Return a list of all users.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)\n\n\n\nAPI policy attributes\n\n\nThe following attributes control the pluggable aspects of API views.\n\n\n.renderer_classes\n\n\n.parser_classes\n\n\n.authentication_classes\n\n\n.throttle_classes\n\n\n.permission_classes\n\n\n.content_negotiation_class\n\n\nAPI policy instantiation methods\n\n\nThe following methods are used by REST framework to instantiate the various pluggable API policies.  You won't typically need to override these methods.\n\n\n.get_renderers(self)\n\n\n.get_parsers(self)\n\n\n.get_authenticators(self)\n\n\n.get_throttles(self)\n\n\n.get_permissions(self)\n\n\n.get_content_negotiator(self)\n\n\nAPI policy implementation methods\n\n\nThe following methods are called before dispatching to the handler method.\n\n\n.check_permissions(self, request)\n\n\n.check_throttles(self, request)\n\n\n.perform_content_negotiation(self, request, force=False)\n\n\nDispatch methods\n\n\nThe following methods are called directly by the view's \n.dispatch()\n method.\nThese perform any actions that need to occur before or after calling the handler methods such as \n.get()\n, \n.post()\n, \nput()\n, \npatch()\n and \n.delete()\n.\n\n\n.initial(self, request, *args, **kwargs)\n\n\nPerforms any actions that need to occur before the handler method gets called.\nThis method is used to enforce permissions and throttling, and perform content negotiation.\n\n\nYou won't typically need to override this method.\n\n\n.handle_exception(self, exc)\n\n\nAny exception thrown by the handler method will be passed to this method, which either returns a \nResponse\n instance, or re-raises the exception.\n\n\nThe default implementation handles any subclass of \nrest_framework.exceptions.APIException\n, as well as Django's \nHttp404\n and \nPermissionDenied\n exceptions, and returns an appropriate error response.\n\n\nIf you need to customize the error responses your API returns you should subclass this method.\n\n\n.initialize_request(self, request, *args, **kwargs)\n\n\nEnsures that the request object that is passed to the handler method is an instance of \nRequest\n, rather than the usual Django \nHttpRequest\n.\n\n\nYou won't typically need to override this method.\n\n\n.finalize_response(self, request, response, *args, **kwargs)\n\n\nEnsures that any \nResponse\n object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.\n\n\nYou won't typically need to override this method.\n\n\n\n\nFunction Based Views\n\n\n\n\nSaying [that class-based views] is always the superior solution is a mistake.\n\n\n \nNick Coghlan\n\n\n\n\nREST 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 \nRequest\n (rather than the usual Django \nHttpRequest\n) and allows them to return a \nResponse\n (instead of a Django \nHttpResponse\n), and allow you to configure how the request is processed.\n\n\n@api_view()\n\n\nSignature:\n \n@api_view(http_method_names=['GET'], exclude_from_schema=False)\n\n\nThe core of this functionality is the \napi_view\n 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:\n\n\nfrom rest_framework.decorators import api_view\n\n@api_view()\ndef hello_world(request):\n    return Response({\"message\": \"Hello, world!\"})\n\n\n\nThis view will use the default renderers, parsers, authentication classes etc specified in the \nsettings\n.\n\n\nBy default only \nGET\n methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behaviour, specify which methods the view allows, like so:\n\n\n@api_view(['GET', 'POST'])\ndef hello_world(request):\n    if request.method == 'POST':\n        return Response({\"message\": \"Got some data!\", \"data\": request.data})\n    return Response({\"message\": \"Hello, world!\"})\n\n\n\nYou can also mark an API view as being omitted from any \nauto-generated schema\n,\nusing the \nexclude_from_schema\n argument.:\n\n\n@api_view(['GET'], exclude_from_schema=True)\ndef api_docs(request):\n    ...\n\n\n\nAPI policy decorators\n\n\nTo override the default settings, REST framework provides a set of additional decorators which can be added to your views.  These must come \nafter\n (below) the \n@api_view\n decorator.  For example, to create a view that uses a \nthrottle\n to ensure it can only be called once per day by a particular user, use the \n@throttle_classes\n decorator, passing a list of throttle classes:\n\n\nfrom rest_framework.decorators import api_view, throttle_classes\nfrom rest_framework.throttling import UserRateThrottle\n\nclass OncePerDayUserThrottle(UserRateThrottle):\n        rate = '1/day'\n\n@api_view(['GET'])\n@throttle_classes([OncePerDayUserThrottle])\ndef view(request):\n    return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n\n\n\nThese decorators correspond to the attributes set on \nAPIView\n subclasses, described above.\n\n\nThe available decorators are:\n\n\n\n\n@renderer_classes(...)\n\n\n@parser_classes(...)\n\n\n@authentication_classes(...)\n\n\n@throttle_classes(...)\n\n\n@permission_classes(...)\n\n\n\n\nEach of these decorators takes a single argument which must be a list or tuple of classes.", 
                 "title": "Views"
             }, 
             {
    @@ -702,7 +702,7 @@
             }, 
             {
                 "location": "/api-guide/views/#api_view", 
    -            "text": "Signature:   @api_view(http_method_names=['GET'])  The core of this functionality is the  api_view  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:  from rest_framework.decorators import api_view\n\n@api_view()\ndef hello_world(request):\n    return Response({\"message\": \"Hello, world!\"})  This view will use the default renderers, parsers, authentication classes etc specified in the  settings .  By default only  GET  methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behavior, specify which methods the view allows, like so:  @api_view(['GET', 'POST'])\ndef hello_world(request):\n    if request.method == 'POST':\n        return Response({\"message\": \"Got some data!\", \"data\": request.data})\n    return Response({\"message\": \"Hello, world!\"})", 
    +            "text": "Signature:   @api_view(http_method_names=['GET'], exclude_from_schema=False)  The core of this functionality is the  api_view  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:  from rest_framework.decorators import api_view\n\n@api_view()\ndef hello_world(request):\n    return Response({\"message\": \"Hello, world!\"})  This view will use the default renderers, parsers, authentication classes etc specified in the  settings .  By default only  GET  methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behaviour, specify which methods the view allows, like so:  @api_view(['GET', 'POST'])\ndef hello_world(request):\n    if request.method == 'POST':\n        return Response({\"message\": \"Got some data!\", \"data\": request.data})\n    return Response({\"message\": \"Hello, world!\"})  You can also mark an API view as being omitted from any  auto-generated schema ,\nusing the  exclude_from_schema  argument.:  @api_view(['GET'], exclude_from_schema=True)\ndef api_docs(request):\n    ...", 
                 "title": "@api_view()"
             }, 
             {
    @@ -712,7 +712,7 @@
             }, 
             {
                 "location": "/api-guide/generic-views/", 
    -            "text": "Generic views\n\n\n\n\nDjango\u2019s 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.\n\n\n \nDjango Documentation\n\n\n\n\nOne 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.\n\n\nThe generic views provided by REST framework allow you to quickly build API views that map closely to your database models.\n\n\nIf the generic views don't suit the needs of your API, you can drop down to using the regular \nAPIView\n class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.\n\n\nExamples\n\n\nTypically when using the generic views, you'll override the view, and set several class attributes.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)\n\n\n\nFor more complex cases you might also want to override various methods on the view class.  For example.\n\n\nclass UserList(generics.ListCreateAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)\n\n    def list(self, request):\n        # Note the use of `get_queryset()` instead of `self.queryset`\n        queryset = self.get_queryset()\n        serializer = UserSerializer(queryset, many=True)\n        return Response(serializer.data)\n\n\n\nFor very simple cases you might want to pass through any class attributes using the \n.as_view()\n method.  For example, your URLconf might include something like the following entry:\n\n\nurl(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n\n\n\n\n\nAPI Reference\n\n\nGenericAPIView\n\n\nThis class extends REST framework's \nAPIView\n class, adding commonly required behavior for standard list and detail views.\n\n\nEach of the concrete generic views provided is built by combining \nGenericAPIView\n, with one or more mixin classes.\n\n\nAttributes\n\n\nBasic settings\n:\n\n\nThe following attributes control the basic view behavior.\n\n\n\n\nqueryset\n - The queryset that should be used for returning objects from this view.  Typically, you must either set this attribute, or override the \nget_queryset()\n method. If you are overriding a view method, it is important that you call \nget_queryset()\n instead of accessing this property directly, as \nqueryset\n will get evaluated once, and those results will be cached for all subsequent requests.\n\n\nserializer_class\n - The serializer class that should be used for validating and deserializing input, and for serializing output.  Typically, you must either set this attribute, or override the \nget_serializer_class()\n method.\n\n\nlookup_field\n - The model field that should be used to for performing object lookup of individual model instances.  Defaults to \n'pk'\n.  Note that when using hyperlinked APIs you'll need to ensure that \nboth\n the API views \nand\n the serializer classes set the lookup fields if you need to use a custom value.\n\n\nlookup_url_kwarg\n - The URL keyword argument that should be used for object lookup.  The URL conf should include a keyword argument corresponding to this value.  If unset this defaults to using the same value as \nlookup_field\n.\n\n\n\n\nPagination\n:\n\n\nThe following attributes are used to control pagination when used with list views.\n\n\n\n\npagination_class\n - The pagination class that should be used when paginating list results. Defaults to the same value as the \nDEFAULT_PAGINATION_CLASS\n setting, which is \n'rest_framework.pagination.PageNumberPagination'\n.\n\n\n\n\nFiltering\n:\n\n\n\n\nfilter_backends\n - A list of filter backend classes that should be used for filtering the queryset.  Defaults to the same value as the \nDEFAULT_FILTER_BACKENDS\n setting.\n\n\n\n\nMethods\n\n\nBase methods\n:\n\n\nget_queryset(self)\n\n\nReturns 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 \nqueryset\n attribute.\n\n\nThis method should always be used rather than accessing \nself.queryset\n directly, as \nself.queryset\n gets evaluated only once, and those results are cached for all subsequent requests.\n\n\nMay be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.\n\n\nFor example:\n\n\ndef get_queryset(self):\n    user = self.request.user\n    return user.accounts.all()\n\n\n\nget_object(self)\n\n\nReturns an object instance that should be used for detail views.  Defaults to using the \nlookup_field\n parameter to filter the base queryset.\n\n\nMay be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.\n\n\nFor example:\n\n\ndef get_object(self):\n    queryset = self.get_queryset()\n    filter = {}\n    for field in self.multiple_lookup_fields:\n        filter[field] = self.kwargs[field]\n\n    obj = get_object_or_404(queryset, **filter)\n    self.check_object_permissions(self.request, obj)\n    return obj\n\n\n\nNote that if your API doesn't include any object level permissions, you may optionally exclude the \nself.check_object_permissions\n, and simply return the object from the \nget_object_or_404\n lookup.\n\n\nfilter_queryset(self, queryset)\n\n\nGiven a queryset, filter it with whichever filter backends are in use, returning a new queryset.   \n\n\nFor example:       \n\n\ndef filter_queryset(self, queryset):\n    filter_backends = (CategoryFilter,)\n\n    if 'geo_route' in self.request.query_params:\n        filter_backends = (GeoRouteFilter, CategoryFilter)\n    elif 'geo_point' in self.request.query_params:\n        filter_backends = (GeoPointFilter, CategoryFilter)\n\n    for backend in list(filter_backends):\n        queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n    return queryset\n\n\n\nget_serializer_class(self)\n\n\nReturns the class that should be used for the serializer.  Defaults to returning the \nserializer_class\n attribute.\n\n\nMay 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.\n\n\nFor example:\n\n\ndef get_serializer_class(self):\n    if self.request.user.is_staff:\n        return FullAccountSerializer\n    return BasicAccountSerializer\n\n\n\nSave and deletion hooks\n:\n\n\nThe following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.\n\n\n\n\nperform_create(self, serializer)\n - Called by \nCreateModelMixin\n when saving a new object instance.\n\n\nperform_update(self, serializer)\n - Called by \nUpdateModelMixin\n when saving an existing object instance.\n\n\nperform_destroy(self, instance)\n - Called by \nDestroyModelMixin\n when deleting an object instance.\n\n\n\n\nThese hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data.  For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.\n\n\ndef perform_create(self, serializer):\n    serializer.save(user=self.request.user)\n\n\n\nThese override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.\n\n\ndef perform_update(self, serializer):\n    instance = serializer.save()\n    send_email_confirmation(user=self.request.user, modified=instance)\n\n\n\nYou can also use these hooks to provide additional validation, by raising a \nValidationError()\n. This can be useful if you need some validation logic to apply at the point of database save. For example:\n\n\ndef perform_create(self, serializer):\n    queryset = SignupRequest.objects.filter(user=self.request.user)\n    if queryset.exists():\n        raise ValidationError('You have already signed up')\n    serializer.save(user=self.request.user)\n\n\n\nNote\n: These methods replace the old-style version 2.x \npre_save\n, \npost_save\n, \npre_delete\n and \npost_delete\n methods, which are no longer available.\n\n\nOther methods\n:\n\n\nYou won't typically need to override the following methods, although you might need to call into them if you're writing custom views using \nGenericAPIView\n.\n\n\n\n\nget_serializer_context(self)\n - Returns a dictionary containing any extra context that should be supplied to the serializer.  Defaults to including \n'request'\n, \n'view'\n and \n'format'\n keys.\n\n\nget_serializer(self, instance=None, data=None, many=False, partial=False)\n - Returns a serializer instance.\n\n\nget_paginated_response(self, data)\n - Returns a paginated style \nResponse\n object.\n\n\npaginate_queryset(self, queryset)\n - Paginate a queryset if required, either returning a page object, or \nNone\n if pagination is not configured for this view.\n\n\nfilter_queryset(self, queryset)\n - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.\n\n\n\n\n\n\nMixins\n\n\nThe 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 \n.get()\n and \n.post()\n, directly.  This allows for more flexible composition of behavior.\n\n\nThe mixin classes can be imported from \nrest_framework.mixins\n.\n\n\nListModelMixin\n\n\nProvides a \n.list(request, *args, **kwargs)\n method, that implements listing a queryset.\n\n\nIf the queryset is populated, this returns a \n200 OK\n response, with a serialized representation of the queryset as the body of the response.  The response data may optionally be paginated.\n\n\nCreateModelMixin\n\n\nProvides a \n.create(request, *args, **kwargs)\n method, that implements creating and saving a new model instance.\n\n\nIf an object is created this returns a \n201 Created\n response, with a serialized representation of the object as the body of the response.  If the representation contains a key named \nurl\n, then the \nLocation\n header of the response will be populated with that value.\n\n\nIf the request data provided for creating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nRetrieveModelMixin\n\n\nProvides a \n.retrieve(request, *args, **kwargs)\n method, that implements returning an existing model instance in a response.\n\n\nIf an object can be retrieved this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.  Otherwise it will return a \n404 Not Found\n.\n\n\nUpdateModelMixin\n\n\nProvides a \n.update(request, *args, **kwargs)\n method, that implements updating and saving an existing model instance.\n\n\nAlso provides a \n.partial_update(request, *args, **kwargs)\n method, which is similar to the \nupdate\n method, except that all fields for the update will be optional.  This allows support for HTTP \nPATCH\n requests.\n\n\nIf an object is updated this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.\n\n\nIf an object is created, for example when making a \nDELETE\n request followed by a \nPUT\n request to the same URL, this returns a \n201 Created\n response, with a serialized representation of the object as the body of the response.\n\n\nIf the request data provided for updating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nDestroyModelMixin\n\n\nProvides a \n.destroy(request, *args, **kwargs)\n method, that implements deletion of an existing model instance.\n\n\nIf an object is deleted this returns a \n204 No Content\n response, otherwise it will return a \n404 Not Found\n.\n\n\n\n\nConcrete View Classes\n\n\nThe 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.\n\n\nThe view classes can be imported from \nrest_framework.generics\n.\n\n\nCreateAPIView\n\n\nUsed for \ncreate-only\n endpoints.\n\n\nProvides a \npost\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nCreateModelMixin\n\n\nListAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n\n\nRetrieveAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n\n\nDestroyAPIView\n\n\nUsed for \ndelete-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides a \ndelete\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nDestroyModelMixin\n\n\nUpdateAPIView\n\n\nUsed for \nupdate-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nUpdateModelMixin\n\n\nListCreateAPIView\n\n\nUsed for \nread-write\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides \nget\n and \npost\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n, \nCreateModelMixin\n\n\nRetrieveUpdateAPIView\n\n\nUsed for \nread or update\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n\n\nRetrieveDestroyAPIView\n\n\nUsed for \nread or delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nDestroyModelMixin\n\n\nRetrieveUpdateDestroyAPIView\n\n\nUsed for \nread-write-delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n, \npatch\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n, \nDestroyModelMixin\n\n\n\n\nCustomizing the generic views\n\n\nOften 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.\n\n\nCreating custom mixins\n\n\nFor example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:\n\n\nclass MultipleFieldLookupMixin(object):\n    \"\"\"\n    Apply this mixin to any view or viewset to get multiple field filtering\n    based on a `lookup_fields` attribute, instead of the default single field filtering.\n    \"\"\"\n    def get_object(self):\n        queryset = self.get_queryset()             # Get the base queryset\n        queryset = self.filter_queryset(queryset)  # Apply any filter backends\n        filter = {}\n        for field in self.lookup_fields:\n            if self.kwargs[field]: # Ignore empty fields.\n                filter[field] = self.kwargs[field]\n        return get_object_or_404(queryset, **filter)  # Lookup the object\n\n\n\nYou can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.\n\n\nclass RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    lookup_fields = ('account', 'username')\n\n\n\nUsing custom mixins is a good option if you have custom behavior that needs to be used.\n\n\nCreating custom base classes\n\n\nIf 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:\n\n\nclass BaseRetrieveView(MultipleFieldLookupMixin,\n                       generics.RetrieveAPIView):\n    pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n                                    generics.RetrieveUpdateDestroyAPIView):\n    pass\n\n\n\nUsing 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.\n\n\n\n\nPUT as create\n\n\nPrior to version 3.0 the REST framework mixins treated \nPUT\n as either an update or a create operation, depending on if the object already existed or not.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to generic PUT-as-create behavior you may want to include something like \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\n\n\nThird party packages\n\n\nThe following third party packages provide additional generic view implementations.\n\n\nDjango REST Framework bulk\n\n\nThe \ndjango-rest-framework-bulk package\n implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\nDjango Rest Multiple Models\n\n\nDjango Rest Multiple Models\n provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.", 
    +            "text": "Generic views\n\n\n\n\nDjango\u2019s 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.\n\n\n \nDjango Documentation\n\n\n\n\nOne 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.\n\n\nThe generic views provided by REST framework allow you to quickly build API views that map closely to your database models.\n\n\nIf the generic views don't suit the needs of your API, you can drop down to using the regular \nAPIView\n class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.\n\n\nExamples\n\n\nTypically when using the generic views, you'll override the view, and set several class attributes.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)\n\n\n\nFor more complex cases you might also want to override various methods on the view class.  For example.\n\n\nclass UserList(generics.ListCreateAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)\n\n    def list(self, request):\n        # Note the use of `get_queryset()` instead of `self.queryset`\n        queryset = self.get_queryset()\n        serializer = UserSerializer(queryset, many=True)\n        return Response(serializer.data)\n\n\n\nFor very simple cases you might want to pass through any class attributes using the \n.as_view()\n method.  For example, your URLconf might include something like the following entry:\n\n\nurl(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n\n\n\n\n\nAPI Reference\n\n\nGenericAPIView\n\n\nThis class extends REST framework's \nAPIView\n class, adding commonly required behavior for standard list and detail views.\n\n\nEach of the concrete generic views provided is built by combining \nGenericAPIView\n, with one or more mixin classes.\n\n\nAttributes\n\n\nBasic settings\n:\n\n\nThe following attributes control the basic view behavior.\n\n\n\n\nqueryset\n - The queryset that should be used for returning objects from this view.  Typically, you must either set this attribute, or override the \nget_queryset()\n method. If you are overriding a view method, it is important that you call \nget_queryset()\n instead of accessing this property directly, as \nqueryset\n will get evaluated once, and those results will be cached for all subsequent requests.\n\n\nserializer_class\n - The serializer class that should be used for validating and deserializing input, and for serializing output.  Typically, you must either set this attribute, or override the \nget_serializer_class()\n method.\n\n\nlookup_field\n - The model field that should be used to for performing object lookup of individual model instances.  Defaults to \n'pk'\n.  Note that when using hyperlinked APIs you'll need to ensure that \nboth\n the API views \nand\n the serializer classes set the lookup fields if you need to use a custom value.\n\n\nlookup_url_kwarg\n - The URL keyword argument that should be used for object lookup.  The URL conf should include a keyword argument corresponding to this value.  If unset this defaults to using the same value as \nlookup_field\n.\n\n\n\n\nPagination\n:\n\n\nThe following attributes are used to control pagination when used with list views.\n\n\n\n\npagination_class\n - The pagination class that should be used when paginating list results. Defaults to the same value as the \nDEFAULT_PAGINATION_CLASS\n setting, which is \n'rest_framework.pagination.PageNumberPagination'\n.\n\n\n\n\nFiltering\n:\n\n\n\n\nfilter_backends\n - A list of filter backend classes that should be used for filtering the queryset.  Defaults to the same value as the \nDEFAULT_FILTER_BACKENDS\n setting.\n\n\n\n\nMethods\n\n\nBase methods\n:\n\n\nget_queryset(self)\n\n\nReturns 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 \nqueryset\n attribute.\n\n\nThis method should always be used rather than accessing \nself.queryset\n directly, as \nself.queryset\n gets evaluated only once, and those results are cached for all subsequent requests.\n\n\nMay be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.\n\n\nFor example:\n\n\ndef get_queryset(self):\n    user = self.request.user\n    return user.accounts.all()\n\n\n\nget_object(self)\n\n\nReturns an object instance that should be used for detail views.  Defaults to using the \nlookup_field\n parameter to filter the base queryset.\n\n\nMay be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.\n\n\nFor example:\n\n\ndef get_object(self):\n    queryset = self.get_queryset()\n    filter = {}\n    for field in self.multiple_lookup_fields:\n        filter[field] = self.kwargs[field]\n\n    obj = get_object_or_404(queryset, **filter)\n    self.check_object_permissions(self.request, obj)\n    return obj\n\n\n\nNote that if your API doesn't include any object level permissions, you may optionally exclude the \nself.check_object_permissions\n, and simply return the object from the \nget_object_or_404\n lookup.\n\n\nfilter_queryset(self, queryset)\n\n\nGiven a queryset, filter it with whichever filter backends are in use, returning a new queryset.   \n\n\nFor example:       \n\n\ndef filter_queryset(self, queryset):\n    filter_backends = (CategoryFilter,)\n\n    if 'geo_route' in self.request.query_params:\n        filter_backends = (GeoRouteFilter, CategoryFilter)\n    elif 'geo_point' in self.request.query_params:\n        filter_backends = (GeoPointFilter, CategoryFilter)\n\n    for backend in list(filter_backends):\n        queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n    return queryset\n\n\n\nget_serializer_class(self)\n\n\nReturns the class that should be used for the serializer.  Defaults to returning the \nserializer_class\n attribute.\n\n\nMay 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.\n\n\nFor example:\n\n\ndef get_serializer_class(self):\n    if self.request.user.is_staff:\n        return FullAccountSerializer\n    return BasicAccountSerializer\n\n\n\nSave and deletion hooks\n:\n\n\nThe following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.\n\n\n\n\nperform_create(self, serializer)\n - Called by \nCreateModelMixin\n when saving a new object instance.\n\n\nperform_update(self, serializer)\n - Called by \nUpdateModelMixin\n when saving an existing object instance.\n\n\nperform_destroy(self, instance)\n - Called by \nDestroyModelMixin\n when deleting an object instance.\n\n\n\n\nThese hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data.  For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.\n\n\ndef perform_create(self, serializer):\n    serializer.save(user=self.request.user)\n\n\n\nThese override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.\n\n\ndef perform_update(self, serializer):\n    instance = serializer.save()\n    send_email_confirmation(user=self.request.user, modified=instance)\n\n\n\nYou can also use these hooks to provide additional validation, by raising a \nValidationError()\n. This can be useful if you need some validation logic to apply at the point of database save. For example:\n\n\ndef perform_create(self, serializer):\n    queryset = SignupRequest.objects.filter(user=self.request.user)\n    if queryset.exists():\n        raise ValidationError('You have already signed up')\n    serializer.save(user=self.request.user)\n\n\n\nNote\n: These methods replace the old-style version 2.x \npre_save\n, \npost_save\n, \npre_delete\n and \npost_delete\n methods, which are no longer available.\n\n\nOther methods\n:\n\n\nYou won't typically need to override the following methods, although you might need to call into them if you're writing custom views using \nGenericAPIView\n.\n\n\n\n\nget_serializer_context(self)\n - Returns a dictionary containing any extra context that should be supplied to the serializer.  Defaults to including \n'request'\n, \n'view'\n and \n'format'\n keys.\n\n\nget_serializer(self, instance=None, data=None, many=False, partial=False)\n - Returns a serializer instance.\n\n\nget_paginated_response(self, data)\n - Returns a paginated style \nResponse\n object.\n\n\npaginate_queryset(self, queryset)\n - Paginate a queryset if required, either returning a page object, or \nNone\n if pagination is not configured for this view.\n\n\nfilter_queryset(self, queryset)\n - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.\n\n\n\n\n\n\nMixins\n\n\nThe 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 \n.get()\n and \n.post()\n, directly.  This allows for more flexible composition of behavior.\n\n\nThe mixin classes can be imported from \nrest_framework.mixins\n.\n\n\nListModelMixin\n\n\nProvides a \n.list(request, *args, **kwargs)\n method, that implements listing a queryset.\n\n\nIf the queryset is populated, this returns a \n200 OK\n response, with a serialized representation of the queryset as the body of the response.  The response data may optionally be paginated.\n\n\nCreateModelMixin\n\n\nProvides a \n.create(request, *args, **kwargs)\n method, that implements creating and saving a new model instance.\n\n\nIf an object is created this returns a \n201 Created\n response, with a serialized representation of the object as the body of the response.  If the representation contains a key named \nurl\n, then the \nLocation\n header of the response will be populated with that value.\n\n\nIf the request data provided for creating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nRetrieveModelMixin\n\n\nProvides a \n.retrieve(request, *args, **kwargs)\n method, that implements returning an existing model instance in a response.\n\n\nIf an object can be retrieved this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.  Otherwise it will return a \n404 Not Found\n.\n\n\nUpdateModelMixin\n\n\nProvides a \n.update(request, *args, **kwargs)\n method, that implements updating and saving an existing model instance.\n\n\nAlso provides a \n.partial_update(request, *args, **kwargs)\n method, which is similar to the \nupdate\n method, except that all fields for the update will be optional.  This allows support for HTTP \nPATCH\n requests.\n\n\nIf an object is updated this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.\n\n\nIf the request data provided for updating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nDestroyModelMixin\n\n\nProvides a \n.destroy(request, *args, **kwargs)\n method, that implements deletion of an existing model instance.\n\n\nIf an object is deleted this returns a \n204 No Content\n response, otherwise it will return a \n404 Not Found\n.\n\n\n\n\nConcrete View Classes\n\n\nThe 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.\n\n\nThe view classes can be imported from \nrest_framework.generics\n.\n\n\nCreateAPIView\n\n\nUsed for \ncreate-only\n endpoints.\n\n\nProvides a \npost\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nCreateModelMixin\n\n\nListAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n\n\nRetrieveAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n\n\nDestroyAPIView\n\n\nUsed for \ndelete-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides a \ndelete\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nDestroyModelMixin\n\n\nUpdateAPIView\n\n\nUsed for \nupdate-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nUpdateModelMixin\n\n\nListCreateAPIView\n\n\nUsed for \nread-write\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides \nget\n and \npost\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n, \nCreateModelMixin\n\n\nRetrieveUpdateAPIView\n\n\nUsed for \nread or update\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n\n\nRetrieveDestroyAPIView\n\n\nUsed for \nread or delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nDestroyModelMixin\n\n\nRetrieveUpdateDestroyAPIView\n\n\nUsed for \nread-write-delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n, \npatch\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n, \nDestroyModelMixin\n\n\n\n\nCustomizing the generic views\n\n\nOften 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.\n\n\nCreating custom mixins\n\n\nFor example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:\n\n\nclass MultipleFieldLookupMixin(object):\n    \"\"\"\n    Apply this mixin to any view or viewset to get multiple field filtering\n    based on a `lookup_fields` attribute, instead of the default single field filtering.\n    \"\"\"\n    def get_object(self):\n        queryset = self.get_queryset()             # Get the base queryset\n        queryset = self.filter_queryset(queryset)  # Apply any filter backends\n        filter = {}\n        for field in self.lookup_fields:\n            if self.kwargs[field]: # Ignore empty fields.\n                filter[field] = self.kwargs[field]\n        return get_object_or_404(queryset, **filter)  # Lookup the object\n\n\n\nYou can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.\n\n\nclass RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    lookup_fields = ('account', 'username')\n\n\n\nUsing custom mixins is a good option if you have custom behavior that needs to be used.\n\n\nCreating custom base classes\n\n\nIf 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:\n\n\nclass BaseRetrieveView(MultipleFieldLookupMixin,\n                       generics.RetrieveAPIView):\n    pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n                                    generics.RetrieveUpdateDestroyAPIView):\n    pass\n\n\n\nUsing 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.\n\n\n\n\nPUT as create\n\n\nPrior to version 3.0 the REST framework mixins treated \nPUT\n as either an update or a create operation, depending on if the object already existed or not.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to generic PUT-as-create behavior you may want to include something like \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\n\n\nThird party packages\n\n\nThe following third party packages provide additional generic view implementations.\n\n\nDjango REST Framework bulk\n\n\nThe \ndjango-rest-framework-bulk package\n implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\nDjango Rest Multiple Models\n\n\nDjango Rest Multiple Models\n provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.", 
                 "title": "Generic views"
             }, 
             {
    @@ -787,7 +787,7 @@
             }, 
             {
                 "location": "/api-guide/generic-views/#updatemodelmixin", 
    -            "text": "Provides a  .update(request, *args, **kwargs)  method, that implements updating and saving an existing model instance.  Also provides a  .partial_update(request, *args, **kwargs)  method, which is similar to the  update  method, except that all fields for the update will be optional.  This allows support for HTTP  PATCH  requests.  If an object is updated this returns a  200 OK  response, with a serialized representation of the object as the body of the response.  If an object is created, for example when making a  DELETE  request followed by a  PUT  request to the same URL, this returns a  201 Created  response, with a serialized representation of the object as the body of the response.  If the request data provided for updating the object was invalid, a  400 Bad Request  response will be returned, with the error details as the body of the response.", 
    +            "text": "Provides a  .update(request, *args, **kwargs)  method, that implements updating and saving an existing model instance.  Also provides a  .partial_update(request, *args, **kwargs)  method, which is similar to the  update  method, except that all fields for the update will be optional.  This allows support for HTTP  PATCH  requests.  If an object is updated this returns a  200 OK  response, with a serialized representation of the object as the body of the response.  If the request data provided for updating the object was invalid, a  400 Bad Request  response will be returned, with the error details as the body of the response.", 
                 "title": "UpdateModelMixin"
             }, 
             {
    @@ -1332,7 +1332,7 @@
             }, 
             {
                 "location": "/api-guide/serializers/", 
    -            "text": "Serializers\n\n\n\n\nExpanding the usefulness of the serializers is something that we would\nlike to address.  However, it's not a trivial problem, and it\nwill take some serious design work.\n\n\n Russell Keith-Magee, \nDjango users group\n\n\n\n\nSerializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into \nJSON\n, \nXML\n or other content types.  Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.\n\n\nThe serializers in REST framework work very similarly to Django's \nForm\n and \nModelForm\n classes. We provide a \nSerializer\n class which gives you a powerful, generic way to control the output of your responses, as well as a \nModelSerializer\n class which provides a useful shortcut for creating serializers that deal with model instances and querysets.\n\n\nDeclaring Serializers\n\n\nLet's start by creating a simple object we can use for example purposes:\n\n\nfrom datetime import datetime\n\nclass Comment(object):\n    def __init__(self, email, content, created=None):\n        self.email = email\n        self.content = content\n        self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n\n\n\nWe'll declare a serializer that we can use to serialize and deserialize data that corresponds to \nComment\n objects.\n\n\nDeclaring a serializer looks very similar to declaring a form:\n\n\nfrom rest_framework import serializers\n\nclass CommentSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nSerializing objects\n\n\nWe can now use \nCommentSerializer\n to serialize a comment, or list of comments. Again, using the \nSerializer\n class looks a lot like using a \nForm\n class.\n\n\nserializer = CommentSerializer(comment)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes.  To finalise the serialization process we render the data into \njson\n.\n\n\nfrom rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n\n\n\nDeserializing objects\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\nfrom rest_framework.parsers import JSONParser\n\nstream = BytesIO(json)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a dictionary of validated data.\n\n\nserializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n\n\n\nSaving instances\n\n\nIf we want to be able to return complete object instances based on the validated data we need to implement one or both of the \n.create()\n and \nupdate()\n methods. For example:\n\n\nclass CommentSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n    def create(self, validated_data):\n        return Comment(**validated_data)\n\n    def update(self, instance, validated_data):\n        instance.email = validated_data.get('email', instance.email)\n        instance.content = validated_data.get('content', instance.content)\n        instance.created = validated_data.get('created', instance.created)\n        return instance\n\n\n\nIf your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if \nComment\n was a Django model, the methods might look like this:\n\n\n    def create(self, validated_data):\n        return Comment.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        instance.email = validated_data.get('email', instance.email)\n        instance.content = validated_data.get('content', instance.content)\n        instance.created = validated_data.get('created', instance.created)\n        instance.save()\n        return instance\n\n\n\nNow when deserializing data, we can call \n.save()\n to return an object instance, based on the validated data.\n\n\ncomment = serializer.save()\n\n\n\nCalling \n.save()\n will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:\n\n\n# .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n\n\n\nBoth the \n.create()\n and \n.update()\n methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.\n\n\nPassing additional attributes to \n.save()\n\n\nSometimes 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.\n\n\nYou can do so by including additional keyword arguments when calling \n.save()\n. For example:\n\n\nserializer.save(owner=request.user)\n\n\n\nAny additional keyword arguments will be included in the \nvalidated_data\n argument when \n.create()\n or \n.update()\n are called.\n\n\nOverriding \n.save()\n directly.\n\n\nIn some cases the \n.create()\n and \n.update()\n 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.\n\n\nIn these cases you might instead choose to override \n.save()\n directly, as being more readable and meaningful.\n\n\nFor example:\n\n\nclass ContactForm(serializers.Serializer):\n    email = serializers.EmailField()\n    message = serializers.CharField()\n\n    def save(self):\n        email = self.validated_data['email']\n        message = self.validated_data['message']\n        send_email(from=email, message=message)\n\n\n\nNote that in the case above we're now having to access the serializer \n.validated_data\n property directly.\n\n\nValidation\n\n\nWhen deserializing data, you always need to call \nis_valid()\n before attempting to access the validated data, or save an object instance. If any validation errors occur, the \n.errors\n property will contain a dictionary representing the resulting error messages.  For example:\n\n\nserializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}\n\n\n\nEach 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 \nnon_field_errors\n key may also be present, and will list any general validation errors. The name of the \nnon_field_errors\n key may be customized using the \nNON_FIELD_ERRORS_KEY\n REST framework setting.\n\n\nWhen deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.\n\n\nRaising an exception on invalid data\n\n\nThe \n.is_valid()\n method takes an optional \nraise_exception\n flag that will cause it to raise a \nserializers.ValidationError\n exception if there are validation errors.\n\n\nThese exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return \nHTTP 400 Bad Request\n responses by default.\n\n\n# Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True)\n\n\n\nField-level validation\n\n\nYou can specify custom field-level validation by adding \n.validate_\nfield_name\n methods to your \nSerializer\n subclass.  These are similar to the \n.clean_\nfield_name\n methods on Django forms.\n\n\nThese methods take a single argument, which is the field value that requires validation.\n\n\nYour \nvalidate_\nfield_name\n methods should return the validated value or raise a \nserializers.ValidationError\n.  For example:\n\n\nfrom rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n    title = serializers.CharField(max_length=100)\n    content = serializers.CharField()\n\n    def validate_title(self, value):\n        \"\"\"\n        Check that the blog post is about Django.\n        \"\"\"\n        if 'django' not in value.lower():\n            raise serializers.ValidationError(\"Blog post is not about Django\")\n        return value\n\n\n\n\n\nNote:\n If your \nfield_name\n is declared on your serializer with the parameter \nrequired=False\n then this validation step will not take place if the field is not included.\n\n\n\n\nObject-level validation\n\n\nTo do any other validation that requires access to multiple fields, add a method called \n.validate()\n to your \nSerializer\n subclass.  This method takes a single argument, which is a dictionary of field values.  It should raise a \nValidationError\n if necessary, or just return the validated values.  For example:\n\n\nfrom rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n    description = serializers.CharField(max_length=100)\n    start = serializers.DateTimeField()\n    finish = serializers.DateTimeField()\n\n    def validate(self, data):\n        \"\"\"\n        Check that the start is before the stop.\n        \"\"\"\n        if data['start'] \n data['finish']:\n            raise serializers.ValidationError(\"finish must occur after start\")\n        return data\n\n\n\nValidators\n\n\nIndividual fields on a serializer can include validators, by declaring them on the field instance, for example:\n\n\ndef multiple_of_ten(value):\n    if value % 10 != 0:\n        raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n    score = IntegerField(validators=[multiple_of_ten])\n    ...\n\n\n\nSerializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner \nMeta\n class, like so:\n\n\nclass EventSerializer(serializers.Serializer):\n    name = serializers.CharField()\n    room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n    date = serializers.DateField()\n\n    class Meta:\n        # Each room only has one event per day.\n        validators = UniqueTogetherValidator(\n            queryset=Event.objects.all(),\n            fields=['room_number', 'date']\n        )\n\n\n\nFor more information see the \nvalidators documentation\n.\n\n\nAccessing the initial data and instance\n\n\nWhen passing an initial object or queryset to a serializer instance, the object will be made available as \n.instance\n. If no initial object is passed then the \n.instance\n attribute will be \nNone\n.\n\n\nWhen passing data to a serializer instance, the unmodified data will be made available as \n.initial_data\n. If the data keyword argument is not passed then the \n.initial_data\n attribute will not exist.\n\n\nPartial updates\n\n\nBy default, serializers must be passed values for all required fields or they will raise validation errors. You can use the \npartial\n argument in order to allow partial updates.\n\n\n# Update `comment` with partial data\nserializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)\n\n\n\nDealing with nested objects\n\n\nThe 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.\n\n\nThe \nSerializer\n class is itself a type of \nField\n, and can be used to represent relationships where one object type is nested inside another.\n\n\nclass UserSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nIf a nested representation may optionally accept the \nNone\n value you should pass the \nrequired=False\n flag to the nested serializer.\n\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer(required=False)  # May be an anonymous user.\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nSimilarly if a nested representation should be a list of items, you should pass the \nmany=True\n flag to the nested serialized.\n\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer(required=False)\n    edits = EditItemSerializer(many=True)  # A nested list of 'edit' items.\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nWritable nested representations\n\n\nWhen 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.\n\n\nserializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}\n\n\n\nSimilarly, the \n.validated_data\n property will include nested data structures.\n\n\nWriting \n.create()\n methods for nested representations\n\n\nIf you're supporting writable nested representations you'll need to write \n.create()\n or \n.update()\n methods that handle saving multiple objects.\n\n\nThe following example demonstrates how you might handle creating a user with a nested profile object.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n    profile = ProfileSerializer()\n\n    class Meta:\n        model = User\n        fields = ('username', 'email', 'profile')\n\n    def create(self, validated_data):\n        profile_data = validated_data.pop('profile')\n        user = User.objects.create(**validated_data)\n        Profile.objects.create(user=user, **profile_data)\n        return user\n\n\n\nWriting \n.update()\n methods for nested representations\n\n\nFor updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is \nNone\n, or not provided, which of the following should occur?\n\n\n\n\nSet the relationship to \nNULL\n in the database.\n\n\nDelete the associated instance.\n\n\nIgnore the data and leave the instance as it is.\n\n\nRaise a validation error.\n\n\n\n\nHere's an example for an \nupdate()\n method on our previous \nUserSerializer\n class.\n\n\n    def update(self, instance, validated_data):\n        profile_data = validated_data.pop('profile')\n        # Unless the application properly enforces that this field is\n        # always set, the follow could raise a `DoesNotExist`, which\n        # would need to be handled.\n        profile = instance.profile\n\n        instance.username = validated_data.get('username', instance.username)\n        instance.email = validated_data.get('email', instance.email)\n        instance.save()\n\n        profile.is_premium_member = profile_data.get(\n            'is_premium_member',\n            profile.is_premium_member\n        )\n        profile.has_support_contract = profile_data.get(\n            'has_support_contract',\n            profile.has_support_contract\n         )\n        profile.save()\n\n        return instance\n\n\n\nBecause 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 \nModelSerializer\n \n.create()\n and \n.update()\n methods do not include support for writable nested representations.\n\n\nIt 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.\n\n\nHandling saving related instances in model manager classes\n\n\nAn alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.\n\n\nFor example, suppose we wanted to ensure that \nUser\n instances and \nProfile\n instances are always created together as a pair. We might write a custom manager class that looks something like this:\n\n\nclass UserManager(models.Manager):\n    ...\n\n    def create(self, username, email, is_premium_member=False, has_support_contract=False):\n        user = User(username=username, email=email)\n        user.save()\n        profile = Profile(\n            user=user,\n            is_premium_member=is_premium_member,\n            has_support_contract=has_support_contract\n        )\n        profile.save()\n        return user\n\n\n\nThis manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our \n.create()\n method on the serializer class can now be re-written to use the new manager method.\n\n\ndef create(self, validated_data):\n    return User.objects.create(\n        username=validated_data['username'],\n        email=validated_data['email']\n        is_premium_member=validated_data['profile']['is_premium_member']\n        has_support_contract=validated_data['profile']['has_support_contract']\n    )\n\n\n\nFor more details on this approach see the Django documentation on \nmodel managers\n, and \nthis blogpost on using model and manager classes\n.\n\n\nDealing with multiple objects\n\n\nThe \nSerializer\n class can also handle serializing or deserializing lists of objects.\n\n\nSerializing multiple objects\n\n\nTo serialize a queryset or list of objects instead of a single object instance, you should pass the \nmany=True\n flag when instantiating the serializer.  You can then pass a queryset or list of objects to be serialized.\n\n\nqueryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n#     {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n#     {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n#     {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n\n\n\nDeserializing multiple objects\n\n\nThe 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 \nListSerializer\n documentation below.\n\n\nIncluding extra context\n\n\nThere 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.\n\n\nYou can provide arbitrary additional context by passing a \ncontext\n argument when instantiating the serializer.  For example:\n\n\nserializer = AccountSerializer(account, context={'request': request})\nserializer.data\n# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n\n\n\nThe context dictionary can be used within any serializer field logic, such as a custom \n.to_representation()\n method, by accessing the \nself.context\n attribute.\n\n\n\n\nModelSerializer\n\n\nOften you'll want serializer classes that map closely to Django model definitions.\n\n\nThe \nModelSerializer\n class provides a shortcut that lets you automatically create a \nSerializer\n class with fields that correspond to the Model fields.\n\n\nThe \nModelSerializer\n class is the same as a regular \nSerializer\n class, except that\n:\n\n\n\n\nIt will automatically generate a set of fields for you, based on the model.\n\n\nIt will automatically generate validators for the serializer, such as unique_together validators.\n\n\nIt includes simple default implementations of \n.create()\n and \n.update()\n.\n\n\n\n\nDeclaring a \nModelSerializer\n looks like this:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n\n\n\nBy default, all the model fields on the class will be mapped to a corresponding serializer fields.\n\n\nAny relationships such as foreign keys on the model will be mapped to \nPrimaryKeyRelatedField\n. Reverse relationships are not included by default unless explicitly included as specified in the \nserializer relations\n documentation.\n\n\nInspecting a \nModelSerializer\n\n\nSerializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with \nModelSerializers\n where you want to determine what set of fields and validators are being automatically created for you.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print(repr(serializer))\nAccountSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    name = CharField(allow_blank=True, max_length=100, required=False)\n    owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nSpecifying which fields to include\n\n\nIf you only want a subset of the default fields to be used in a model serializer, you can do so using \nfields\n or \nexclude\n options, just as you would with a \nModelForm\n. It is strongly recommended that you explicitly set all fields that should be serialized using the \nfields\n attribute. This will make it less likely to result in unintentionally exposing data when your models change.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n\n\n\nYou can also set the \nfields\n attribute to the special value \n'__all__'\n to indicate that all fields in the model should be used.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = '__all__'\n\n\n\nYou can set the \nexclude\n attribute to a list of fields to be excluded from the serializer.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        exclude = ('users',)\n\n\n\nIn the example above, if the \nAccount\n model had 3 fields \naccount_name\n, \nusers\n, and \ncreated\n, this will result in the fields \naccount_name\n and \ncreated\n to be serialized.\n\n\nThe names in the \nfields\n and \nexclude\n attributes will normally map to model fields on the model class.\n\n\nAlternatively names in the \nfields\n options can map to properties or methods which take no arguments that exist on the model class.\n\n\nSpecifying nested serialization\n\n\nThe default \nModelSerializer\n uses primary keys for relationships, but you can also easily generate nested representations using the \ndepth\n option:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n        depth = 1\n\n\n\nThe \ndepth\n option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.\n\n\nIf you want to customize the way the serialization is done you'll need to define the field yourself.\n\n\nSpecifying fields explicitly\n\n\nYou can add extra fields to a \nModelSerializer\n or override the default fields by declaring fields on the class, just as you would for a \nSerializer\n class.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    url = serializers.CharField(source='get_absolute_url', read_only=True)\n    groups = serializers.PrimaryKeyRelatedField(many=True)\n\n    class Meta:\n        model = Account\n\n\n\nExtra fields can correspond to any property or callable on the model.\n\n\nSpecifying read only fields\n\n\nYou may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the \nread_only=True\n attribute, you may use the shortcut Meta option, \nread_only_fields\n.\n\n\nThis option should be a list or tuple of field names, and is declared as follows:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n        read_only_fields = ('account_name',)\n\n\n\nModel fields which have \neditable=False\n set, and \nAutoField\n fields will be set to read-only by default, and do not need to be added to the \nread_only_fields\n option.\n\n\n\n\nNote\n: There is a special-case where a read-only field is part of a \nunique_together\n constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.\n\n\nThe right way to deal with this is to specify the field explicitly on the serializer, providing both the \nread_only=True\n and \ndefault=\u2026\n keyword arguments.\n\n\nOne example of this is a read-only relation to the currently authenticated \nUser\n which is \nunique_together\n with another identifier. In this case you would declare the user field like so:\n\n\nuser = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())\n\n\n\nPlease review the \nValidators Documentation\n for details on the \nUniqueTogetherValidator\n and \nCurrentUserDefault\n classes.\n\n\n\n\nAdditional keyword arguments\n\n\nThere is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the \nextra_kwargs\n option. As in the case of \nread_only_fields\n, this means you do not need to explicitly declare the field on the serializer.\n\n\nThis option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:\n\n\nclass CreateUserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = ('email', 'username', 'password')\n        extra_kwargs = {'password': {'write_only': True}}\n\n    def create(self, validated_data):\n        user = User(\n            email=validated_data['email'],\n            username=validated_data['username']\n        )\n        user.set_password(validated_data['password'])\n        user.save()\n        return user\n\n\n\nRelational fields\n\n\nWhen serializing model instances, there are a number of different ways you might choose to represent relationships.  The default representation for \nModelSerializer\n is to use the primary keys of the related instances.\n\n\nAlternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.\n\n\nFor full details see the \nserializer relations\n documentation.\n\n\nInheritance of the 'Meta' class\n\n\nThe inner \nMeta\n class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's \nModel\n and \nModelForm\n classes. If you want the \nMeta\n class to inherit from a parent class you must do so explicitly. For example:\n\n\nclass AccountSerializer(MyBaseSerializer):\n    class Meta(MyBaseSerializer.Meta):\n        model = Account\n\n\n\nTypically we would recommend \nnot\n using inheritance on inner Meta classes, but instead declaring all options explicitly.\n\n\nCustomizing field mappings\n\n\nThe ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.\n\n\nNormally if a \nModelSerializer\n does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular \nSerializer\n 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.\n\n\n.serializer_field_mapping\n\n\nA 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.\n\n\n.serializer_related_field\n\n\nThis property should be the serializer field class, that is used for relational fields by default.\n\n\nFor \nModelSerializer\n this defaults to \nPrimaryKeyRelatedField\n.\n\n\nFor \nHyperlinkedModelSerializer\n this defaults to \nserializers.HyperlinkedRelatedField\n.\n\n\nserializer_url_field\n\n\nThe serializer field class that should be used for any \nurl\n field on the serializer.\n\n\nDefaults to \nserializers.HyperlinkedIdentityField\n\n\nserializer_choice_field\n\n\nThe serializer field class that should be used for any choice fields on the serializer.\n\n\nDefaults to \nserializers.ChoiceField\n\n\nThe field_class and field_kwargs API\n\n\nThe 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 \n(field_class, field_kwargs)\n.\n\n\n.build_standard_field(self, field_name, model_field)\n\n\nCalled to generate a serializer field that maps to a standard model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_field_mapping\n attribute.\n\n\n.build_relational_field(self, field_name, relation_info)\n\n\nCalled to generate a serializer field that maps to a relational model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_relational_field\n attribute.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_nested_field(self, field_name, relation_info, nested_depth)\n\n\nCalled to generate a serializer field that maps to a relational model field, when the \ndepth\n option has been set.\n\n\nThe default implementation dynamically creates a nested serializer class based on either \nModelSerializer\n or \nHyperlinkedModelSerializer\n.\n\n\nThe \nnested_depth\n will be the value of the \ndepth\n option, minus one.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_property_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field that maps to a property or zero-argument method on the model class.\n\n\nThe default implementation returns a \nReadOnlyField\n class.\n\n\n.build_url_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field for the serializer's own \nurl\n field. The default implementation returns a \nHyperlinkedIdentityField\n class.\n\n\n.build_unknown_field(self, field_name, model_class)\n\n\nCalled when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.\n\n\n\n\nHyperlinkedModelSerializer\n\n\nThe \nHyperlinkedModelSerializer\n class is similar to the \nModelSerializer\n class except that it uses hyperlinks to represent relationships, rather than primary keys.\n\n\nBy default the serializer will include a \nurl\n field instead of a primary key field.\n\n\nThe url field will be represented using a \nHyperlinkedIdentityField\n serializer field, and any relationships on the model will be represented using a \nHyperlinkedRelatedField\n serializer field.\n\n\nYou can explicitly include the primary key by adding it to the \nfields\n option, for example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('url', 'id', 'account_name', 'users', 'created')\n\n\n\nAbsolute and relative URLs\n\n\nWhen instantiating a \nHyperlinkedModelSerializer\n you must include the current\n\nrequest\n in the serializer context, for example:\n\n\nserializer = AccountSerializer(queryset, context={'request': request})\n\n\n\nDoing so will ensure that the hyperlinks can include an appropriate hostname,\nso that the resulting representation uses fully qualified URLs, such as:\n\n\nhttp://api.example.com/accounts/1/\n\n\n\nRather than relative URLs, such as:\n\n\n/accounts/1/\n\n\n\nIf you \ndo\n want to use relative URLs, you should explicitly pass \n{'request': None}\n\nin the serializer context.\n\n\nHow hyperlinked views are determined\n\n\nThere needs to be a way of determining which views should be used for hyperlinking to model instances.\n\n\nBy default hyperlinks are expected to correspond to a view name that matches the style \n'{model_name}-detail'\n, and looks up the instance by a \npk\n keyword argument.\n\n\nYou can override a URL field view name and lookup field by using either, or both of, the \nview_name\n and \nlookup_field\n options in the \nextra_kwargs\n setting, like so:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('account_url', 'account_name', 'users', 'created')\n        extra_kwargs = {\n            'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}\n            'users': {'lookup_field': 'username'}\n        }\n\n\n\nAlternatively you can set the fields on the serializer explicitly. For example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    url = serializers.HyperlinkedIdentityField(\n        view_name='accounts',\n        lookup_field='slug'\n    )\n    users = serializers.HyperlinkedRelatedField(\n        view_name='user-detail',\n        lookup_field='username',\n        many=True,\n        read_only=True\n    )\n\n    class Meta:\n        model = Account\n        fields = ('url', 'account_name', 'users', 'created')\n\n\n\n\n\nTip\n: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the \nrepr\n of a \nHyperlinkedModelSerializer\n instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.\n\n\n\n\nChanging the URL field name\n\n\nThe name of the URL field defaults to 'url'.  You can override this globally, by using the \nURL_FIELD_NAME\n setting.\n\n\n\n\nListSerializer\n\n\nThe \nListSerializer\n class provides the behavior for serializing and validating multiple objects at once. You won't \ntypically\n need to use \nListSerializer\n directly, but should instead simply pass \nmany=True\n when instantiating a serializer.\n\n\nWhen a serializer is instantiated and \nmany=True\n is passed, a \nListSerializer\n instance will be created. The serializer class then becomes a child of the parent \nListSerializer\n\n\nThe following argument can also be passed to a \nListSerializer\n field or a serializer that is passed \nmany=True\n:\n\n\nallow_empty\n\n\nThis is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nCustomizing \nListSerializer\n behavior\n\n\nThere \nare\n a few use cases when you might want to customize the \nListSerializer\n behavior. For example:\n\n\n\n\nYou want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.\n\n\nYou want to customize the create or update behavior of multiple objects.\n\n\n\n\nFor these cases you can modify the class that is used when \nmany=True\n is passed, by using the \nlist_serializer_class\n option on the serializer \nMeta\n class.\n\n\nFor example:\n\n\nclass CustomListSerializer(serializers.ListSerializer):\n    ...\n\nclass CustomSerializer(serializers.Serializer):\n    ...\n    class Meta:\n        list_serializer_class = CustomListSerializer\n\n\n\nCustomizing multiple create\n\n\nThe default implementation for multiple object creation is to simply call \n.create()\n for each item in the list. If you want to customize this behavior, you'll need to customize the \n.create()\n method on \nListSerializer\n class that is used when \nmany=True\n is passed.\n\n\nFor example:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n    def create(self, validated_data):\n        books = [Book(**item) for item in validated_data]\n        return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n    ...\n    class Meta:\n        list_serializer_class = BookListSerializer\n\n\n\nCustomizing multiple update\n\n\nBy default the \nListSerializer\n class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.\n\n\nTo support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:\n\n\n\n\nHow do you determine which instance should be updated for each item in the list of data?\n\n\nHow should insertions be handled? Are they invalid, or do they create new objects?\n\n\nHow should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?\n\n\nHow should ordering be handled? Does changing the position of two items imply any state change or is it ignored?\n\n\n\n\nYou will need to add an explicit \nid\n field to the instance serializer. The default implicitly-generated \nid\n field is marked as \nread_only\n. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's \nupdate\n method.\n\n\nHere's an example of how you might choose to implement multiple updates:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n    def update(self, instance, validated_data):\n        # Maps for id-\ninstance and id-\ndata item.\n        book_mapping = {book.id: book for book in instance}\n        data_mapping = {item['id']: item for item in validated_data}\n\n        # Perform creations and updates.\n        ret = []\n        for book_id, data in data_mapping.items():\n            book = book_mapping.get(book_id, None)\n            if book is None:\n                ret.append(self.child.create(data))\n            else:\n                ret.append(self.child.update(book, data))\n\n        # Perform deletions.\n        for book_id, book in book_mapping.items():\n            if book_id not in data_mapping:\n                book.delete()\n\n        return ret\n\nclass BookSerializer(serializers.Serializer):\n    # We need to identify elements in the list using their primary key,\n    # so use a writable field here, rather than the default which would be read-only.\n    id = serializers.IntegerField()\n\n    ...\n    id = serializers.IntegerField(required=False)\n\n    class Meta:\n        list_serializer_class = BookListSerializer\n\n\n\nIt 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 \nallow_add_remove\n behavior that was present in REST framework 2.\n\n\nCustomizing ListSerializer initialization\n\n\nWhen a serializer with \nmany=True\n is instantiated, we need to determine which arguments and keyword arguments should be passed to the \n.__init__()\n method for both the child \nSerializer\n class, and for the parent \nListSerializer\n class.\n\n\nThe default implementation is to pass all arguments to both classes, except for \nvalidators\n, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.\n\n\nOccasionally you might need to explicitly specify how the child and parent classes should be instantiated when \nmany=True\n is passed. You can do so by using the \nmany_init\n class method.\n\n\n    @classmethod\n    def many_init(cls, *args, **kwargs):\n        # Instantiate the child serializer.\n        kwargs['child'] = cls()\n        # Instantiate the parent list serializer.\n        return CustomListSerializer(*args, **kwargs)\n\n\n\n\n\nBaseSerializer\n\n\nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns any errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class-based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    player_name = models.CharField(max_length=10)\n    score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n    instance = HighScore.objects.get(pk=pk)\n    serializer = HighScoreSerializer(instance)\n    return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n    queryset = HighScore.objects.order_by('-score')\n    serializer = HighScoreSerializer(queryset, many=True)\n    return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_internal_value(self, data):\n        score = data.get('score')\n        player_name = data.get('player_name')\n\n        # Perform the data validation.\n        if not score:\n            raise ValidationError({\n                'score': 'This field is required.'\n            })\n        if not player_name:\n            raise ValidationError({\n                'player_name': 'This field is required.'\n            })\n        if len(player_name) \n 10:\n            raise ValidationError({\n                'player_name': 'May not be more than 10 characters.'\n            })\n\n        # Return the validated values. This will be available as\n        # the `.validated_data` property.\n        return {\n            'score': int(score),\n            'player_name': player_name\n        }\n\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n    def create(self, validated_data):\n        return HighScore.objects.create(**validated_data)\n\n\n\nCreating new base classes\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n    \"\"\"\n    A read-only serializer that coerces arbitrary complex objects\n    into primitive representations.\n    \"\"\"\n    def to_representation(self, obj):\n        for attribute_name in dir(obj):\n            attribute = getattr(obj, attribute_name)\n            if attribute_name('_'):\n                # Ignore private attributes.\n                pass\n            elif hasattr(attribute, '__call__'):\n                # Ignore methods and other callables.\n                pass\n            elif isinstance(attribute, (str, int, bool, float, type(None))):\n                # Primitive types can be passed through unmodified.\n                output[attribute_name] = attribute\n            elif isinstance(attribute, list):\n                # Recursively deal with items in lists.\n                output[attribute_name] = [\n                    self.to_representation(item) for item in attribute\n                ]\n            elif isinstance(attribute, dict):\n                # Recursively deal with items in dictionaries.\n                output[attribute_name] = {\n                    str(key): self.to_representation(value)\n                    for key, value in attribute.items()\n                }\n            else:\n                # Force anything else to its string representation.\n                output[attribute_name] = str(attribute)\n\n\n\n\n\nAdvanced serializer usage\n\n\nOverriding serialization and deserialization behavior\n\n\nIf you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the \n.to_representation()\n or \n.to_internal_value()\n methods.\n\n\nSome reasons this might be useful include...\n\n\n\n\nAdding new behavior for new serializer base classes.\n\n\nModifying the behavior slightly for an existing class.\n\n\nImproving serialization performance for a frequently accessed API endpoint that returns lots of data.\n\n\n\n\nThe signatures for these methods are as follows:\n\n\n.to_representation(self, obj)\n\n\nTakes 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.\n\n\n.to_internal_value(self, data)\n\n\nTakes the unvalidated incoming data as input and should return the validated data that will be made available as \nserializer.validated_data\n. The return value will also be passed to the \n.create()\n or \n.update()\n methods if \n.save()\n is called on the serializer class.\n\n\nIf any of the validation fails, then the method should raise a \nserializers.ValidationError(errors)\n. Typically the \nerrors\n argument here will be a dictionary mapping field names to error messages.\n\n\nThe \ndata\n argument passed to this method will normally be the value of \nrequest.data\n, so the datatype it provides will depend on the parser classes you have configured for your API.\n\n\nDynamically modifying fields\n\n\nOnce a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the \n.fields\n attribute.  Accessing and modifying this attribute allows you to dynamically modify the serializer.\n\n\nModifying the \nfields\n 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.\n\n\nExample\n\n\nFor 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:\n\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n    \"\"\"\n    A ModelSerializer that takes an additional `fields` argument that\n    controls which fields should be displayed.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        # Don't pass the 'fields' arg up to the superclass\n        fields = kwargs.pop('fields', None)\n\n        # Instantiate the superclass normally\n        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n        if fields is not None:\n            # Drop any fields that are not specified in the `fields` argument.\n            allowed = set(fields)\n            existing = set(self.fields.keys())\n            for field_name in existing - allowed:\n                self.fields.pop(field_name)\n\n\n\nThis would then allow you to do the following:\n\n\n class UserSerializer(DynamicFieldsModelSerializer):\n\n     class Meta:\n\n         model = User\n\n         fields = ('id', 'username', 'email')\n\n\n\n print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n\n\n\n print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}\n\n\n\nCustomizing the default fields\n\n\nREST framework 2 provided an API to allow developers to override how a \nModelSerializer\n class would automatically generate the default set of fields.\n\n\nThis API included the \n.get_field()\n, \n.get_pk_field()\n and other methods.\n\n\nBecause 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.\n\n\nA new interface for controlling this behavior is currently planned for REST framework 3.1.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango REST marshmallow\n\n\nThe \ndjango-rest-marshmallow\n package provides an alternative implementation for serializers, using the python \nmarshmallow\n library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.\n\n\nSerpy\n\n\nThe \nserpy\n package is an alternative implementation for serializers that is built for speed. \nSerpy\n serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.\n\n\nMongoengineModelSerializer\n\n\nThe \ndjango-rest-framework-mongoengine\n package provides a \nMongoEngineModelSerializer\n serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\nGeoFeatureModelSerializer\n\n\nThe \ndjango-rest-framework-gis\n package provides a \nGeoFeatureModelSerializer\n serializer class that supports GeoJSON both for read and write operations.\n\n\nHStoreSerializer\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreSerializer\n to support \ndjango-hstore\n \nDictionaryField\n model field and its \nschema-mode\n feature.\n\n\nDynamic REST\n\n\nThe \ndynamic-rest\n package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \nform\n submissions per the (inactive) \nHTML JSON Form specification\n.  The serializer facilitates processing of arbitrarily nested JSON structures within HTML.  For example, \ninput name=\"items[0][id]\" value=\"5\"\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.", 
    +            "text": "Serializers\n\n\n\n\nExpanding the usefulness of the serializers is something that we would\nlike to address.  However, it's not a trivial problem, and it\nwill take some serious design work.\n\n\n Russell Keith-Magee, \nDjango users group\n\n\n\n\nSerializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into \nJSON\n, \nXML\n or other content types.  Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.\n\n\nThe serializers in REST framework work very similarly to Django's \nForm\n and \nModelForm\n classes. We provide a \nSerializer\n class which gives you a powerful, generic way to control the output of your responses, as well as a \nModelSerializer\n class which provides a useful shortcut for creating serializers that deal with model instances and querysets.\n\n\nDeclaring Serializers\n\n\nLet's start by creating a simple object we can use for example purposes:\n\n\nfrom datetime import datetime\n\nclass Comment(object):\n    def __init__(self, email, content, created=None):\n        self.email = email\n        self.content = content\n        self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n\n\n\nWe'll declare a serializer that we can use to serialize and deserialize data that corresponds to \nComment\n objects.\n\n\nDeclaring a serializer looks very similar to declaring a form:\n\n\nfrom rest_framework import serializers\n\nclass CommentSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nSerializing objects\n\n\nWe can now use \nCommentSerializer\n to serialize a comment, or list of comments. Again, using the \nSerializer\n class looks a lot like using a \nForm\n class.\n\n\nserializer = CommentSerializer(comment)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes.  To finalise the serialization process we render the data into \njson\n.\n\n\nfrom rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n\n\n\nDeserializing objects\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\nfrom rest_framework.parsers import JSONParser\n\nstream = BytesIO(json)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a dictionary of validated data.\n\n\nserializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n\n\n\nSaving instances\n\n\nIf we want to be able to return complete object instances based on the validated data we need to implement one or both of the \n.create()\n and \nupdate()\n methods. For example:\n\n\nclass CommentSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n    def create(self, validated_data):\n        return Comment(**validated_data)\n\n    def update(self, instance, validated_data):\n        instance.email = validated_data.get('email', instance.email)\n        instance.content = validated_data.get('content', instance.content)\n        instance.created = validated_data.get('created', instance.created)\n        return instance\n\n\n\nIf your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if \nComment\n was a Django model, the methods might look like this:\n\n\n    def create(self, validated_data):\n        return Comment.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        instance.email = validated_data.get('email', instance.email)\n        instance.content = validated_data.get('content', instance.content)\n        instance.created = validated_data.get('created', instance.created)\n        instance.save()\n        return instance\n\n\n\nNow when deserializing data, we can call \n.save()\n to return an object instance, based on the validated data.\n\n\ncomment = serializer.save()\n\n\n\nCalling \n.save()\n will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:\n\n\n# .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n\n\n\nBoth the \n.create()\n and \n.update()\n methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.\n\n\nPassing additional attributes to \n.save()\n\n\nSometimes 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.\n\n\nYou can do so by including additional keyword arguments when calling \n.save()\n. For example:\n\n\nserializer.save(owner=request.user)\n\n\n\nAny additional keyword arguments will be included in the \nvalidated_data\n argument when \n.create()\n or \n.update()\n are called.\n\n\nOverriding \n.save()\n directly.\n\n\nIn some cases the \n.create()\n and \n.update()\n 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.\n\n\nIn these cases you might instead choose to override \n.save()\n directly, as being more readable and meaningful.\n\n\nFor example:\n\n\nclass ContactForm(serializers.Serializer):\n    email = serializers.EmailField()\n    message = serializers.CharField()\n\n    def save(self):\n        email = self.validated_data['email']\n        message = self.validated_data['message']\n        send_email(from=email, message=message)\n\n\n\nNote that in the case above we're now having to access the serializer \n.validated_data\n property directly.\n\n\nValidation\n\n\nWhen deserializing data, you always need to call \nis_valid()\n before attempting to access the validated data, or save an object instance. If any validation errors occur, the \n.errors\n property will contain a dictionary representing the resulting error messages.  For example:\n\n\nserializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}\n\n\n\nEach 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 \nnon_field_errors\n key may also be present, and will list any general validation errors. The name of the \nnon_field_errors\n key may be customized using the \nNON_FIELD_ERRORS_KEY\n REST framework setting.\n\n\nWhen deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.\n\n\nRaising an exception on invalid data\n\n\nThe \n.is_valid()\n method takes an optional \nraise_exception\n flag that will cause it to raise a \nserializers.ValidationError\n exception if there are validation errors.\n\n\nThese exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return \nHTTP 400 Bad Request\n responses by default.\n\n\n# Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True)\n\n\n\nField-level validation\n\n\nYou can specify custom field-level validation by adding \n.validate_\nfield_name\n methods to your \nSerializer\n subclass.  These are similar to the \n.clean_\nfield_name\n methods on Django forms.\n\n\nThese methods take a single argument, which is the field value that requires validation.\n\n\nYour \nvalidate_\nfield_name\n methods should return the validated value or raise a \nserializers.ValidationError\n.  For example:\n\n\nfrom rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n    title = serializers.CharField(max_length=100)\n    content = serializers.CharField()\n\n    def validate_title(self, value):\n        \"\"\"\n        Check that the blog post is about Django.\n        \"\"\"\n        if 'django' not in value.lower():\n            raise serializers.ValidationError(\"Blog post is not about Django\")\n        return value\n\n\n\n\n\nNote:\n If your \nfield_name\n is declared on your serializer with the parameter \nrequired=False\n then this validation step will not take place if the field is not included.\n\n\n\n\nObject-level validation\n\n\nTo do any other validation that requires access to multiple fields, add a method called \n.validate()\n to your \nSerializer\n subclass.  This method takes a single argument, which is a dictionary of field values.  It should raise a \nValidationError\n if necessary, or just return the validated values.  For example:\n\n\nfrom rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n    description = serializers.CharField(max_length=100)\n    start = serializers.DateTimeField()\n    finish = serializers.DateTimeField()\n\n    def validate(self, data):\n        \"\"\"\n        Check that the start is before the stop.\n        \"\"\"\n        if data['start'] \n data['finish']:\n            raise serializers.ValidationError(\"finish must occur after start\")\n        return data\n\n\n\nValidators\n\n\nIndividual fields on a serializer can include validators, by declaring them on the field instance, for example:\n\n\ndef multiple_of_ten(value):\n    if value % 10 != 0:\n        raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n    score = IntegerField(validators=[multiple_of_ten])\n    ...\n\n\n\nSerializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner \nMeta\n class, like so:\n\n\nclass EventSerializer(serializers.Serializer):\n    name = serializers.CharField()\n    room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n    date = serializers.DateField()\n\n    class Meta:\n        # Each room only has one event per day.\n        validators = UniqueTogetherValidator(\n            queryset=Event.objects.all(),\n            fields=['room_number', 'date']\n        )\n\n\n\nFor more information see the \nvalidators documentation\n.\n\n\nAccessing the initial data and instance\n\n\nWhen passing an initial object or queryset to a serializer instance, the object will be made available as \n.instance\n. If no initial object is passed then the \n.instance\n attribute will be \nNone\n.\n\n\nWhen passing data to a serializer instance, the unmodified data will be made available as \n.initial_data\n. If the data keyword argument is not passed then the \n.initial_data\n attribute will not exist.\n\n\nPartial updates\n\n\nBy default, serializers must be passed values for all required fields or they will raise validation errors. You can use the \npartial\n argument in order to allow partial updates.\n\n\n# Update `comment` with partial data\nserializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)\n\n\n\nDealing with nested objects\n\n\nThe 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.\n\n\nThe \nSerializer\n class is itself a type of \nField\n, and can be used to represent relationships where one object type is nested inside another.\n\n\nclass UserSerializer(serializers.Serializer):\n    email = serializers.EmailField()\n    username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer()\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nIf a nested representation may optionally accept the \nNone\n value you should pass the \nrequired=False\n flag to the nested serializer.\n\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer(required=False)  # May be an anonymous user.\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nSimilarly if a nested representation should be a list of items, you should pass the \nmany=True\n flag to the nested serialized.\n\n\nclass CommentSerializer(serializers.Serializer):\n    user = UserSerializer(required=False)\n    edits = EditItemSerializer(many=True)  # A nested list of 'edit' items.\n    content = serializers.CharField(max_length=200)\n    created = serializers.DateTimeField()\n\n\n\nWritable nested representations\n\n\nWhen 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.\n\n\nserializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}\n\n\n\nSimilarly, the \n.validated_data\n property will include nested data structures.\n\n\nWriting \n.create()\n methods for nested representations\n\n\nIf you're supporting writable nested representations you'll need to write \n.create()\n or \n.update()\n methods that handle saving multiple objects.\n\n\nThe following example demonstrates how you might handle creating a user with a nested profile object.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n    profile = ProfileSerializer()\n\n    class Meta:\n        model = User\n        fields = ('username', 'email', 'profile')\n\n    def create(self, validated_data):\n        profile_data = validated_data.pop('profile')\n        user = User.objects.create(**validated_data)\n        Profile.objects.create(user=user, **profile_data)\n        return user\n\n\n\nWriting \n.update()\n methods for nested representations\n\n\nFor updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is \nNone\n, or not provided, which of the following should occur?\n\n\n\n\nSet the relationship to \nNULL\n in the database.\n\n\nDelete the associated instance.\n\n\nIgnore the data and leave the instance as it is.\n\n\nRaise a validation error.\n\n\n\n\nHere's an example for an \nupdate()\n method on our previous \nUserSerializer\n class.\n\n\n    def update(self, instance, validated_data):\n        profile_data = validated_data.pop('profile')\n        # Unless the application properly enforces that this field is\n        # always set, the follow could raise a `DoesNotExist`, which\n        # would need to be handled.\n        profile = instance.profile\n\n        instance.username = validated_data.get('username', instance.username)\n        instance.email = validated_data.get('email', instance.email)\n        instance.save()\n\n        profile.is_premium_member = profile_data.get(\n            'is_premium_member',\n            profile.is_premium_member\n        )\n        profile.has_support_contract = profile_data.get(\n            'has_support_contract',\n            profile.has_support_contract\n         )\n        profile.save()\n\n        return instance\n\n\n\nBecause 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 \nModelSerializer\n \n.create()\n and \n.update()\n methods do not include support for writable nested representations.\n\n\nIt 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.\n\n\nHandling saving related instances in model manager classes\n\n\nAn alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.\n\n\nFor example, suppose we wanted to ensure that \nUser\n instances and \nProfile\n instances are always created together as a pair. We might write a custom manager class that looks something like this:\n\n\nclass UserManager(models.Manager):\n    ...\n\n    def create(self, username, email, is_premium_member=False, has_support_contract=False):\n        user = User(username=username, email=email)\n        user.save()\n        profile = Profile(\n            user=user,\n            is_premium_member=is_premium_member,\n            has_support_contract=has_support_contract\n        )\n        profile.save()\n        return user\n\n\n\nThis manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our \n.create()\n method on the serializer class can now be re-written to use the new manager method.\n\n\ndef create(self, validated_data):\n    return User.objects.create(\n        username=validated_data['username'],\n        email=validated_data['email']\n        is_premium_member=validated_data['profile']['is_premium_member']\n        has_support_contract=validated_data['profile']['has_support_contract']\n    )\n\n\n\nFor more details on this approach see the Django documentation on \nmodel managers\n, and \nthis blogpost on using model and manager classes\n.\n\n\nDealing with multiple objects\n\n\nThe \nSerializer\n class can also handle serializing or deserializing lists of objects.\n\n\nSerializing multiple objects\n\n\nTo serialize a queryset or list of objects instead of a single object instance, you should pass the \nmany=True\n flag when instantiating the serializer.  You can then pass a queryset or list of objects to be serialized.\n\n\nqueryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n#     {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n#     {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n#     {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n\n\n\nDeserializing multiple objects\n\n\nThe 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 \nListSerializer\n documentation below.\n\n\nIncluding extra context\n\n\nThere 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.\n\n\nYou can provide arbitrary additional context by passing a \ncontext\n argument when instantiating the serializer.  For example:\n\n\nserializer = AccountSerializer(account, context={'request': request})\nserializer.data\n# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n\n\n\nThe context dictionary can be used within any serializer field logic, such as a custom \n.to_representation()\n method, by accessing the \nself.context\n attribute.\n\n\n\n\nModelSerializer\n\n\nOften you'll want serializer classes that map closely to Django model definitions.\n\n\nThe \nModelSerializer\n class provides a shortcut that lets you automatically create a \nSerializer\n class with fields that correspond to the Model fields.\n\n\nThe \nModelSerializer\n class is the same as a regular \nSerializer\n class, except that\n:\n\n\n\n\nIt will automatically generate a set of fields for you, based on the model.\n\n\nIt will automatically generate validators for the serializer, such as unique_together validators.\n\n\nIt includes simple default implementations of \n.create()\n and \n.update()\n.\n\n\n\n\nDeclaring a \nModelSerializer\n looks like this:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n\n\n\nBy default, all the model fields on the class will be mapped to a corresponding serializer fields.\n\n\nAny relationships such as foreign keys on the model will be mapped to \nPrimaryKeyRelatedField\n. Reverse relationships are not included by default unless explicitly included as specified in the \nserializer relations\n documentation.\n\n\nInspecting a \nModelSerializer\n\n\nSerializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with \nModelSerializers\n where you want to determine what set of fields and validators are being automatically created for you.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print(repr(serializer))\nAccountSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    name = CharField(allow_blank=True, max_length=100, required=False)\n    owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nSpecifying which fields to include\n\n\nIf you only want a subset of the default fields to be used in a model serializer, you can do so using \nfields\n or \nexclude\n options, just as you would with a \nModelForm\n. It is strongly recommended that you explicitly set all fields that should be serialized using the \nfields\n attribute. This will make it less likely to result in unintentionally exposing data when your models change.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n\n\n\nYou can also set the \nfields\n attribute to the special value \n'__all__'\n to indicate that all fields in the model should be used.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = '__all__'\n\n\n\nYou can set the \nexclude\n attribute to a list of fields to be excluded from the serializer.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        exclude = ('users',)\n\n\n\nIn the example above, if the \nAccount\n model had 3 fields \naccount_name\n, \nusers\n, and \ncreated\n, this will result in the fields \naccount_name\n and \ncreated\n to be serialized.\n\n\nThe names in the \nfields\n and \nexclude\n attributes will normally map to model fields on the model class.\n\n\nAlternatively names in the \nfields\n options can map to properties or methods which take no arguments that exist on the model class.\n\n\nSpecifying nested serialization\n\n\nThe default \nModelSerializer\n uses primary keys for relationships, but you can also easily generate nested representations using the \ndepth\n option:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n        depth = 1\n\n\n\nThe \ndepth\n option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.\n\n\nIf you want to customize the way the serialization is done you'll need to define the field yourself.\n\n\nSpecifying fields explicitly\n\n\nYou can add extra fields to a \nModelSerializer\n or override the default fields by declaring fields on the class, just as you would for a \nSerializer\n class.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    url = serializers.CharField(source='get_absolute_url', read_only=True)\n    groups = serializers.PrimaryKeyRelatedField(many=True)\n\n    class Meta:\n        model = Account\n\n\n\nExtra fields can correspond to any property or callable on the model.\n\n\nSpecifying read only fields\n\n\nYou may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the \nread_only=True\n attribute, you may use the shortcut Meta option, \nread_only_fields\n.\n\n\nThis option should be a list or tuple of field names, and is declared as follows:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'users', 'created')\n        read_only_fields = ('account_name',)\n\n\n\nModel fields which have \neditable=False\n set, and \nAutoField\n fields will be set to read-only by default, and do not need to be added to the \nread_only_fields\n option.\n\n\n\n\nNote\n: There is a special-case where a read-only field is part of a \nunique_together\n constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.\n\n\nThe right way to deal with this is to specify the field explicitly on the serializer, providing both the \nread_only=True\n and \ndefault=\u2026\n keyword arguments.\n\n\nOne example of this is a read-only relation to the currently authenticated \nUser\n which is \nunique_together\n with another identifier. In this case you would declare the user field like so:\n\n\nuser = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())\n\n\n\nPlease review the \nValidators Documentation\n for details on the \nUniqueTogetherValidator\n and \nCurrentUserDefault\n classes.\n\n\n\n\nAdditional keyword arguments\n\n\nThere is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the \nextra_kwargs\n option. As in the case of \nread_only_fields\n, this means you do not need to explicitly declare the field on the serializer.\n\n\nThis option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:\n\n\nclass CreateUserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = ('email', 'username', 'password')\n        extra_kwargs = {'password': {'write_only': True}}\n\n    def create(self, validated_data):\n        user = User(\n            email=validated_data['email'],\n            username=validated_data['username']\n        )\n        user.set_password(validated_data['password'])\n        user.save()\n        return user\n\n\n\nRelational fields\n\n\nWhen serializing model instances, there are a number of different ways you might choose to represent relationships.  The default representation for \nModelSerializer\n is to use the primary keys of the related instances.\n\n\nAlternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.\n\n\nFor full details see the \nserializer relations\n documentation.\n\n\nInheritance of the 'Meta' class\n\n\nThe inner \nMeta\n class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's \nModel\n and \nModelForm\n classes. If you want the \nMeta\n class to inherit from a parent class you must do so explicitly. For example:\n\n\nclass AccountSerializer(MyBaseSerializer):\n    class Meta(MyBaseSerializer.Meta):\n        model = Account\n\n\n\nTypically we would recommend \nnot\n using inheritance on inner Meta classes, but instead declaring all options explicitly.\n\n\nCustomizing field mappings\n\n\nThe ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.\n\n\nNormally if a \nModelSerializer\n does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular \nSerializer\n 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.\n\n\n.serializer_field_mapping\n\n\nA 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.\n\n\n.serializer_related_field\n\n\nThis property should be the serializer field class, that is used for relational fields by default.\n\n\nFor \nModelSerializer\n this defaults to \nPrimaryKeyRelatedField\n.\n\n\nFor \nHyperlinkedModelSerializer\n this defaults to \nserializers.HyperlinkedRelatedField\n.\n\n\nserializer_url_field\n\n\nThe serializer field class that should be used for any \nurl\n field on the serializer.\n\n\nDefaults to \nserializers.HyperlinkedIdentityField\n\n\nserializer_choice_field\n\n\nThe serializer field class that should be used for any choice fields on the serializer.\n\n\nDefaults to \nserializers.ChoiceField\n\n\nThe field_class and field_kwargs API\n\n\nThe 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 \n(field_class, field_kwargs)\n.\n\n\n.build_standard_field(self, field_name, model_field)\n\n\nCalled to generate a serializer field that maps to a standard model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_field_mapping\n attribute.\n\n\n.build_relational_field(self, field_name, relation_info)\n\n\nCalled to generate a serializer field that maps to a relational model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_relational_field\n attribute.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_nested_field(self, field_name, relation_info, nested_depth)\n\n\nCalled to generate a serializer field that maps to a relational model field, when the \ndepth\n option has been set.\n\n\nThe default implementation dynamically creates a nested serializer class based on either \nModelSerializer\n or \nHyperlinkedModelSerializer\n.\n\n\nThe \nnested_depth\n will be the value of the \ndepth\n option, minus one.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_property_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field that maps to a property or zero-argument method on the model class.\n\n\nThe default implementation returns a \nReadOnlyField\n class.\n\n\n.build_url_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field for the serializer's own \nurl\n field. The default implementation returns a \nHyperlinkedIdentityField\n class.\n\n\n.build_unknown_field(self, field_name, model_class)\n\n\nCalled when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.\n\n\n\n\nHyperlinkedModelSerializer\n\n\nThe \nHyperlinkedModelSerializer\n class is similar to the \nModelSerializer\n class except that it uses hyperlinks to represent relationships, rather than primary keys.\n\n\nBy default the serializer will include a \nurl\n field instead of a primary key field.\n\n\nThe url field will be represented using a \nHyperlinkedIdentityField\n serializer field, and any relationships on the model will be represented using a \nHyperlinkedRelatedField\n serializer field.\n\n\nYou can explicitly include the primary key by adding it to the \nfields\n option, for example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('url', 'id', 'account_name', 'users', 'created')\n\n\n\nAbsolute and relative URLs\n\n\nWhen instantiating a \nHyperlinkedModelSerializer\n you must include the current\n\nrequest\n in the serializer context, for example:\n\n\nserializer = AccountSerializer(queryset, context={'request': request})\n\n\n\nDoing so will ensure that the hyperlinks can include an appropriate hostname,\nso that the resulting representation uses fully qualified URLs, such as:\n\n\nhttp://api.example.com/accounts/1/\n\n\n\nRather than relative URLs, such as:\n\n\n/accounts/1/\n\n\n\nIf you \ndo\n want to use relative URLs, you should explicitly pass \n{'request': None}\n\nin the serializer context.\n\n\nHow hyperlinked views are determined\n\n\nThere needs to be a way of determining which views should be used for hyperlinking to model instances.\n\n\nBy default hyperlinks are expected to correspond to a view name that matches the style \n'{model_name}-detail'\n, and looks up the instance by a \npk\n keyword argument.\n\n\nYou can override a URL field view name and lookup field by using either, or both of, the \nview_name\n and \nlookup_field\n options in the \nextra_kwargs\n setting, like so:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('account_url', 'account_name', 'users', 'created')\n        extra_kwargs = {\n            'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}\n            'users': {'lookup_field': 'username'}\n        }\n\n\n\nAlternatively you can set the fields on the serializer explicitly. For example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n    url = serializers.HyperlinkedIdentityField(\n        view_name='accounts',\n        lookup_field='slug'\n    )\n    users = serializers.HyperlinkedRelatedField(\n        view_name='user-detail',\n        lookup_field='username',\n        many=True,\n        read_only=True\n    )\n\n    class Meta:\n        model = Account\n        fields = ('url', 'account_name', 'users', 'created')\n\n\n\n\n\nTip\n: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the \nrepr\n of a \nHyperlinkedModelSerializer\n instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.\n\n\n\n\nChanging the URL field name\n\n\nThe name of the URL field defaults to 'url'.  You can override this globally, by using the \nURL_FIELD_NAME\n setting.\n\n\n\n\nListSerializer\n\n\nThe \nListSerializer\n class provides the behavior for serializing and validating multiple objects at once. You won't \ntypically\n need to use \nListSerializer\n directly, but should instead simply pass \nmany=True\n when instantiating a serializer.\n\n\nWhen a serializer is instantiated and \nmany=True\n is passed, a \nListSerializer\n instance will be created. The serializer class then becomes a child of the parent \nListSerializer\n\n\nThe following argument can also be passed to a \nListSerializer\n field or a serializer that is passed \nmany=True\n:\n\n\nallow_empty\n\n\nThis is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nCustomizing \nListSerializer\n behavior\n\n\nThere \nare\n a few use cases when you might want to customize the \nListSerializer\n behavior. For example:\n\n\n\n\nYou want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.\n\n\nYou want to customize the create or update behavior of multiple objects.\n\n\n\n\nFor these cases you can modify the class that is used when \nmany=True\n is passed, by using the \nlist_serializer_class\n option on the serializer \nMeta\n class.\n\n\nFor example:\n\n\nclass CustomListSerializer(serializers.ListSerializer):\n    ...\n\nclass CustomSerializer(serializers.Serializer):\n    ...\n    class Meta:\n        list_serializer_class = CustomListSerializer\n\n\n\nCustomizing multiple create\n\n\nThe default implementation for multiple object creation is to simply call \n.create()\n for each item in the list. If you want to customize this behavior, you'll need to customize the \n.create()\n method on \nListSerializer\n class that is used when \nmany=True\n is passed.\n\n\nFor example:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n    def create(self, validated_data):\n        books = [Book(**item) for item in validated_data]\n        return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n    ...\n    class Meta:\n        list_serializer_class = BookListSerializer\n\n\n\nCustomizing multiple update\n\n\nBy default the \nListSerializer\n class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.\n\n\nTo support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:\n\n\n\n\nHow do you determine which instance should be updated for each item in the list of data?\n\n\nHow should insertions be handled? Are they invalid, or do they create new objects?\n\n\nHow should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?\n\n\nHow should ordering be handled? Does changing the position of two items imply any state change or is it ignored?\n\n\n\n\nYou will need to add an explicit \nid\n field to the instance serializer. The default implicitly-generated \nid\n field is marked as \nread_only\n. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's \nupdate\n method.\n\n\nHere's an example of how you might choose to implement multiple updates:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n    def update(self, instance, validated_data):\n        # Maps for id-\ninstance and id-\ndata item.\n        book_mapping = {book.id: book for book in instance}\n        data_mapping = {item['id']: item for item in validated_data}\n\n        # Perform creations and updates.\n        ret = []\n        for book_id, data in data_mapping.items():\n            book = book_mapping.get(book_id, None)\n            if book is None:\n                ret.append(self.child.create(data))\n            else:\n                ret.append(self.child.update(book, data))\n\n        # Perform deletions.\n        for book_id, book in book_mapping.items():\n            if book_id not in data_mapping:\n                book.delete()\n\n        return ret\n\nclass BookSerializer(serializers.Serializer):\n    # We need to identify elements in the list using their primary key,\n    # so use a writable field here, rather than the default which would be read-only.\n    id = serializers.IntegerField()\n\n    ...\n    id = serializers.IntegerField(required=False)\n\n    class Meta:\n        list_serializer_class = BookListSerializer\n\n\n\nIt 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 \nallow_add_remove\n behavior that was present in REST framework 2.\n\n\nCustomizing ListSerializer initialization\n\n\nWhen a serializer with \nmany=True\n is instantiated, we need to determine which arguments and keyword arguments should be passed to the \n.__init__()\n method for both the child \nSerializer\n class, and for the parent \nListSerializer\n class.\n\n\nThe default implementation is to pass all arguments to both classes, except for \nvalidators\n, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.\n\n\nOccasionally you might need to explicitly specify how the child and parent classes should be instantiated when \nmany=True\n is passed. You can do so by using the \nmany_init\n class method.\n\n\n    @classmethod\n    def many_init(cls, *args, **kwargs):\n        # Instantiate the child serializer.\n        kwargs['child'] = cls()\n        # Instantiate the parent list serializer.\n        return CustomListSerializer(*args, **kwargs)\n\n\n\n\n\nBaseSerializer\n\n\nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns any errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class-based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    player_name = models.CharField(max_length=10)\n    score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n    instance = HighScore.objects.get(pk=pk)\n    serializer = HighScoreSerializer(instance)\n    return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n    queryset = HighScore.objects.order_by('-score')\n    serializer = HighScoreSerializer(queryset, many=True)\n    return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_internal_value(self, data):\n        score = data.get('score')\n        player_name = data.get('player_name')\n\n        # Perform the data validation.\n        if not score:\n            raise ValidationError({\n                'score': 'This field is required.'\n            })\n        if not player_name:\n            raise ValidationError({\n                'player_name': 'This field is required.'\n            })\n        if len(player_name) \n 10:\n            raise ValidationError({\n                'player_name': 'May not be more than 10 characters.'\n            })\n\n        # Return the validated values. This will be available as\n        # the `.validated_data` property.\n        return {\n            'score': int(score),\n            'player_name': player_name\n        }\n\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n    def create(self, validated_data):\n        return HighScore.objects.create(**validated_data)\n\n\n\nCreating new base classes\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n    \"\"\"\n    A read-only serializer that coerces arbitrary complex objects\n    into primitive representations.\n    \"\"\"\n    def to_representation(self, obj):\n        for attribute_name in dir(obj):\n            attribute = getattr(obj, attribute_name)\n            if attribute_name('_'):\n                # Ignore private attributes.\n                pass\n            elif hasattr(attribute, '__call__'):\n                # Ignore methods and other callables.\n                pass\n            elif isinstance(attribute, (str, int, bool, float, type(None))):\n                # Primitive types can be passed through unmodified.\n                output[attribute_name] = attribute\n            elif isinstance(attribute, list):\n                # Recursively deal with items in lists.\n                output[attribute_name] = [\n                    self.to_representation(item) for item in attribute\n                ]\n            elif isinstance(attribute, dict):\n                # Recursively deal with items in dictionaries.\n                output[attribute_name] = {\n                    str(key): self.to_representation(value)\n                    for key, value in attribute.items()\n                }\n            else:\n                # Force anything else to its string representation.\n                output[attribute_name] = str(attribute)\n\n\n\n\n\nAdvanced serializer usage\n\n\nOverriding serialization and deserialization behavior\n\n\nIf you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the \n.to_representation()\n or \n.to_internal_value()\n methods.\n\n\nSome reasons this might be useful include...\n\n\n\n\nAdding new behavior for new serializer base classes.\n\n\nModifying the behavior slightly for an existing class.\n\n\nImproving serialization performance for a frequently accessed API endpoint that returns lots of data.\n\n\n\n\nThe signatures for these methods are as follows:\n\n\n.to_representation(self, obj)\n\n\nTakes 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.\n\n\n.to_internal_value(self, data)\n\n\nTakes the unvalidated incoming data as input and should return the validated data that will be made available as \nserializer.validated_data\n. The return value will also be passed to the \n.create()\n or \n.update()\n methods if \n.save()\n is called on the serializer class.\n\n\nIf any of the validation fails, then the method should raise a \nserializers.ValidationError(errors)\n. Typically the \nerrors\n argument here will be a dictionary mapping field names to error messages.\n\n\nThe \ndata\n argument passed to this method will normally be the value of \nrequest.data\n, so the datatype it provides will depend on the parser classes you have configured for your API.\n\n\nDynamically modifying fields\n\n\nOnce a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the \n.fields\n attribute.  Accessing and modifying this attribute allows you to dynamically modify the serializer.\n\n\nModifying the \nfields\n 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.\n\n\nExample\n\n\nFor 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:\n\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n    \"\"\"\n    A ModelSerializer that takes an additional `fields` argument that\n    controls which fields should be displayed.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        # Don't pass the 'fields' arg up to the superclass\n        fields = kwargs.pop('fields', None)\n\n        # Instantiate the superclass normally\n        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n        if fields is not None:\n            # Drop any fields that are not specified in the `fields` argument.\n            allowed = set(fields)\n            existing = set(self.fields.keys())\n            for field_name in existing - allowed:\n                self.fields.pop(field_name)\n\n\n\nThis would then allow you to do the following:\n\n\n class UserSerializer(DynamicFieldsModelSerializer):\n\n     class Meta:\n\n         model = User\n\n         fields = ('id', 'username', 'email')\n\n\n\n print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n\n\n\n print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}\n\n\n\nCustomizing the default fields\n\n\nREST framework 2 provided an API to allow developers to override how a \nModelSerializer\n class would automatically generate the default set of fields.\n\n\nThis API included the \n.get_field()\n, \n.get_pk_field()\n and other methods.\n\n\nBecause 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.\n\n\nA new interface for controlling this behavior is currently planned for REST framework 3.1.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango REST marshmallow\n\n\nThe \ndjango-rest-marshmallow\n package provides an alternative implementation for serializers, using the python \nmarshmallow\n library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.\n\n\nSerpy\n\n\nThe \nserpy\n package is an alternative implementation for serializers that is built for speed. \nSerpy\n serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.\n\n\nMongoengineModelSerializer\n\n\nThe \ndjango-rest-framework-mongoengine\n package provides a \nMongoEngineModelSerializer\n serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\nGeoFeatureModelSerializer\n\n\nThe \ndjango-rest-framework-gis\n package provides a \nGeoFeatureModelSerializer\n serializer class that supports GeoJSON both for read and write operations.\n\n\nHStoreSerializer\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreSerializer\n to support \ndjango-hstore\n \nDictionaryField\n model field and its \nschema-mode\n feature.\n\n\nDynamic REST\n\n\nThe \ndynamic-rest\n package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.\n\n\nDynamic Fields Mixin\n\n\nThe \ndrf-dynamic-fields\n package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \nform\n submissions per the (inactive) \nHTML JSON Form specification\n.  The serializer facilitates processing of arbitrarily nested JSON structures within HTML.  For example, \ninput name=\"items[0][id]\" value=\"5\"\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.", 
                 "title": "Serializers"
             }, 
             {
    @@ -1695,6 +1695,11 @@
                 "text": "The  dynamic-rest  package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.", 
                 "title": "Dynamic REST"
             }, 
    +        {
    +            "location": "/api-guide/serializers/#dynamic-fields-mixin", 
    +            "text": "The  drf-dynamic-fields  package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.", 
    +            "title": "Dynamic Fields Mixin"
    +        }, 
             {
                 "location": "/api-guide/serializers/#html-json-forms", 
                 "text": "The  html-json-forms  package provides an algorithm and serializer for processing  form  submissions per the (inactive)  HTML JSON Form specification .  The serializer facilitates processing of arbitrarily nested JSON structures within HTML.  For example,  input name=\"items[0][id]\" value=\"5\"  will be interpreted as  {\"items\": [{\"id\": \"5\"}]} .", 
    @@ -1702,7 +1707,7 @@
             }, 
             {
                 "location": "/api-guide/fields/", 
    -            "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes.  They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments.  Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-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.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n 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.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.\n\n\nThe \ndefault\n is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.\n\n\nMay 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 \nset_context\n 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 \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field.  May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n 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.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA 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 \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n    day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n    style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n    choices=['red', 'green', 'blue'],\n    style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n 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.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, 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.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n.  Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n  Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included.  Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n 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'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting \nlocalize\n will force the value to \nTrue\n.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\nlocalize\n Set to \nTrue\n to enable localization of input and output based on the current locale. This will also force \ncoerce_to_string\n to \nTrue\n. Defaults to \nFalse\n. Note that data formatting is enabled if you have set \nUSE_L10N=True\n in your settings file.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n.  This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now_add\n model fields.\nauto_now\n and \n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer.  For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n    created = serializers.DateTimeField()\n\n    class Meta:\n        model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=api_settings.DATE_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format.  If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=api_settings.TIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format.  If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation.  Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package.  The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n   child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n    child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n    child = CharField()\n\n\n\nJSONField\n\n\nA 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.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, if \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n 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.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n 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.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed.  In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model.  For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis 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.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n    days_since_joined = serializers.SerializerMethodField()\n\n    class Meta:\n        model = User\n\n    def get_days_since_joined(self, obj):\n        return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n 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, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. 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.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n    \"\"\"\n    A color represented in the RGB colorspace.\n    \"\"\"\n    def __init__(self, red, green, blue):\n        assert(red \n= 0 and green \n= 0 and blue \n= 0)\n        assert(red \n 256 and green \n 256 and blue \n 256)\n        self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n    \"\"\"\n    Color objects are serialized into 'rgb(#, #, #)' notation.\n    \"\"\"\n    def to_representation(self, obj):\n        return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n    def to_internal_value(self, data):\n        data = data.strip('rgb(').rstrip(')')\n        red, green, blue = [int(col) for col in data.split(',')]\n        return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object.  If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n    def get_attribute(self, obj):\n        # We pass the object instance onto `to_representation`,\n        # not just the field attribute.\n        return obj\n\n    def to_representation(self, obj):\n        \"\"\"\n        Serialize the object's class name.\n        \"\"\"\n        return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n    if not isinstance(data, six.text_type):\n        msg = 'Incorrect type. Expected a string, but got %s'\n        raise ValidationError(msg % type(data).__name__)\n\n    if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n        raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n    data = data.strip('rgb(').rstrip(')')\n    red, green, blue = [int(col) for col in data.split(',')]\n\n    if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n        raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n    return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n    'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n    'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n    'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n    if not isinstance(data, six.text_type):\n        msg = 'Incorrect type. Expected a string, but got %s'\n        self.fail('incorrect_type', input_type=type(data).__name__)\n\n    if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n        self.fail('incorrect_format')\n\n    data = data.strip('rgb(').rstrip(')')\n    red, green, blue = [int(col) for col in data.split(',')]\n\n    if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n        self.fail('out_of_range')\n\n    return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n 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.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a  \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", 
    +            "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes.  They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments.  Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-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.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n 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.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.\n\n\nThe \ndefault\n is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.\n\n\nMay 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 \nset_context\n 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 \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field.  May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n 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.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA 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 \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n    day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n    style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n    choices=['red', 'green', 'blue'],\n    style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n 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.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, 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.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n.  Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n  Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included.  Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n 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'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting \nlocalize\n will force the value to \nTrue\n.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\nlocalize\n Set to \nTrue\n to enable localization of input and output based on the current locale. This will also force \ncoerce_to_string\n to \nTrue\n. Defaults to \nFalse\n. Note that data formatting is enabled if you have set \nUSE_L10N=True\n in your settings file.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n.  This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now\n and \nauto_now_add\n model fields.\n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer.  For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n    created = serializers.DateTimeField()\n\n    class Meta:\n        model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=api_settings.DATE_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format.  If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=api_settings.TIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format.  If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date.  If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation.  Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package.  The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n   child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n    child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n    child = CharField()\n\n\n\nJSONField\n\n\nA 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.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, if \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Account\n        fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n 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.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n 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.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed.  In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model.  For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis 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.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n    days_since_joined = serializers.SerializerMethodField()\n\n    class Meta:\n        model = User\n\n    def get_days_since_joined(self, obj):\n        return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n 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, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. 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.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n    \"\"\"\n    A color represented in the RGB colorspace.\n    \"\"\"\n    def __init__(self, red, green, blue):\n        assert(red \n= 0 and green \n= 0 and blue \n= 0)\n        assert(red \n 256 and green \n 256 and blue \n 256)\n        self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n    \"\"\"\n    Color objects are serialized into 'rgb(#, #, #)' notation.\n    \"\"\"\n    def to_representation(self, obj):\n        return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n    def to_internal_value(self, data):\n        data = data.strip('rgb(').rstrip(')')\n        red, green, blue = [int(col) for col in data.split(',')]\n        return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object.  If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n    def get_attribute(self, obj):\n        # We pass the object instance onto `to_representation`,\n        # not just the field attribute.\n        return obj\n\n    def to_representation(self, obj):\n        \"\"\"\n        Serialize the object's class name.\n        \"\"\"\n        return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n    if not isinstance(data, six.text_type):\n        msg = 'Incorrect type. Expected a string, but got %s'\n        raise ValidationError(msg % type(data).__name__)\n\n    if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n        raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n    data = data.strip('rgb(').rstrip(')')\n    red, green, blue = [int(col) for col in data.split(',')]\n\n    if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n        raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n    return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n    'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n    'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n    'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n    if not isinstance(data, six.text_type):\n        msg = 'Incorrect type. Expected a string, but got %s'\n        self.fail('incorrect_type', input_type=type(data).__name__)\n\n    if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n        self.fail('incorrect_format')\n\n    data = data.strip('rgb(').rstrip(')')\n    red, green, blue = [int(col) for col in data.split(',')]\n\n    if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n        self.fail('out_of_range')\n\n    return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n 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.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a  \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", 
                 "title": "Serializer fields"
             }, 
             {
    @@ -2032,7 +2037,7 @@
             }, 
             {
                 "location": "/api-guide/relations/", 
    -            "text": "Serializer relations\n\n\n\n\nBad programmers worry about the code.\nGood programmers worry about data structures and their relationships.\n\n\n \nLinus Torvalds\n\n\n\n\nRelational fields are used to represent model relationships.  They can be applied to \nForeignKey\n, \nManyToManyField\n and \nOneToOneField\n relationships, as well as to reverse relationships, and custom relationships such as \nGenericForeignKey\n.\n\n\n\n\nNote:\n The relational fields are declared in \nrelations.py\n, but by convention you should import them from the \nserializers\n module, using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nInspecting relationships.\n\n\nWhen using the \nModelSerializer\n 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.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print repr(serializer)  # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    name = CharField(allow_blank=True, max_length=100, required=False)\n    owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nAPI Reference\n\n\nIn 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.\n\n\nclass Album(models.Model):\n    album_name = models.CharField(max_length=100)\n    artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n    album = models.ForeignKey(Album, related_name='tracks')\n    order = models.IntegerField()\n    title = models.CharField(max_length=100)\n    duration = models.IntegerField()\n\n    class Meta:\n        unique_together = ('album', 'order')\n        ordering = ['order']\n\n    def __unicode__(self):\n        return '%d: %s' % (self.order, self.title)\n\n\n\nStringRelatedField\n\n\nStringRelatedField\n may be used to represent the target of the relationship using its \n__unicode__\n method.\n\n\nFor example, the following serializer.\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.StringRelatedField(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to the following representation.\n\n\n{\n    'album_name': 'Things We Lost In The Fire',\n    'artist': 'Low',\n    'tracks': [\n        '1: Sunflower',\n        '2: Whitetail',\n        '3: Dinosaur Act',\n        ...\n    ]\n}\n\n\n\nThis field is read only.\n\n\nArguments\n:\n\n\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\n\n\nPrimaryKeyRelatedField\n\n\nPrimaryKeyRelatedField\n may be used to represent the target of the relationship using its primary key.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'The Roots',\n    'artist': 'Undun',\n    'tracks': [\n        89,\n        90,\n        91,\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nArguments\n:\n\n\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\npk_field\n - Set to a field to control serialization/deserialization of the primary key's value. For example, \npk_field=UUIDField(format='hex')\n would serialize a UUID primary key into its compact hex representation.\n\n\n\n\nHyperlinkedRelatedField\n\n\nHyperlinkedRelatedField\n may be used to represent the target of the relationship using a hyperlink.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.HyperlinkedRelatedField(\n        many=True,\n        read_only=True,\n        view_name='track-detail'\n    )\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'Graceland',\n    'artist': 'Paul Simon',\n    'tracks': [\n        'http://www.example.com/api/tracks/45/',\n        'http://www.example.com/api/tracks/46/',\n        'http://www.example.com/api/tracks/47/',\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\n\n\nNote\n: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the \nlookup_field\n and \nlookup_url_kwarg\n arguments.\n\n\nThis is suitable for URLs that contain a single primary key or slug argument as part of the URL.\n\n\nIf you require more complex hyperlinked representation you'll need to customize the field, as described in the \ncustom hyperlinked fields\n section, below.\n\n\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship.  If you're using \nthe standard router classes\n this will be a string with the format \nmodelname\n-detail\n. \nrequired\n.\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup.  Should correspond to a URL keyword argument on the referenced view.  Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\nSlugRelatedField\n\n\nSlugRelatedField\n may be used to represent the target of the relationship using a field on the target.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.SlugRelatedField(\n        many=True,\n        read_only=True,\n        slug_field='title'\n     )\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'Dear John',\n    'artist': 'Loney Dear',\n    'tracks': [\n        'Airport Surroundings',\n        'Everything Turns to You',\n        'I Was Only Going Out',\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nWhen using \nSlugRelatedField\n as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with \nunique=True\n.\n\n\nArguments\n:\n\n\n\n\nslug_field\n - The field on the target that should be used to represent it.  This should be a field that uniquely identifies any given instance.  For example, \nusername\n.  \nrequired\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\n\n\nHyperlinkedIdentityField\n\n\nThis field can be applied as an identity relationship, such as the \n'url'\n field on  a HyperlinkedModelSerializer.  It can also be used for an attribute on the object.  For example, the following serializer:\n\n\nclass AlbumSerializer(serializers.HyperlinkedModelSerializer):\n    track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'track_listing')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'The Eraser',\n    'artist': 'Thom Yorke',\n    'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n\n\n\nThis field is always read-only.\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship.  If you're using \nthe standard router classes\n this will be a string with the format \nmodel_name\n-detail\n.  \nrequired\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup.  Should correspond to a URL keyword argument on the referenced view.  Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\n\n\nNested relationships\n\n\nNested relationships can be expressed by using serializers as fields.\n\n\nIf the field is used to represent a to-many relationship, you should add the \nmany=True\n flag to the serializer field.\n\n\nExample\n\n\nFor example, the following serializer:\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Track\n        fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackSerializer(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a nested representation like this:\n\n\n album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse')\n\n Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\nTrack: Track object\n\n\n serializer = AlbumSerializer(instance=album)\n\n serializer.data\n{\n    'album_name': 'The Grey Album',\n    'artist': 'Danger Mouse',\n    'tracks': [\n        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n        {'order': 3, 'title': 'Encore', 'duration': 159},\n        ...\n    ],\n}\n\n\n\nWritable nested serializers\n\n\nBy default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create \ncreate()\n and/or \nupdate()\n methods in order to explicitly specify how the child relationships should be saved.\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Track\n        fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackSerializer(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n    def create(self, validated_data):\n        tracks_data = validated_data.pop('tracks')\n        album = Album.objects.create(**validated_data)\n        for track_data in tracks_data:\n            Track.objects.create(album=album, **track_data)\n        return album\n\n\n data = {\n    'album_name': 'The Grey Album',\n    'artist': 'Danger Mouse',\n    'tracks': [\n        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n        {'order': 3, 'title': 'Encore', 'duration': 159},\n    ],\n}\n\n serializer = AlbumSerializer(data=data)\n\n serializer.is_valid()\nTrue\n\n serializer.save()\n\nAlbum: Album object\n\n\n\n\n\n\nCustom relational fields\n\n\nIn rare cases where none of the existing relational styles fit the representation you need,\nyou can implement a completely custom relational field, that describes exactly how the\noutput representation should be generated from the model instance.\n\n\nTo implement a custom relational field, you should override \nRelatedField\n, and implement the \n.to_representation(self, value)\n method. This method takes the target of the field as the \nvalue\n argument, and should return the representation that should be used to serialize the target. The \nvalue\n argument will typically be a model instance.\n\n\nIf you want to implement a read-write relational field, you must also implement the \n.to_internal_value(self, data)\n method.\n\n\nTo provide a dynamic queryset based on the \ncontext\n, you can also override \n.get_queryset(self)\n instead of specifying \n.queryset\n on the class or when initializing the field.\n\n\nExample\n\n\nFor example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.\n\n\nimport time\n\nclass TrackListingField(serializers.RelatedField):\n    def to_representation(self, value):\n        duration = time.strftime('%M:%S', time.gmtime(value.duration))\n        return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackListingField(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nThis custom field would then serialize to the following representation.\n\n\n{\n    'album_name': 'Sometimes I Wish We Were an Eagle',\n    'artist': 'Bill Callahan',\n    'tracks': [\n        'Track 1: Jim Cain (04:39)',\n        'Track 2: Eid Ma Clack Shaw (04:19)',\n        'Track 3: The Wind and the Dove (04:34)',\n        ...\n    ]\n}\n\n\n\n\n\nCustom hyperlinked fields\n\n\nIn 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.\n\n\nYou can achieve this by overriding \nHyperlinkedRelatedField\n. There are two methods that may be overridden:\n\n\nget_url(self, obj, view_name, request, format)\n\n\nThe \nget_url\n method is used to map the object instance to its URL representation.\n\n\nMay raise a \nNoReverseMatch\n if the \nview_name\n and \nlookup_field\n\nattributes are not configured to correctly match the URL conf.\n\n\nget_object(self, queryset, view_name, view_args, view_kwargs)\n\n\nIf you want to support a writable hyperlinked field then you'll also want to override \nget_object\n, 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.\n\n\nThe return value of this method should the object that corresponds to the matched URL conf arguments.\n\n\nMay raise an \nObjectDoesNotExist\n exception.\n\n\nExample\n\n\nSay we have a URL for a customer object that takes two keyword arguments, like so:\n\n\n/api/\norganization_slug\n/customers/\ncustomer_pk\n/\n\n\n\nThis cannot be represented with the default implementation, which accepts only a single lookup field.\n\n\nIn this case we'd need to override \nHyperlinkedRelatedField\n to get the behavior we want:\n\n\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n    # We define these as class attributes, so we don't need to pass them as arguments.\n    view_name = 'customer-detail'\n    queryset = Customer.objects.all()\n\n    def get_url(self, obj, view_name, request, format):\n        url_kwargs = {\n            'organization_slug': obj.organization.slug,\n            'customer_pk': obj.pk\n        }\n        return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n    def get_object(self, view_name, view_args, view_kwargs):\n        lookup_kwargs = {\n           'organization__slug': view_kwargs['organization_slug'],\n           'pk': view_kwargs['customer_pk']\n        }\n        return self.get_queryset().get(**lookup_kwargs)\n\n\n\nNote that if you wanted to use this style together with the generic views then you'd also need to override \n.get_object\n on the view in order to get the correct lookup behavior.\n\n\nGenerally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.\n\n\n\n\nFurther notes\n\n\nThe \nqueryset\n argument\n\n\nThe \nqueryset\n argument is only ever required for \nwritable\n 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.\n\n\nIn version 2.x a serializer class could \nsometimes\n automatically determine the \nqueryset\n argument \nif\n a \nModelSerializer\n class was being used.\n\n\nThis behavior is now replaced with \nalways\n using an explicit \nqueryset\n argument for writable relational fields.\n\n\nDoing so reduces the amount of hidden 'magic' that \nModelSerializer\n provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the \nModelSerializer\n shortcut, or using fully explicit \nSerializer\n classes.\n\n\nCustomizing the HTML display\n\n\nThe built-in \n__str__\n method of the model will be used to generate string representations of the objects used to populate the \nchoices\n property. These choices are used to populate select HTML inputs in the browsable API.\n\n\nTo provide customized representations for such inputs, override \ndisplay_value()\n of a \nRelatedField\n subclass. This method will receive a model object, and should return a string suitable for representing it. For example:\n\n\nclass TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):\n    def display_value(self, instance):\n        return 'Track: %s' % (instance.title)\n\n\n\nSelect field cutoffs\n\n\nWhen 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\u2026\" will be displayed.\n\n\nThis 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.\n\n\nThere are two keyword arguments you can use to control this behavior:\n\n\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to \nNone\n to disable any limiting. Defaults to \n1000\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nIn cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the \nstyle\n keyword argument. For example:\n\n\nassigned_to = serializers.SlugRelatedField(\n   queryset=User.objects.all(),\n   slug_field='username',\n   style={'base_template': 'input.html'}\n)\n\n\n\nReverse relations\n\n\nNote that reverse relationships are not automatically included by the \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes.  To include a reverse relationship, you must explicitly add it to the fields list.  For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    class Meta:\n        fields = ('tracks', ...)\n\n\n\nYou'll normally want to ensure that you've set an appropriate \nrelated_name\n argument on the relationship, that you can use as the field name.  For example:\n\n\nclass Track(models.Model):\n    album = models.ForeignKey(Album, related_name='tracks')\n    ...\n\n\n\nIf you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the \nfields\n argument.  For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    class Meta:\n        fields = ('track_set', ...)\n\n\n\nSee the Django documentation on \nreverse relationships\n for more details.\n\n\nGeneric relationships\n\n\nIf you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.\n\n\nFor example, given the following model for a tag, which has a generic relationship with other arbitrary models:\n\n\nclass TaggedItem(models.Model):\n    \"\"\"\n    Tags arbitrary model instances using a generic relation.\n\n    See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/\n    \"\"\"\n    tag_name = models.SlugField()\n    content_type = models.ForeignKey(ContentType)\n    object_id = models.PositiveIntegerField()\n    tagged_object = GenericForeignKey('content_type', 'object_id')\n\n    def __unicode__(self):\n        return self.tag_name\n\n\n\nAnd the following two models, which may have associated tags:\n\n\nclass Bookmark(models.Model):\n    \"\"\"\n    A bookmark consists of a URL, and 0 or more descriptive tags.\n    \"\"\"\n    url = models.URLField()\n    tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n    \"\"\"\n    A note consists of some text, and 0 or more descriptive tags.\n    \"\"\"\n    text = models.CharField(max_length=1000)\n    tags = GenericRelation(TaggedItem)\n\n\n\nWe could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.\n\n\nclass TaggedObjectRelatedField(serializers.RelatedField):\n    \"\"\"\n    A custom field to use for the `tagged_object` generic relationship.\n    \"\"\"\n\n    def to_representation(self, value):\n        \"\"\"\n        Serialize tagged objects to a simple textual representation.\n        \"\"\"\n        if isinstance(value, Bookmark):\n            return 'Bookmark: ' + value.url\n        elif isinstance(value, Note):\n            return 'Note: ' + value.text\n        raise Exception('Unexpected type of tagged object')\n\n\n\nIf you need the target of the relationship to have a nested representation, you can use the required serializers inside the \n.to_representation()\n method:\n\n\n    def to_representation(self, value):\n        \"\"\"\n        Serialize bookmark instances using a bookmark serializer,\n        and note instances using a note serializer.\n        \"\"\"\n        if isinstance(value, Bookmark):\n            serializer = BookmarkSerializer(value)\n        elif isinstance(value, Note):\n            serializer = NoteSerializer(value)\n        else:\n            raise Exception('Unexpected type of tagged object')\n\n        return serializer.data\n\n\n\nNote that reverse generic keys, expressed using the \nGenericRelation\n field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.\n\n\nFor more information see \nthe Django documentation on generic relations\n.\n\n\nManyToManyFields with a Through Model\n\n\nBy default, relational fields that target a \nManyToManyField\n with a\n\nthrough\n model specified are set to read-only.\n\n\nIf you explicitly specify a relational field pointing to a\n\nManyToManyField\n with a through model, be sure to set \nread_only\n\nto \nTrue\n.\n\n\n\n\nThird Party Packages\n\n\nThe following third party packages are also available.\n\n\nDRF Nested Routers\n\n\nThe \ndrf-nested-routers package\n provides routers and relationship fields for working with nested resources.\n\n\nRest Framework Generic Relations\n\n\nThe \nrest-framework-generic-relations\n library provides read/write serialization for generic foreign keys.", 
    +            "text": "Serializer relations\n\n\n\n\nBad programmers worry about the code.\nGood programmers worry about data structures and their relationships.\n\n\n \nLinus Torvalds\n\n\n\n\nRelational fields are used to represent model relationships.  They can be applied to \nForeignKey\n, \nManyToManyField\n and \nOneToOneField\n relationships, as well as to reverse relationships, and custom relationships such as \nGenericForeignKey\n.\n\n\n\n\nNote:\n The relational fields are declared in \nrelations.py\n, but by convention you should import them from the \nserializers\n module, using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nInspecting relationships.\n\n\nWhen using the \nModelSerializer\n 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.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print repr(serializer)  # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    name = CharField(allow_blank=True, max_length=100, required=False)\n    owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nAPI Reference\n\n\nIn 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.\n\n\nclass Album(models.Model):\n    album_name = models.CharField(max_length=100)\n    artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n    album = models.ForeignKey(Album, related_name='tracks')\n    order = models.IntegerField()\n    title = models.CharField(max_length=100)\n    duration = models.IntegerField()\n\n    class Meta:\n        unique_together = ('album', 'order')\n        ordering = ['order']\n\n    def __unicode__(self):\n        return '%d: %s' % (self.order, self.title)\n\n\n\nStringRelatedField\n\n\nStringRelatedField\n may be used to represent the target of the relationship using its \n__unicode__\n method.\n\n\nFor example, the following serializer.\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.StringRelatedField(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to the following representation.\n\n\n{\n    'album_name': 'Things We Lost In The Fire',\n    'artist': 'Low',\n    'tracks': [\n        '1: Sunflower',\n        '2: Whitetail',\n        '3: Dinosaur Act',\n        ...\n    ]\n}\n\n\n\nThis field is read only.\n\n\nArguments\n:\n\n\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\n\n\nPrimaryKeyRelatedField\n\n\nPrimaryKeyRelatedField\n may be used to represent the target of the relationship using its primary key.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'Undun',\n    'artist': 'The Roots',\n    'tracks': [\n        89,\n        90,\n        91,\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nArguments\n:\n\n\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\npk_field\n - Set to a field to control serialization/deserialization of the primary key's value. For example, \npk_field=UUIDField(format='hex')\n would serialize a UUID primary key into its compact hex representation.\n\n\n\n\nHyperlinkedRelatedField\n\n\nHyperlinkedRelatedField\n may be used to represent the target of the relationship using a hyperlink.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.HyperlinkedRelatedField(\n        many=True,\n        read_only=True,\n        view_name='track-detail'\n    )\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'Graceland',\n    'artist': 'Paul Simon',\n    'tracks': [\n        'http://www.example.com/api/tracks/45/',\n        'http://www.example.com/api/tracks/46/',\n        'http://www.example.com/api/tracks/47/',\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\n\n\nNote\n: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the \nlookup_field\n and \nlookup_url_kwarg\n arguments.\n\n\nThis is suitable for URLs that contain a single primary key or slug argument as part of the URL.\n\n\nIf you require more complex hyperlinked representation you'll need to customize the field, as described in the \ncustom hyperlinked fields\n section, below.\n\n\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship.  If you're using \nthe standard router classes\n this will be a string with the format \nmodelname\n-detail\n. \nrequired\n.\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup.  Should correspond to a URL keyword argument on the referenced view.  Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\nSlugRelatedField\n\n\nSlugRelatedField\n may be used to represent the target of the relationship using a field on the target.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.SlugRelatedField(\n        many=True,\n        read_only=True,\n        slug_field='title'\n     )\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'Dear John',\n    'artist': 'Loney Dear',\n    'tracks': [\n        'Airport Surroundings',\n        'Everything Turns to You',\n        'I Was Only Going Out',\n        ...\n    ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nWhen using \nSlugRelatedField\n as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with \nunique=True\n.\n\n\nArguments\n:\n\n\n\n\nslug_field\n - The field on the target that should be used to represent it.  This should be a field that uniquely identifies any given instance.  For example, \nusername\n.  \nrequired\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\n\n\nHyperlinkedIdentityField\n\n\nThis field can be applied as an identity relationship, such as the \n'url'\n field on  a HyperlinkedModelSerializer.  It can also be used for an attribute on the object.  For example, the following serializer:\n\n\nclass AlbumSerializer(serializers.HyperlinkedModelSerializer):\n    track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'track_listing')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n    'album_name': 'The Eraser',\n    'artist': 'Thom Yorke',\n    'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n\n\n\nThis field is always read-only.\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship.  If you're using \nthe standard router classes\n this will be a string with the format \nmodel_name\n-detail\n.  \nrequired\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup.  Should correspond to a URL keyword argument on the referenced view.  Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\n\n\nNested relationships\n\n\nNested relationships can be expressed by using serializers as fields.\n\n\nIf the field is used to represent a to-many relationship, you should add the \nmany=True\n flag to the serializer field.\n\n\nExample\n\n\nFor example, the following serializer:\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Track\n        fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackSerializer(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a nested representation like this:\n\n\n album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse')\n\n Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\nTrack: Track object\n\n\n serializer = AlbumSerializer(instance=album)\n\n serializer.data\n{\n    'album_name': 'The Grey Album',\n    'artist': 'Danger Mouse',\n    'tracks': [\n        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n        {'order': 3, 'title': 'Encore', 'duration': 159},\n        ...\n    ],\n}\n\n\n\nWritable nested serializers\n\n\nBy default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create \ncreate()\n and/or \nupdate()\n methods in order to explicitly specify how the child relationships should be saved.\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Track\n        fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackSerializer(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n    def create(self, validated_data):\n        tracks_data = validated_data.pop('tracks')\n        album = Album.objects.create(**validated_data)\n        for track_data in tracks_data:\n            Track.objects.create(album=album, **track_data)\n        return album\n\n\n data = {\n    'album_name': 'The Grey Album',\n    'artist': 'Danger Mouse',\n    'tracks': [\n        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n        {'order': 3, 'title': 'Encore', 'duration': 159},\n    ],\n}\n\n serializer = AlbumSerializer(data=data)\n\n serializer.is_valid()\nTrue\n\n serializer.save()\n\nAlbum: Album object\n\n\n\n\n\n\nCustom relational fields\n\n\nIn rare cases where none of the existing relational styles fit the representation you need,\nyou can implement a completely custom relational field, that describes exactly how the\noutput representation should be generated from the model instance.\n\n\nTo implement a custom relational field, you should override \nRelatedField\n, and implement the \n.to_representation(self, value)\n method. This method takes the target of the field as the \nvalue\n argument, and should return the representation that should be used to serialize the target. The \nvalue\n argument will typically be a model instance.\n\n\nIf you want to implement a read-write relational field, you must also implement the \n.to_internal_value(self, data)\n method.\n\n\nTo provide a dynamic queryset based on the \ncontext\n, you can also override \n.get_queryset(self)\n instead of specifying \n.queryset\n on the class or when initializing the field.\n\n\nExample\n\n\nFor example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.\n\n\nimport time\n\nclass TrackListingField(serializers.RelatedField):\n    def to_representation(self, value):\n        duration = time.strftime('%M:%S', time.gmtime(value.duration))\n        return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    tracks = TrackListingField(many=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')\n\n\n\nThis custom field would then serialize to the following representation.\n\n\n{\n    'album_name': 'Sometimes I Wish We Were an Eagle',\n    'artist': 'Bill Callahan',\n    'tracks': [\n        'Track 1: Jim Cain (04:39)',\n        'Track 2: Eid Ma Clack Shaw (04:19)',\n        'Track 3: The Wind and the Dove (04:34)',\n        ...\n    ]\n}\n\n\n\n\n\nCustom hyperlinked fields\n\n\nIn 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.\n\n\nYou can achieve this by overriding \nHyperlinkedRelatedField\n. There are two methods that may be overridden:\n\n\nget_url(self, obj, view_name, request, format)\n\n\nThe \nget_url\n method is used to map the object instance to its URL representation.\n\n\nMay raise a \nNoReverseMatch\n if the \nview_name\n and \nlookup_field\n\nattributes are not configured to correctly match the URL conf.\n\n\nget_object(self, queryset, view_name, view_args, view_kwargs)\n\n\nIf you want to support a writable hyperlinked field then you'll also want to override \nget_object\n, 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.\n\n\nThe return value of this method should the object that corresponds to the matched URL conf arguments.\n\n\nMay raise an \nObjectDoesNotExist\n exception.\n\n\nExample\n\n\nSay we have a URL for a customer object that takes two keyword arguments, like so:\n\n\n/api/\norganization_slug\n/customers/\ncustomer_pk\n/\n\n\n\nThis cannot be represented with the default implementation, which accepts only a single lookup field.\n\n\nIn this case we'd need to override \nHyperlinkedRelatedField\n to get the behavior we want:\n\n\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n    # We define these as class attributes, so we don't need to pass them as arguments.\n    view_name = 'customer-detail'\n    queryset = Customer.objects.all()\n\n    def get_url(self, obj, view_name, request, format):\n        url_kwargs = {\n            'organization_slug': obj.organization.slug,\n            'customer_pk': obj.pk\n        }\n        return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n    def get_object(self, view_name, view_args, view_kwargs):\n        lookup_kwargs = {\n           'organization__slug': view_kwargs['organization_slug'],\n           'pk': view_kwargs['customer_pk']\n        }\n        return self.get_queryset().get(**lookup_kwargs)\n\n\n\nNote that if you wanted to use this style together with the generic views then you'd also need to override \n.get_object\n on the view in order to get the correct lookup behavior.\n\n\nGenerally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.\n\n\n\n\nFurther notes\n\n\nThe \nqueryset\n argument\n\n\nThe \nqueryset\n argument is only ever required for \nwritable\n 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.\n\n\nIn version 2.x a serializer class could \nsometimes\n automatically determine the \nqueryset\n argument \nif\n a \nModelSerializer\n class was being used.\n\n\nThis behavior is now replaced with \nalways\n using an explicit \nqueryset\n argument for writable relational fields.\n\n\nDoing so reduces the amount of hidden 'magic' that \nModelSerializer\n provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the \nModelSerializer\n shortcut, or using fully explicit \nSerializer\n classes.\n\n\nCustomizing the HTML display\n\n\nThe built-in \n__str__\n method of the model will be used to generate string representations of the objects used to populate the \nchoices\n property. These choices are used to populate select HTML inputs in the browsable API.\n\n\nTo provide customized representations for such inputs, override \ndisplay_value()\n of a \nRelatedField\n subclass. This method will receive a model object, and should return a string suitable for representing it. For example:\n\n\nclass TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):\n    def display_value(self, instance):\n        return 'Track: %s' % (instance.title)\n\n\n\nSelect field cutoffs\n\n\nWhen 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\u2026\" will be displayed.\n\n\nThis 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.\n\n\nThere are two keyword arguments you can use to control this behavior:\n\n\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to \nNone\n to disable any limiting. Defaults to \n1000\n.\n\n\nhtml_cutoff_text\n - 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 \n\"More than {count} items\u2026\"\n\n\n\n\nYou can also control these globally using the settings \nHTML_SELECT_CUTOFF\n and \nHTML_SELECT_CUTOFF_TEXT\n.\n\n\nIn cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the \nstyle\n keyword argument. For example:\n\n\nassigned_to = serializers.SlugRelatedField(\n   queryset=User.objects.all(),\n   slug_field='username',\n   style={'base_template': 'input.html'}\n)\n\n\n\nReverse relations\n\n\nNote that reverse relationships are not automatically included by the \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes.  To include a reverse relationship, you must explicitly add it to the fields list.  For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    class Meta:\n        fields = ('tracks', ...)\n\n\n\nYou'll normally want to ensure that you've set an appropriate \nrelated_name\n argument on the relationship, that you can use as the field name.  For example:\n\n\nclass Track(models.Model):\n    album = models.ForeignKey(Album, related_name='tracks')\n    ...\n\n\n\nIf you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the \nfields\n argument.  For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n    class Meta:\n        fields = ('track_set', ...)\n\n\n\nSee the Django documentation on \nreverse relationships\n for more details.\n\n\nGeneric relationships\n\n\nIf you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.\n\n\nFor example, given the following model for a tag, which has a generic relationship with other arbitrary models:\n\n\nclass TaggedItem(models.Model):\n    \"\"\"\n    Tags arbitrary model instances using a generic relation.\n\n    See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/\n    \"\"\"\n    tag_name = models.SlugField()\n    content_type = models.ForeignKey(ContentType)\n    object_id = models.PositiveIntegerField()\n    tagged_object = GenericForeignKey('content_type', 'object_id')\n\n    def __unicode__(self):\n        return self.tag_name\n\n\n\nAnd the following two models, which may have associated tags:\n\n\nclass Bookmark(models.Model):\n    \"\"\"\n    A bookmark consists of a URL, and 0 or more descriptive tags.\n    \"\"\"\n    url = models.URLField()\n    tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n    \"\"\"\n    A note consists of some text, and 0 or more descriptive tags.\n    \"\"\"\n    text = models.CharField(max_length=1000)\n    tags = GenericRelation(TaggedItem)\n\n\n\nWe could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.\n\n\nclass TaggedObjectRelatedField(serializers.RelatedField):\n    \"\"\"\n    A custom field to use for the `tagged_object` generic relationship.\n    \"\"\"\n\n    def to_representation(self, value):\n        \"\"\"\n        Serialize tagged objects to a simple textual representation.\n        \"\"\"\n        if isinstance(value, Bookmark):\n            return 'Bookmark: ' + value.url\n        elif isinstance(value, Note):\n            return 'Note: ' + value.text\n        raise Exception('Unexpected type of tagged object')\n\n\n\nIf you need the target of the relationship to have a nested representation, you can use the required serializers inside the \n.to_representation()\n method:\n\n\n    def to_representation(self, value):\n        \"\"\"\n        Serialize bookmark instances using a bookmark serializer,\n        and note instances using a note serializer.\n        \"\"\"\n        if isinstance(value, Bookmark):\n            serializer = BookmarkSerializer(value)\n        elif isinstance(value, Note):\n            serializer = NoteSerializer(value)\n        else:\n            raise Exception('Unexpected type of tagged object')\n\n        return serializer.data\n\n\n\nNote that reverse generic keys, expressed using the \nGenericRelation\n field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.\n\n\nFor more information see \nthe Django documentation on generic relations\n.\n\n\nManyToManyFields with a Through Model\n\n\nBy default, relational fields that target a \nManyToManyField\n with a\n\nthrough\n model specified are set to read-only.\n\n\nIf you explicitly specify a relational field pointing to a\n\nManyToManyField\n with a through model, be sure to set \nread_only\n\nto \nTrue\n.\n\n\n\n\nThird Party Packages\n\n\nThe following third party packages are also available.\n\n\nDRF Nested Routers\n\n\nThe \ndrf-nested-routers package\n provides routers and relationship fields for working with nested resources.\n\n\nRest Framework Generic Relations\n\n\nThe \nrest-framework-generic-relations\n library provides read/write serialization for generic foreign keys.", 
                 "title": "Serializer relations"
             }, 
             {
    @@ -2057,7 +2062,7 @@
             }, 
             {
                 "location": "/api-guide/relations/#primarykeyrelatedfield", 
    -            "text": "PrimaryKeyRelatedField  may be used to represent the target of the relationship using its primary key.  For example, the following serializer:  class AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')  Would serialize to a representation like this:  {\n    'album_name': 'The Roots',\n    'artist': 'Undun',\n    'tracks': [\n        89,\n        90,\n        91,\n        ...\n    ]\n}  By default this field is read-write, although you can change this behavior using the  read_only  flag.  Arguments :   queryset  - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set  read_only=True .  many  - If applied to a to-many relationship, you should set this argument to  True .  allow_null  - If set to  True , the field will accept values of  None  or the empty string for nullable relationships. Defaults to  False .  pk_field  - Set to a field to control serialization/deserialization of the primary key's value. For example,  pk_field=UUIDField(format='hex')  would serialize a UUID primary key into its compact hex representation.", 
    +            "text": "PrimaryKeyRelatedField  may be used to represent the target of the relationship using its primary key.  For example, the following serializer:  class AlbumSerializer(serializers.ModelSerializer):\n    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n    class Meta:\n        model = Album\n        fields = ('album_name', 'artist', 'tracks')  Would serialize to a representation like this:  {\n    'album_name': 'Undun',\n    'artist': 'The Roots',\n    'tracks': [\n        89,\n        90,\n        91,\n        ...\n    ]\n}  By default this field is read-write, although you can change this behavior using the  read_only  flag.  Arguments :   queryset  - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set  read_only=True .  many  - If applied to a to-many relationship, you should set this argument to  True .  allow_null  - If set to  True , the field will accept values of  None  or the empty string for nullable relationships. Defaults to  False .  pk_field  - Set to a field to control serialization/deserialization of the primary key's value. For example,  pk_field=UUIDField(format='hex')  would serialize a UUID primary key into its compact hex representation.", 
                 "title": "PrimaryKeyRelatedField"
             }, 
             {
    @@ -2127,7 +2132,7 @@
             }, 
             {
                 "location": "/api-guide/relations/#select-field-cutoffs", 
    -            "text": "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\u2026\" will be displayed.  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.  There are two keyword arguments you can use to control this behavior:   html_cutoff  - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to  None  to disable any limiting. Defaults to  1000 .  html_cutoff_text  - 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  \"More than {count} items\u2026\"   In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the  style  keyword argument. For example:  assigned_to = serializers.SlugRelatedField(\n   queryset=User.objects.all(),\n   slug_field='username',\n   style={'base_template': 'input.html'}\n)", 
    +            "text": "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\u2026\" will be displayed.  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.  There are two keyword arguments you can use to control this behavior:   html_cutoff  - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to  None  to disable any limiting. Defaults to  1000 .  html_cutoff_text  - 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  \"More than {count} items\u2026\"   You can also control these globally using the settings  HTML_SELECT_CUTOFF  and  HTML_SELECT_CUTOFF_TEXT .  In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the  style  keyword argument. For example:  assigned_to = serializers.SlugRelatedField(\n   queryset=User.objects.all(),\n   slug_field='username',\n   style={'base_template': 'input.html'}\n)", 
                 "title": "Select field cutoffs"
             }, 
             {
    @@ -2162,7 +2167,7 @@
             }, 
             {
                 "location": "/api-guide/validators/", 
    -            "text": "Validators\n\n\n\n\nValidators can be useful for re-using validation logic between different types of fields.\n\n\n \nDjango documentation\n\n\n\n\nMost 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.\n\n\nHowever, 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.\n\n\nValidation in REST framework\n\n\nValidation in Django REST framework serializers is handled a little differently to how validation works in Django's \nModelForm\n class.\n\n\nWith \nModelForm\n 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:\n\n\n\n\nIt introduces a proper separation of concerns, making your code behavior more obvious.\n\n\nIt is easy to switch between using shortcut \nModelSerializer\n classes and using  explicit \nSerializer\n classes. Any validation behavior being used for \nModelSerializer\n is simple to replicate.\n\n\nPrinting the \nrepr\n 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.\n\n\n\n\nWhen you're using \nModelSerializer\n all of this is handled automatically for you. If you want to drop down to using a \nSerializer\n classes instead, then you need to define the validation rules explicitly.\n\n\nExample\n\n\nAs an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.\n\n\nclass CustomerReportRecord(models.Model):\n    time_raised = models.DateTimeField(default=timezone.now, editable=False)\n    reference = models.CharField(unique=True, max_length=20)\n    description = models.TextField()\n\n\n\nHere's a basic \nModelSerializer\n that we can use for creating or updating instances of \nCustomerReportRecord\n:\n\n\nclass CustomerReportSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = CustomerReportRecord\n\n\n\nIf we open up the Django shell using \nmanage.py shell\n we can now\n\n\n from project.example.serializers import CustomerReportSerializer\n\n serializer = CustomerReportSerializer()\n\n print(repr(serializer))\nCustomerReportSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    time_raised = DateTimeField(read_only=True)\n    reference = CharField(max_length=20, validators=[\nUniqueValidator(queryset=CustomerReportRecord.objects.all())\n])\n    description = CharField(style={'type': 'textarea'})\n\n\n\nThe interesting bit here is the \nreference\n field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.\n\n\nBecause of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.\n\n\n\n\nUniqueValidator\n\n\nThis validator can be used to enforce the \nunique=True\n constraint on model fields.\nIt takes a single required argument, and an optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThis validator should be applied to \nserializer fields\n, like so:\n\n\nfrom rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n    max_length=100,\n    validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n\n\n\nUniqueTogetherValidator\n\n\nThis validator can be used to enforce \nunique_together\n constraints on model instances.\nIt has two required arguments, and a single optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfields\n \nrequired\n - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nfrom rest_framework.validators import UniqueTogetherValidator\n\nclass ExampleSerializer(serializers.Serializer):\n    # ...\n    class Meta:\n        # ToDo items belong to a parent list, and have an ordering defined\n        #\u00a0by the 'position' field. No two items in a given list may share\n        # the same position.\n        validators = [\n            UniqueTogetherValidator(\n                queryset=ToDoItem.objects.all(),\n                fields=('list', 'position')\n            )\n        ]\n\n\n\n\n\nNote\n: The \nUniqueTogetherValidation\n class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nUniqueForDateValidator\n\n\nUniqueForMonthValidator\n\n\nUniqueForYearValidator\n\n\nThese validators can be used to enforce the \nunique_for_date\n, \nunique_for_month\n and \nunique_for_year\n constraints on model instances. They take the following arguments:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfield\n \nrequired\n - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.\n\n\ndate_field\n \nrequired\n - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nfrom rest_framework.validators import UniqueForYearValidator\n\nclass ExampleSerializer(serializers.Serializer):\n    # ...\n    class Meta:\n        # Blog posts should have a slug that is unique for the current year.\n        validators = [\n            UniqueForYearValidator(\n                queryset=BlogPostItem.objects.all(),\n                field='slug',\n                date_field='published'\n            )\n        ]\n\n\n\nThe 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 \ndefault=...\n, because the value being used for the default wouldn't be generated until after the validation has run.\n\n\nThere 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 \nModelSerializer\n you'll probably simply rely on the defaults that REST framework generates for you, but if you are using \nSerializer\n or simply want more explicit control, use on of the styles demonstrated below.\n\n\nUsing with a writable date field.\n\n\nIf 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 \ndefault\n argument, or by setting \nrequired=True\n.\n\n\npublished = serializers.DateTimeField(required=True)\n\n\n\nUsing with a read-only date field.\n\n\nIf you want the date field to be visible, but not editable by the user, then set \nread_only=True\n and additionally set a \ndefault=...\n argument.\n\n\npublished = serializers.DateTimeField(read_only=True, default=timezone.now)\n\n\n\nThe field will not be writable to the user, but the default value will still be passed through to the \nvalidated_data\n.\n\n\nUsing with a hidden date field.\n\n\nIf you want the date field to be entirely hidden from the user, then use \nHiddenField\n. This field type does not accept user input, but instead always returns it's default value to the \nvalidated_data\n in the serializer.\n\n\npublished = serializers.HiddenField(default=timezone.now)\n\n\n\n\n\nNote\n: The \nUniqueFor\nRange\nValidation\n classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nAdvanced field defaults\n\n\nValidators 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 \nis\n available as input to the validator.\n\n\nTwo patterns that you may want to use for this sort of validation include:\n\n\n\n\nUsing \nHiddenField\n. This field will be present in \nvalidated_data\n but \nwill not\n be used in the serializer output representation.\n\n\nUsing a standard field with \nread_only=True\n, but that also includes a \ndefault=\u2026\n argument. This field \nwill\n be used in the serializer output representation, but cannot be set directly by the user.\n\n\n\n\nREST framework includes a couple of defaults that may be useful in this context.\n\n\nCurrentUserDefault\n\n\nA 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.\n\n\nowner = serializers.HiddenField(\n    default=serializers.CurrentUserDefault()\n)\n\n\n\nCreateOnlyDefault\n\n\nA default class that can be used to \nonly set a default argument during create operations\n. During updates the field is omitted.\n\n\nIt takes a single argument, which is the default value or callable that should be used during create operations.\n\n\ncreated_at = serializers.DateTimeField(\n    read_only=True,\n    default=serializers.CreateOnlyDefault(timezone.now)\n)\n\n\n\n\n\nLimitations of validators\n\n\nThere are some ambiguous cases where you'll need to instead handle validation\nexplicitly, rather than relying on the default serializer classes that\n\nModelSerializer\n generates.\n\n\nIn these cases you may want to disable the automatically generated validators,\nby specifying an empty list for the serializer \nMeta.validators\n attribute.\n\n\nOptional fields\n\n\nBy default \"unique together\" validation enforces that all fields be\n\nrequired=True\n. In some cases, you might want to explicit apply\n\nrequired=False\n to one of the fields, in which case the desired behaviour\nof the validation is ambiguous.\n\n\nIn this case you will typically need to exclude the validator from the\nserializer class, and instead write any validation logic explicitly, either\nin the \n.validate()\n method, or else in the view.\n\n\nFor example:\n\n\nclass BillingRecordSerializer(serializers.ModelSerializer):\n    def validate(self, data):\n        # Apply custom validation either here, or in the view.\n\n    class Meta:\n        fields = ('client', 'date', 'amount')\n        extra_kwargs = {'client': {'required': 'False'}}\n        validators = []  # Remove a default \"unique together\" constraint.\n\n\n\nUpdating nested serializers\n\n\nWhen applying an update to an existing instance, uniqueness validators will\nexclude the current instance from the uniqueness check. The current instance\nis available in the context of the uniqueness check, because it exists as\nan attribute on the serializer, having initially been passed using\n\ninstance=...\n when instantiating the serializer.\n\n\nIn the case of update operations on \nnested\n serializers there's no way of\napplying this exclusion, because the instance is not available.\n\n\nAgain, you'll probably want to explicitly remove the validator from the\nserializer class, and write the code the for the validation constraint\nexplicitly, in a \n.validate()\n method, or in the view.\n\n\nDebugging complex cases\n\n\nIf you're not sure exactly what behavior a \nModelSerializer\n class will\ngenerate it is usually a good idea to run \nmanage.py shell\n, and print\nan instance of the serializer, so that you can inspect the fields and\nvalidators that it automatically generates for you.\n\n\n serializer = MyComplexModelSerializer()\n\n print(serializer)\nclass MyComplexModelSerializer:\n    my_fields = ...\n\n\n\nAlso keep in mind that with complex cases it can often be better to explicitly\ndefine your serializer classes, rather than relying on the default\n\nModelSerializer\n behavior. This involves a little more code, but ensures\nthat the resulting behavior is more transparent.\n\n\n\n\nWriting custom validators\n\n\nYou can use any of Django's existing validators, or write your own custom validators.\n\n\nFunction based\n\n\nA validator may be any callable that raises a \nserializers.ValidationError\n on failure.\n\n\ndef even_number(value):\n    if value % 2 != 0:\n        raise serializers.ValidationError('This field must be an even number.')\n\n\n\nClass-based\n\n\nTo write a class-based validator, use the \n__call__\n method. Class-based validators are useful as they allow you to parameterize and reuse behavior.\n\n\nclass MultipleOf(object):\n    def __init__(self, base):\n        self.base = base\n\n    def __call__(self, value):\n        if value % self.base != 0:\n            message = 'This field must be a multiple of %d.' % self.base\n            raise serializers.ValidationError(message)\n\n\n\nUsing \nset_context()\n\n\nIn 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 \nset_context\n method on a class-based validator.\n\n\ndef set_context(self, serializer_field):\n    # Determine if this is an update or a create operation.\n    # In `__call__` we can then use that information to modify the validation behavior.\n    self.is_update = serializer_field.parent.instance is not None", 
    +            "text": "Validators\n\n\n\n\nValidators can be useful for re-using validation logic between different types of fields.\n\n\n \nDjango documentation\n\n\n\n\nMost 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.\n\n\nHowever, 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.\n\n\nValidation in REST framework\n\n\nValidation in Django REST framework serializers is handled a little differently to how validation works in Django's \nModelForm\n class.\n\n\nWith \nModelForm\n 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:\n\n\n\n\nIt introduces a proper separation of concerns, making your code behavior more obvious.\n\n\nIt is easy to switch between using shortcut \nModelSerializer\n classes and using  explicit \nSerializer\n classes. Any validation behavior being used for \nModelSerializer\n is simple to replicate.\n\n\nPrinting the \nrepr\n 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.\n\n\n\n\nWhen you're using \nModelSerializer\n all of this is handled automatically for you. If you want to drop down to using a \nSerializer\n classes instead, then you need to define the validation rules explicitly.\n\n\nExample\n\n\nAs an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.\n\n\nclass CustomerReportRecord(models.Model):\n    time_raised = models.DateTimeField(default=timezone.now, editable=False)\n    reference = models.CharField(unique=True, max_length=20)\n    description = models.TextField()\n\n\n\nHere's a basic \nModelSerializer\n that we can use for creating or updating instances of \nCustomerReportRecord\n:\n\n\nclass CustomerReportSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = CustomerReportRecord\n\n\n\nIf we open up the Django shell using \nmanage.py shell\n we can now\n\n\n from project.example.serializers import CustomerReportSerializer\n\n serializer = CustomerReportSerializer()\n\n print(repr(serializer))\nCustomerReportSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    time_raised = DateTimeField(read_only=True)\n    reference = CharField(max_length=20, validators=[\nUniqueValidator(queryset=CustomerReportRecord.objects.all())\n])\n    description = CharField(style={'type': 'textarea'})\n\n\n\nThe interesting bit here is the \nreference\n field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.\n\n\nBecause of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.\n\n\n\n\nUniqueValidator\n\n\nThis validator can be used to enforce the \nunique=True\n constraint on model fields.\nIt takes a single required argument, and an optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\nlookup\n - The lookup used to find an existing instance with the value being validated. Defaults to \n'exact'\n.\n\n\n\n\nThis validator should be applied to \nserializer fields\n, like so:\n\n\nfrom rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n    max_length=100,\n    validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n\n\n\nUniqueTogetherValidator\n\n\nThis validator can be used to enforce \nunique_together\n constraints on model instances.\nIt has two required arguments, and a single optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfields\n \nrequired\n - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nfrom rest_framework.validators import UniqueTogetherValidator\n\nclass ExampleSerializer(serializers.Serializer):\n    # ...\n    class Meta:\n        # ToDo items belong to a parent list, and have an ordering defined\n        #\u00a0by the 'position' field. No two items in a given list may share\n        # the same position.\n        validators = [\n            UniqueTogetherValidator(\n                queryset=ToDoItem.objects.all(),\n                fields=('list', 'position')\n            )\n        ]\n\n\n\n\n\nNote\n: The \nUniqueTogetherValidation\n class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nUniqueForDateValidator\n\n\nUniqueForMonthValidator\n\n\nUniqueForYearValidator\n\n\nThese validators can be used to enforce the \nunique_for_date\n, \nunique_for_month\n and \nunique_for_year\n constraints on model instances. They take the following arguments:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfield\n \nrequired\n - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.\n\n\ndate_field\n \nrequired\n - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nfrom rest_framework.validators import UniqueForYearValidator\n\nclass ExampleSerializer(serializers.Serializer):\n    # ...\n    class Meta:\n        # Blog posts should have a slug that is unique for the current year.\n        validators = [\n            UniqueForYearValidator(\n                queryset=BlogPostItem.objects.all(),\n                field='slug',\n                date_field='published'\n            )\n        ]\n\n\n\nThe 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 \ndefault=...\n, because the value being used for the default wouldn't be generated until after the validation has run.\n\n\nThere 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 \nModelSerializer\n you'll probably simply rely on the defaults that REST framework generates for you, but if you are using \nSerializer\n or simply want more explicit control, use on of the styles demonstrated below.\n\n\nUsing with a writable date field.\n\n\nIf 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 \ndefault\n argument, or by setting \nrequired=True\n.\n\n\npublished = serializers.DateTimeField(required=True)\n\n\n\nUsing with a read-only date field.\n\n\nIf you want the date field to be visible, but not editable by the user, then set \nread_only=True\n and additionally set a \ndefault=...\n argument.\n\n\npublished = serializers.DateTimeField(read_only=True, default=timezone.now)\n\n\n\nThe field will not be writable to the user, but the default value will still be passed through to the \nvalidated_data\n.\n\n\nUsing with a hidden date field.\n\n\nIf you want the date field to be entirely hidden from the user, then use \nHiddenField\n. This field type does not accept user input, but instead always returns it's default value to the \nvalidated_data\n in the serializer.\n\n\npublished = serializers.HiddenField(default=timezone.now)\n\n\n\n\n\nNote\n: The \nUniqueFor\nRange\nValidation\n classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nAdvanced field defaults\n\n\nValidators 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 \nis\n available as input to the validator.\n\n\nTwo patterns that you may want to use for this sort of validation include:\n\n\n\n\nUsing \nHiddenField\n. This field will be present in \nvalidated_data\n but \nwill not\n be used in the serializer output representation.\n\n\nUsing a standard field with \nread_only=True\n, but that also includes a \ndefault=\u2026\n argument. This field \nwill\n be used in the serializer output representation, but cannot be set directly by the user.\n\n\n\n\nREST framework includes a couple of defaults that may be useful in this context.\n\n\nCurrentUserDefault\n\n\nA 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.\n\n\nowner = serializers.HiddenField(\n    default=serializers.CurrentUserDefault()\n)\n\n\n\nCreateOnlyDefault\n\n\nA default class that can be used to \nonly set a default argument during create operations\n. During updates the field is omitted.\n\n\nIt takes a single argument, which is the default value or callable that should be used during create operations.\n\n\ncreated_at = serializers.DateTimeField(\n    read_only=True,\n    default=serializers.CreateOnlyDefault(timezone.now)\n)\n\n\n\n\n\nLimitations of validators\n\n\nThere are some ambiguous cases where you'll need to instead handle validation\nexplicitly, rather than relying on the default serializer classes that\n\nModelSerializer\n generates.\n\n\nIn these cases you may want to disable the automatically generated validators,\nby specifying an empty list for the serializer \nMeta.validators\n attribute.\n\n\nOptional fields\n\n\nBy default \"unique together\" validation enforces that all fields be\n\nrequired=True\n. In some cases, you might want to explicit apply\n\nrequired=False\n to one of the fields, in which case the desired behaviour\nof the validation is ambiguous.\n\n\nIn this case you will typically need to exclude the validator from the\nserializer class, and instead write any validation logic explicitly, either\nin the \n.validate()\n method, or else in the view.\n\n\nFor example:\n\n\nclass BillingRecordSerializer(serializers.ModelSerializer):\n    def validate(self, data):\n        # Apply custom validation either here, or in the view.\n\n    class Meta:\n        fields = ('client', 'date', 'amount')\n        extra_kwargs = {'client': {'required': 'False'}}\n        validators = []  # Remove a default \"unique together\" constraint.\n\n\n\nUpdating nested serializers\n\n\nWhen applying an update to an existing instance, uniqueness validators will\nexclude the current instance from the uniqueness check. The current instance\nis available in the context of the uniqueness check, because it exists as\nan attribute on the serializer, having initially been passed using\n\ninstance=...\n when instantiating the serializer.\n\n\nIn the case of update operations on \nnested\n serializers there's no way of\napplying this exclusion, because the instance is not available.\n\n\nAgain, you'll probably want to explicitly remove the validator from the\nserializer class, and write the code the for the validation constraint\nexplicitly, in a \n.validate()\n method, or in the view.\n\n\nDebugging complex cases\n\n\nIf you're not sure exactly what behavior a \nModelSerializer\n class will\ngenerate it is usually a good idea to run \nmanage.py shell\n, and print\nan instance of the serializer, so that you can inspect the fields and\nvalidators that it automatically generates for you.\n\n\n serializer = MyComplexModelSerializer()\n\n print(serializer)\nclass MyComplexModelSerializer:\n    my_fields = ...\n\n\n\nAlso keep in mind that with complex cases it can often be better to explicitly\ndefine your serializer classes, rather than relying on the default\n\nModelSerializer\n behavior. This involves a little more code, but ensures\nthat the resulting behavior is more transparent.\n\n\n\n\nWriting custom validators\n\n\nYou can use any of Django's existing validators, or write your own custom validators.\n\n\nFunction based\n\n\nA validator may be any callable that raises a \nserializers.ValidationError\n on failure.\n\n\ndef even_number(value):\n    if value % 2 != 0:\n        raise serializers.ValidationError('This field must be an even number.')\n\n\n\nClass-based\n\n\nTo write a class-based validator, use the \n__call__\n method. Class-based validators are useful as they allow you to parameterize and reuse behavior.\n\n\nclass MultipleOf(object):\n    def __init__(self, base):\n        self.base = base\n\n    def __call__(self, value):\n        if value % self.base != 0:\n            message = 'This field must be a multiple of %d.' % self.base\n            raise serializers.ValidationError(message)\n\n\n\nUsing \nset_context()\n\n\nIn 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 \nset_context\n method on a class-based validator.\n\n\ndef set_context(self, serializer_field):\n    # Determine if this is an update or a create operation.\n    # In `__call__` we can then use that information to modify the validation behavior.\n    self.is_update = serializer_field.parent.instance is not None", 
                 "title": "Validators"
             }, 
             {
    @@ -2182,7 +2187,7 @@
             }, 
             {
                 "location": "/api-guide/validators/#uniquevalidator", 
    -            "text": "This validator can be used to enforce the  unique=True  constraint on model fields.\nIt takes a single required argument, and an optional  messages  argument:   queryset   required  - This is the queryset against which uniqueness should be enforced.  message  - The error message that should be used when validation fails.   This validator should be applied to  serializer fields , like so:  from rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n    max_length=100,\n    validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)", 
    +            "text": "This validator can be used to enforce the  unique=True  constraint on model fields.\nIt takes a single required argument, and an optional  messages  argument:   queryset   required  - This is the queryset against which uniqueness should be enforced.  message  - The error message that should be used when validation fails.  lookup  - The lookup used to find an existing instance with the value being validated. Defaults to  'exact' .   This validator should be applied to  serializer fields , like so:  from rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n    max_length=100,\n    validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)", 
                 "title": "UniqueValidator"
             }, 
             {
    @@ -2597,7 +2602,7 @@
             }, 
             {
                 "location": "/api-guide/filtering/", 
    -            "text": "Filtering\n\n\n\n\nThe 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.\n\n\n \nDjango documentation\n\n\n\n\nThe 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.\n\n\nThe simplest way to filter the queryset of any view that subclasses \nGenericAPIView\n is to override the \n.get_queryset()\n method.\n\n\nOverriding this method allows you to customize the queryset returned by the view in a number of different ways.\n\n\nFiltering against the current user\n\n\nYou might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.\n\n\nYou can do so by filtering based on the value of \nrequest.user\n.\n\n\nFor example:\n\n\nfrom myapp.models import Purchase\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        This view should return a list of all the purchases\n        for the currently authenticated user.\n        \"\"\"\n        user = self.request.user\n        return Purchase.objects.filter(purchaser=user)\n\n\n\nFiltering against the URL\n\n\nAnother style of filtering might involve restricting the queryset based on some part of the URL.\n\n\nFor example if your URL config contained an entry like this:\n\n\nurl('^purchases/(?P\nusername\n.+)/$', PurchaseList.as_view()),\n\n\n\nYou could then write a view that returned a purchase queryset filtered by the username portion of the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        This view should return a list of all the purchases for\n        the user as determined by the username portion of the URL.\n        \"\"\"\n        username = self.kwargs['username']\n        return Purchase.objects.filter(purchaser__username=username)\n\n\n\nFiltering against query parameters\n\n\nA final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.\n\n\nWe can override \n.get_queryset()\n to deal with URLs such as \nhttp://example.com/api/purchases?username=denvercoder9\n, and filter the queryset only if the \nusername\n parameter is included in the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        Optionally restricts the returned purchases to a given user,\n        by filtering against a `username` query parameter in the URL.\n        \"\"\"\n        queryset = Purchase.objects.all()\n        username = self.request.query_params.get('username', None)\n        if username is not None:\n            queryset = queryset.filter(purchaser__username=username)\n        return queryset\n\n\n\n\n\nGeneric Filtering\n\n\nAs 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.\n\n\nGeneric filters can also present themselves as HTML controls in the browsable API and admin API.\n\n\n\n\nSetting filter backends\n\n\nThe default filter backends may be set globally, using the \nDEFAULT_FILTER_BACKENDS\n setting.  For example.\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n}\n\n\n\nYou can also set the filter backends on a per-view, or per-viewset basis,\nusing the \nGenericAPIView\n class-based views.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n\n\n\nFiltering and object lookups\n\n\nNote 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.\n\n\nFor instance, given the previous example, and a product with an id of \n4675\n, 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:\n\n\nhttp://example.com/api/products/4675/?category=clothing\nmax_price=10.00\n\n\n\nOverriding the initial queryset\n\n\nNote that you can use both an overridden \n.get_queryset()\n and generic filtering together, and everything will work as expected.  For example, if \nProduct\n had a many-to-many relationship with \nUser\n, named \npurchase\n, you might want to write a view like this:\n\n\nclass PurchasedProductsList(generics.ListAPIView):\n    \"\"\"\n    Return a list of all the products that the authenticated\n    user has ever purchased, with optional filtering.\n    \"\"\"\n    model = Product\n    serializer_class = ProductSerializer\n    filter_class = ProductFilter\n\n    def get_queryset(self):\n        user = self.request.user\n        return user.purchase_set.all()\n\n\n\n\n\nAPI Guide\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n class supports highly customizable field filtering, using the \ndjango-filter package\n.\n\n\nTo use REST framework's \nDjangoFilterBackend\n, first install \ndjango-filter\n.\n\n\npip install django-filter\n\n\n\nIf you are using the browsable API or admin API you may also want to install \ndjango-crispy-forms\n, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML.\n\n\npip install django-crispy-forms\n\n\n\nWith crispy forms installed and added to Django's \nINSTALLED_APPS\n, the browsable API will present a filtering control for \nDjangoFilterBackend\n, like so:\n\n\n\n\nSpecifying filter fields\n\n\nIf all you need is simple equality-based filtering, you can set a \nfilter_fields\n attribute on the view, or viewset, listing the set of fields you wish to filter against.\n\n\nclass ProductList(generics.ListAPIView):\n    queryset = Product.objects.all()\n    serializer_class = ProductSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n    filter_fields = ('category', 'in_stock')\n\n\n\nThis will automatically create a \nFilterSet\n class for the given fields, and will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nin_stock=True\n\n\n\nSpecifying a FilterSet\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view.  For example:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    min_price = django_filters.NumberFilter(name=\"price\", lookup_expr='gte')\n    max_price = django_filters.NumberFilter(name=\"price\", lookup_expr='lte')\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n    queryset = Product.objects.all()\n    serializer_class = ProductSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n    filter_class = ProductFilter\n\n\n\nWhich will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nmax_price=10.00\n\n\n\nYou can also span relationships using \ndjango-filter\n, let's assume that each\nproduct has foreign key to \nManufacturer\n model, so we create filter that\nfilters using \nManufacturer\n name. For example:\n\n\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'manufacturer__name']\n\n\n\nThis enables us to make queries like:\n\n\nhttp://example.com/api/products?manufacturer__name=foo\n\n\n\nThis is nice, but it exposes the Django's double underscore convention as part of the API.  If you instead want to explicitly name the filter argument you can instead explicitly include it on the \nFilterSet\n class:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'manufacturer']\n\n\n\nAnd now you can execute:\n\n\nhttp://example.com/api/products?manufacturer=foo\n\n\n\nFor more details on using filter sets see the \ndjango-filter documentation\n.\n\n\n\n\nHints \n Tips\n\n\n\n\nBy default filtering is not enabled.  If you want to use \nDjangoFilterBackend\n remember to make sure it is installed by using the \n'DEFAULT_FILTER_BACKENDS'\n setting.\n\n\nWhen using boolean fields, you should use the values \nTrue\n and \nFalse\n in the URL query parameters, rather than \n0\n, \n1\n, \ntrue\n or \nfalse\n.  (The allowed boolean values are currently hardwired in Django's \nNullBooleanSelect implementation\n.)\n\n\ndjango-filter\n supports filtering across relationships, using Django's double-underscore syntax.\n\n\n\n\n\n\nSearchFilter\n\n\nThe \nSearchFilter\n class supports simple single query parameter based searching, and is based on the \nDjango admin's search functionality\n.\n\n\nWhen in use, the browsable API will include a \nSearchFilter\n control:\n\n\n\n\nThe \nSearchFilter\n class will only be applied if the view has a \nsearch_fields\n attribute set.  The \nsearch_fields\n attribute should be a list of names of text type fields on the model, such as \nCharField\n or \nTextField\n.\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.SearchFilter,)\n    search_fields = ('username', 'email')\n\n\n\nThis will allow the client to filter the items in the list by making queries such as:\n\n\nhttp://example.com/api/users?search=russell\n\n\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:\n\n\nsearch_fields = ('username', 'email', 'profile__profession')\n\n\n\nBy default, searches will use case-insensitive partial matches.  The search parameter may contain multiple search terms, which should be whitespace and/or comma separated.  If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.\n\n\nThe search behavior may be restricted by prepending various characters to the \nsearch_fields\n.\n\n\n\n\n'^' Starts-with search.\n\n\n'=' Exact matches.\n\n\n'@' Full-text search.  (Currently only supported Django's MySQL backend.)\n\n\n'$' Regex search.\n\n\n\n\nFor example:\n\n\nsearch_fields = ('=username', '=email')\n\n\n\nBy default, the search parameter is named \n'search\n', but this may be overridden with the \nSEARCH_PARAM\n setting.\n\n\nFor more details, see the \nDjango documentation\n.\n\n\n\n\nOrderingFilter\n\n\nThe \nOrderingFilter\n class supports simple query parameter controlled ordering of results.\n\n\n\n\nBy default, the query parameter is named \n'ordering'\n, but this may by overridden with the \nORDERING_PARAM\n setting.\n\n\nFor example, to order users by username:\n\n\nhttp://example.com/api/users?ordering=username\n\n\n\nThe client may also specify reverse orderings by prefixing the field name with '-', like so:\n\n\nhttp://example.com/api/users?ordering=-username\n\n\n\nMultiple orderings may also be specified:\n\n\nhttp://example.com/api/users?ordering=account,username\n\n\n\nSpecifying which fields may be ordered against\n\n\nIt's recommended that you explicitly specify which fields the API should allowing in the ordering filter.  You can do this by setting an \nordering_fields\n attribute on the view, like so:\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = ('username', 'email')\n\n\n\nThis helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.\n\n\nIf you \ndon't\n specify an \nordering_fields\n attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the \nserializer_class\n attribute.\n\n\nIf you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on \nany\n model field or queryset aggregate, by using the special value \n'__all__'\n.\n\n\nclass BookingsListView(generics.ListAPIView):\n    queryset = Booking.objects.all()\n    serializer_class = BookingSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = '__all__'\n\n\n\nSpecifying a default ordering\n\n\nIf an \nordering\n attribute is set on the view, this will be used as the default ordering.\n\n\nTypically you'd instead control this by setting \norder_by\n on the initial queryset, but using the \nordering\n 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.\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = ('username', 'email')\n    ordering = ('username',)\n\n\n\nThe \nordering\n attribute may be either a string or a list/tuple of strings.\n\n\n\n\nDjangoObjectPermissionsFilter\n\n\nThe \nDjangoObjectPermissionsFilter\n is intended to be used together with the \ndjango-guardian\n package, with custom \n'view'\n permissions added.  The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.\n\n\nIf you're using \nDjangoObjectPermissionsFilter\n, 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 \nDjangoObjectPermissions\n and add \n'view'\n permissions to the \nperms_map\n attribute.\n\n\nA complete example using both \nDjangoObjectPermissionsFilter\n and \nDjangoObjectPermissions\n might look something like this.\n\n\npermissions.py\n:\n\n\nclass CustomObjectPermissions(permissions.DjangoObjectPermissions):\n    \"\"\"\n    Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n    \"\"\"\n    perms_map = {\n        'GET': ['%(app_label)s.view_%(model_name)s'],\n        'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n        'HEAD': ['%(app_label)s.view_%(model_name)s'],\n        'POST': ['%(app_label)s.add_%(model_name)s'],\n        'PUT': ['%(app_label)s.change_%(model_name)s'],\n        'PATCH': ['%(app_label)s.change_%(model_name)s'],\n        'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n    }\n\n\n\nviews.py\n:\n\n\nclass EventViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    Viewset that only lists events if user has 'view' permissions, and only\n    allows operations on individual events if user has appropriate 'view', 'add',\n    'change' or 'delete' permissions.\n    \"\"\"\n    queryset = Event.objects.all()\n    serializer_class = EventSerializer\n    filter_backends = (filters.DjangoObjectPermissionsFilter,)\n    permission_classes = (myapp.permissions.CustomObjectPermissions,)\n\n\n\nFor more information on adding \n'view'\n permissions for models, see the \nrelevant section\n of the \ndjango-guardian\n documentation, and \nthis blogpost\n.\n\n\n\n\nCustom generic filtering\n\n\nYou can also provide your own generic filtering backend, or write an installable app for other developers to use.\n\n\nTo do so override \nBaseFilterBackend\n, and override the \n.filter_queryset(self, request, queryset, view)\n method.  The method should return a new, filtered queryset.\n\n\nAs 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.\n\n\nExample\n\n\nFor example, you might need to restrict users to only being able to see objects they created.\n\n\nclass IsOwnerFilterBackend(filters.BaseFilterBackend):\n    \"\"\"\n    Filter that only allows users to see their own objects.\n    \"\"\"\n    def filter_queryset(self, request, queryset, view):\n        return queryset.filter(owner=request.user)\n\n\n\nWe could achieve the same behavior by overriding \nget_queryset()\n 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.\n\n\nCustomizing the interface\n\n\nGeneric filters may also present an interface in the browsable API. To do so you should implement a \nto_html()\n method which returns a rendered HTML representation of the filter. This method should have the following signature:\n\n\nto_html(self, request, queryset, view)\n\n\nThe method should return a rendered HTML string.\n\n\nThird party packages\n\n\nThe following third party packages provide additional filter implementations.\n\n\nDjango REST framework filters package\n\n\nThe \ndjango-rest-framework-filters package\n works together with the \nDjangoFilterBackend\n class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.\n\n\nDjango REST framework full word search filter\n\n\nThe \ndjangorestframework-word-filter\n developed as alternative to \nfilters.SearchFilter\n which will search full word in text, or exact match.\n\n\nDjango URL Filter\n\n\ndjango-url-filter\n 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 \nQuerySet\ns.", 
    +            "text": "Filtering\n\n\n\n\nThe 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.\n\n\n \nDjango documentation\n\n\n\n\nThe 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.\n\n\nThe simplest way to filter the queryset of any view that subclasses \nGenericAPIView\n is to override the \n.get_queryset()\n method.\n\n\nOverriding this method allows you to customize the queryset returned by the view in a number of different ways.\n\n\nFiltering against the current user\n\n\nYou might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.\n\n\nYou can do so by filtering based on the value of \nrequest.user\n.\n\n\nFor example:\n\n\nfrom myapp.models import Purchase\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        This view should return a list of all the purchases\n        for the currently authenticated user.\n        \"\"\"\n        user = self.request.user\n        return Purchase.objects.filter(purchaser=user)\n\n\n\nFiltering against the URL\n\n\nAnother style of filtering might involve restricting the queryset based on some part of the URL.\n\n\nFor example if your URL config contained an entry like this:\n\n\nurl('^purchases/(?P\nusername\n.+)/$', PurchaseList.as_view()),\n\n\n\nYou could then write a view that returned a purchase queryset filtered by the username portion of the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        This view should return a list of all the purchases for\n        the user as determined by the username portion of the URL.\n        \"\"\"\n        username = self.kwargs['username']\n        return Purchase.objects.filter(purchaser__username=username)\n\n\n\nFiltering against query parameters\n\n\nA final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.\n\n\nWe can override \n.get_queryset()\n to deal with URLs such as \nhttp://example.com/api/purchases?username=denvercoder9\n, and filter the queryset only if the \nusername\n parameter is included in the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n    serializer_class = PurchaseSerializer\n\n    def get_queryset(self):\n        \"\"\"\n        Optionally restricts the returned purchases to a given user,\n        by filtering against a `username` query parameter in the URL.\n        \"\"\"\n        queryset = Purchase.objects.all()\n        username = self.request.query_params.get('username', None)\n        if username is not None:\n            queryset = queryset.filter(purchaser__username=username)\n        return queryset\n\n\n\n\n\nGeneric Filtering\n\n\nAs 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.\n\n\nGeneric filters can also present themselves as HTML controls in the browsable API and admin API.\n\n\n\n\nSetting filter backends\n\n\nThe default filter backends may be set globally, using the \nDEFAULT_FILTER_BACKENDS\n setting.  For example.\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n}\n\n\n\nYou can also set the filter backends on a per-view, or per-viewset basis,\nusing the \nGenericAPIView\n class-based views.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n\n\n\nFiltering and object lookups\n\n\nNote 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.\n\n\nFor instance, given the previous example, and a product with an id of \n4675\n, 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:\n\n\nhttp://example.com/api/products/4675/?category=clothing\nmax_price=10.00\n\n\n\nOverriding the initial queryset\n\n\nNote that you can use both an overridden \n.get_queryset()\n and generic filtering together, and everything will work as expected.  For example, if \nProduct\n had a many-to-many relationship with \nUser\n, named \npurchase\n, you might want to write a view like this:\n\n\nclass PurchasedProductsList(generics.ListAPIView):\n    \"\"\"\n    Return a list of all the products that the authenticated\n    user has ever purchased, with optional filtering.\n    \"\"\"\n    model = Product\n    serializer_class = ProductSerializer\n    filter_class = ProductFilter\n\n    def get_queryset(self):\n        user = self.request.user\n        return user.purchase_set.all()\n\n\n\n\n\nAPI Guide\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n class supports highly customizable field filtering, using the \ndjango-filter package\n.\n\n\nTo use REST framework's \nDjangoFilterBackend\n, first install \ndjango-filter\n.\n\n\npip install django-filter\n\n\n\nIf you are using the browsable API or admin API you may also want to install \ndjango-crispy-forms\n, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML.\n\n\npip install django-crispy-forms\n\n\n\nWith crispy forms installed and added to Django's \nINSTALLED_APPS\n, the browsable API will present a filtering control for \nDjangoFilterBackend\n, like so:\n\n\n\n\nSpecifying filter fields\n\n\nIf all you need is simple equality-based filtering, you can set a \nfilter_fields\n attribute on the view, or viewset, listing the set of fields you wish to filter against.\n\n\nclass ProductList(generics.ListAPIView):\n    queryset = Product.objects.all()\n    serializer_class = ProductSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n    filter_fields = ('category', 'in_stock')\n\n\n\nThis will automatically create a \nFilterSet\n class for the given fields, and will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nin_stock=True\n\n\n\nSpecifying a FilterSet\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view.  For example:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    min_price = django_filters.NumberFilter(name=\"price\", lookup_expr='gte')\n    max_price = django_filters.NumberFilter(name=\"price\", lookup_expr='lte')\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n    queryset = Product.objects.all()\n    serializer_class = ProductSerializer\n    filter_backends = (filters.DjangoFilterBackend,)\n    filter_class = ProductFilter\n\n\n\nWhich will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nmax_price=10.00\n\n\n\nYou can also span relationships using \ndjango-filter\n, let's assume that each\nproduct has foreign key to \nManufacturer\n model, so we create filter that\nfilters using \nManufacturer\n name. For example:\n\n\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'manufacturer__name']\n\n\n\nThis enables us to make queries like:\n\n\nhttp://example.com/api/products?manufacturer__name=foo\n\n\n\nThis is nice, but it exposes the Django's double underscore convention as part of the API.  If you instead want to explicitly name the filter argument you can instead explicitly include it on the \nFilterSet\n class:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n    manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n    class Meta:\n        model = Product\n        fields = ['category', 'in_stock', 'manufacturer']\n\n\n\nAnd now you can execute:\n\n\nhttp://example.com/api/products?manufacturer=foo\n\n\n\nFor more details on using filter sets see the \ndjango-filter documentation\n.\n\n\n\n\nHints \n Tips\n\n\n\n\nBy default filtering is not enabled.  If you want to use \nDjangoFilterBackend\n remember to make sure it is installed by using the \n'DEFAULT_FILTER_BACKENDS'\n setting.\n\n\nWhen using boolean fields, you should use the values \nTrue\n and \nFalse\n in the URL query parameters, rather than \n0\n, \n1\n, \ntrue\n or \nfalse\n.  (The allowed boolean values are currently hardwired in Django's \nNullBooleanSelect implementation\n.)\n\n\ndjango-filter\n supports filtering across relationships, using Django's double-underscore syntax.\n\n\n\n\n\n\nSearchFilter\n\n\nThe \nSearchFilter\n class supports simple single query parameter based searching, and is based on the \nDjango admin's search functionality\n.\n\n\nWhen in use, the browsable API will include a \nSearchFilter\n control:\n\n\n\n\nThe \nSearchFilter\n class will only be applied if the view has a \nsearch_fields\n attribute set.  The \nsearch_fields\n attribute should be a list of names of text type fields on the model, such as \nCharField\n or \nTextField\n.\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.SearchFilter,)\n    search_fields = ('username', 'email')\n\n\n\nThis will allow the client to filter the items in the list by making queries such as:\n\n\nhttp://example.com/api/users?search=russell\n\n\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:\n\n\nsearch_fields = ('username', 'email', 'profile__profession')\n\n\n\nBy default, searches will use case-insensitive partial matches.  The search parameter may contain multiple search terms, which should be whitespace and/or comma separated.  If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.\n\n\nThe search behavior may be restricted by prepending various characters to the \nsearch_fields\n.\n\n\n\n\n'^' Starts-with search.\n\n\n'=' Exact matches.\n\n\n'@' Full-text search.  (Currently only supported Django's MySQL backend.)\n\n\n'$' Regex search.\n\n\n\n\nFor example:\n\n\nsearch_fields = ('=username', '=email')\n\n\n\nBy default, the search parameter is named \n'search\n', but this may be overridden with the \nSEARCH_PARAM\n setting.\n\n\nFor more details, see the \nDjango documentation\n.\n\n\n\n\nOrderingFilter\n\n\nThe \nOrderingFilter\n class supports simple query parameter controlled ordering of results.\n\n\n\n\nBy default, the query parameter is named \n'ordering'\n, but this may by overridden with the \nORDERING_PARAM\n setting.\n\n\nFor example, to order users by username:\n\n\nhttp://example.com/api/users?ordering=username\n\n\n\nThe client may also specify reverse orderings by prefixing the field name with '-', like so:\n\n\nhttp://example.com/api/users?ordering=-username\n\n\n\nMultiple orderings may also be specified:\n\n\nhttp://example.com/api/users?ordering=account,username\n\n\n\nSpecifying which fields may be ordered against\n\n\nIt's recommended that you explicitly specify which fields the API should allowing in the ordering filter.  You can do this by setting an \nordering_fields\n attribute on the view, like so:\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = ('username', 'email')\n\n\n\nThis helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.\n\n\nIf you \ndon't\n specify an \nordering_fields\n attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the \nserializer_class\n attribute.\n\n\nIf you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on \nany\n model field or queryset aggregate, by using the special value \n'__all__'\n.\n\n\nclass BookingsListView(generics.ListAPIView):\n    queryset = Booking.objects.all()\n    serializer_class = BookingSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = '__all__'\n\n\n\nSpecifying a default ordering\n\n\nIf an \nordering\n attribute is set on the view, this will be used as the default ordering.\n\n\nTypically you'd instead control this by setting \norder_by\n on the initial queryset, but using the \nordering\n 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.\n\n\nclass UserListView(generics.ListAPIView):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    filter_backends = (filters.OrderingFilter,)\n    ordering_fields = ('username', 'email')\n    ordering = ('username',)\n\n\n\nThe \nordering\n attribute may be either a string or a list/tuple of strings.\n\n\n\n\nDjangoObjectPermissionsFilter\n\n\nThe \nDjangoObjectPermissionsFilter\n is intended to be used together with the \ndjango-guardian\n package, with custom \n'view'\n permissions added.  The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.\n\n\nIf you're using \nDjangoObjectPermissionsFilter\n, 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 \nDjangoObjectPermissions\n and add \n'view'\n permissions to the \nperms_map\n attribute.\n\n\nA complete example using both \nDjangoObjectPermissionsFilter\n and \nDjangoObjectPermissions\n might look something like this.\n\n\npermissions.py\n:\n\n\nclass CustomObjectPermissions(permissions.DjangoObjectPermissions):\n    \"\"\"\n    Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n    \"\"\"\n    perms_map = {\n        'GET': ['%(app_label)s.view_%(model_name)s'],\n        'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n        'HEAD': ['%(app_label)s.view_%(model_name)s'],\n        'POST': ['%(app_label)s.add_%(model_name)s'],\n        'PUT': ['%(app_label)s.change_%(model_name)s'],\n        'PATCH': ['%(app_label)s.change_%(model_name)s'],\n        'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n    }\n\n\n\nviews.py\n:\n\n\nclass EventViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    Viewset that only lists events if user has 'view' permissions, and only\n    allows operations on individual events if user has appropriate 'view', 'add',\n    'change' or 'delete' permissions.\n    \"\"\"\n    queryset = Event.objects.all()\n    serializer_class = EventSerializer\n    filter_backends = (filters.DjangoObjectPermissionsFilter,)\n    permission_classes = (myapp.permissions.CustomObjectPermissions,)\n\n\n\nFor more information on adding \n'view'\n permissions for models, see the \nrelevant section\n of the \ndjango-guardian\n documentation, and \nthis blogpost\n.\n\n\n\n\nCustom generic filtering\n\n\nYou can also provide your own generic filtering backend, or write an installable app for other developers to use.\n\n\nTo do so override \nBaseFilterBackend\n, and override the \n.filter_queryset(self, request, queryset, view)\n method.  The method should return a new, filtered queryset.\n\n\nAs 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.\n\n\nExample\n\n\nFor example, you might need to restrict users to only being able to see objects they created.\n\n\nclass IsOwnerFilterBackend(filters.BaseFilterBackend):\n    \"\"\"\n    Filter that only allows users to see their own objects.\n    \"\"\"\n    def filter_queryset(self, request, queryset, view):\n        return queryset.filter(owner=request.user)\n\n\n\nWe could achieve the same behavior by overriding \nget_queryset()\n 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.\n\n\nCustomizing the interface\n\n\nGeneric filters may also present an interface in the browsable API. To do so you should implement a \nto_html()\n method which returns a rendered HTML representation of the filter. This method should have the following signature:\n\n\nto_html(self, request, queryset, view)\n\n\nThe method should return a rendered HTML string.\n\n\nPagination \n schemas\n\n\nYou can also make the filter controls available to the schema autogeneration\nthat REST framework provides, by implementing a \nget_schema_fields()\n method,\nwhich should return a list of \ncoreapi.Field\n instances.\n\n\nThird party packages\n\n\nThe following third party packages provide additional filter implementations.\n\n\nDjango REST framework filters package\n\n\nThe \ndjango-rest-framework-filters package\n works together with the \nDjangoFilterBackend\n class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.\n\n\nDjango REST framework full word search filter\n\n\nThe \ndjangorestframework-word-filter\n developed as alternative to \nfilters.SearchFilter\n which will search full word in text, or exact match.\n\n\nDjango URL Filter\n\n\ndjango-url-filter\n 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 \nQuerySet\ns.\n\n\ndrf-url-filters\n\n\ndrf-url-filter\n is a simple Django app to apply filters on drf \nModelViewSet\n's \nQueryset\n in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package \nVoluptuous\n is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.", 
                 "title": "Filtering"
             }, 
             {
    @@ -2700,6 +2705,11 @@
                 "text": "Generic filters may also present an interface in the browsable API. To do so you should implement a  to_html()  method which returns a rendered HTML representation of the filter. This method should have the following signature:  to_html(self, request, queryset, view)  The method should return a rendered HTML string.", 
                 "title": "Customizing the interface"
             }, 
    +        {
    +            "location": "/api-guide/filtering/#pagination-schemas", 
    +            "text": "You can also make the filter controls available to the schema autogeneration\nthat REST framework provides, by implementing a  get_schema_fields()  method,\nwhich should return a list of  coreapi.Field  instances.", 
    +            "title": "Pagination & schemas"
    +        }, 
             {
                 "location": "/api-guide/filtering/#third-party-packages", 
                 "text": "The following third party packages provide additional filter implementations.", 
    @@ -2720,9 +2730,14 @@
                 "text": "django-url-filter  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  QuerySet s.", 
                 "title": "Django URL Filter"
             }, 
    +        {
    +            "location": "/api-guide/filtering/#drf-url-filters", 
    +            "text": "drf-url-filter  is a simple Django app to apply filters on drf  ModelViewSet 's  Queryset  in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package  Voluptuous  is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.", 
    +            "title": "drf-url-filters"
    +        }, 
             {
                 "location": "/api-guide/pagination/", 
    -            "text": "Pagination\n\n\n\n\nDjango provides a few classes that help you manage paginated data \u2013 that is, data that\u2019s split across several pages, with \u201cPrevious/Next\u201d links.\n\n\n \nDjango documentation\n\n\n\n\nREST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.\n\n\nThe pagination API can support either:\n\n\n\n\nPagination links that are provided as part of the content of the response.\n\n\nPagination links that are included in response headers, such as \nContent-Range\n or \nLink\n.\n\n\n\n\nThe 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.\n\n\nPagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular \nAPIView\n, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the \nmixins.ListModelMixin\n and \ngenerics.GenericAPIView\n classes for an example.\n\n\nPagination can be turned off by setting the pagination class to \nNone\n.\n\n\nSetting the pagination style\n\n\nThe default pagination style may be set globally, using the \nDEFAULT_PAGINATION_CLASS\n and \nPAGE_SIZE\n setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nNote that you need to set both the pagination class, and the page size that should be used.\n\n\nYou can also set the pagination class on an individual view by using the \npagination_class\n 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.\n\n\nModifying the pagination style\n\n\nIf 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.\n\n\nclass LargeResultsSetPagination(PageNumberPagination):\n    page_size = 1000\n    page_size_query_param = 'page_size'\n    max_page_size = 10000\n\nclass StandardResultsSetPagination(PageNumberPagination):\n    page_size = 100\n    page_size_query_param = 'page_size'\n    max_page_size = 1000\n\n\n\nYou can then apply your new style to a view using the \n.pagination_class\n attribute:\n\n\nclass BillingRecordsView(generics.ListAPIView):\n    queryset = Billing.objects.all()\n    serializer_class = BillingRecordsSerializer\n    pagination_class = LargeResultsSetPagination\n\n\n\nOr apply the style globally, using the \nDEFAULT_PAGINATION_CLASS\n settings key. For example:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'\n}\n\n\n\n\n\nAPI Reference\n\n\nPageNumberPagination\n\n\nThis pagination style accepts a single number page number in the request query parameters.\n\n\nRequest\n:\n\n\nGET https://api.example.org/accounts/?page=4\n\n\n\nResponse\n:\n\n\nHTTP 200 OK\n{\n    \"count\": 1023\n    \"next\": \"https://api.example.org/accounts/?page=5\",\n    \"previous\": \"https://api.example.org/accounts/?page=3\",\n    \"results\": [\n       \u2026\n    ]\n}\n\n\n\nSetup\n\n\nTo enable the \nPageNumberPagination\n style globally, use the following configuration, modifying the \nPAGE_SIZE\n as desired:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nPageNumberPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nPageNumberPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nPageNumberPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\ndjango_paginator_class\n - The Django Paginator class to use. Default is \ndjango.core.paginator.Paginator\n, which should be fine for most use cases.\n\n\npage_size\n - A numeric value indicating the page size. If set, this overrides the \nPAGE_SIZE\n setting. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\npage_query_param\n - A string value indicating the name of the query parameter to use for the pagination control.\n\n\npage_size_query_param\n - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to \nNone\n, indicating that the client may not control the requested page size.\n\n\nmax_page_size\n - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if \npage_size_query_param\n is also set.\n\n\nlast_page_strings\n - A list or tuple of string values indicating values that may be used with the \npage_query_param\n to request the final page in the set. Defaults to \n('last',)\n\n\ntemplate\n - 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/numbers.html\"\n.\n\n\n\n\n\n\nLimitOffsetPagination\n\n\nThis pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an\n\"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the \npage_size\n in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.\n\n\nRequest\n:\n\n\nGET https://api.example.org/accounts/?limit=100\noffset=400\n\n\n\nResponse\n:\n\n\nHTTP 200 OK\n{\n    \"count\": 1023\n    \"next\": \"https://api.example.org/accounts/?limit=100\noffset=500\",\n    \"previous\": \"https://api.example.org/accounts/?limit=100\noffset=300\",\n    \"results\": [\n       \u2026\n    ]\n}\n\n\n\nSetup\n\n\nTo enable the \nLimitOffsetPagination\n style globally, use the following configuration:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n}\n\n\n\nOptionally, you may also set a \nPAGE_SIZE\n key. If the \nPAGE_SIZE\n parameter is also used then the \nlimit\n query parameter will be optional, and may be omitted by the client.\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nLimitOffsetPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nLimitOffsetPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nLimitOffsetPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\ndefault_limit\n - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\nlimit_query_param\n - A string value indicating the name of the \"limit\" query parameter. Defaults to \n'limit'\n.\n\n\noffset_query_param\n - A string value indicating the name of the \"offset\" query parameter. Defaults to \n'offset'\n.\n\n\nmax_limit\n - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to \nNone\n.\n\n\ntemplate\n - 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/numbers.html\"\n.\n\n\n\n\n\n\nCursorPagination\n\n\nThe 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.\n\n\nCursor 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.\n\n\nCursor 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:\n\n\n\n\nProvides a consistent pagination view. When used properly \nCursorPagination\n 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.\n\n\nSupports 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.\n\n\n\n\nDetails and limitations\n\n\nProper 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 \n\"-created\"\n. This assumes that \nthere must be a 'created' timestamp field\n on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first.\n\n\nYou can modify the ordering by overriding the \n'ordering'\n attribute on the pagination class, or by using the \nOrderingFilter\n filter class together with \nCursorPagination\n. When used with \nOrderingFilter\n you should strongly consider restricting the fields that the user may order by.\n\n\nProper usage of cursor pagination should have an ordering field that satisfies the following:\n\n\n\n\nShould be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.\n\n\nShould be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering.\n\n\nShould be a non-nullable value that can be coerced to a string.\n\n\nThe field should have a database index.\n\n\n\n\nUsing an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.\n\n\nFor more technical details on the implementation we use for cursor pagination, the \n\"Building cursors for the Disqus API\"\n blog post gives a good overview of the basic approach.\n\n\nSetup\n\n\nTo enable the \nCursorPagination\n style globally, use the following configuration, modifying the \nPAGE_SIZE\n as desired:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nCursorPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nCursorPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nCursorPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\npage_size\n = A numeric value indicating the page size. If set, this overrides the \nPAGE_SIZE\n setting. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\ncursor_query_param\n = A string value indicating the name of the \"cursor\" query parameter. Defaults to \n'cursor'\n.\n\n\nordering\n = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: \nordering = 'slug'\n. Defaults to \n-created\n. This value may also be overridden by using \nOrderingFilter\n on the view.\n\n\ntemplate\n = 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/previous_and_next.html\"\n.\n\n\n\n\n\n\nCustom pagination styles\n\n\nTo create a custom pagination serializer class you should subclass \npagination.BasePagination\n and override the \npaginate_queryset(self, queryset, request, view=None)\n and \nget_paginated_response(self, data)\n methods:\n\n\n\n\nThe \npaginate_queryset\n method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.\n\n\nThe \nget_paginated_response\n method is passed the serialized page data and should return a \nResponse\n instance.\n\n\n\n\nNote that the \npaginate_queryset\n method may set state on the pagination instance, that may later be used by the \nget_paginated_response\n method.\n\n\nExample\n\n\nSuppose 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:\n\n\nclass CustomPagination(pagination.PageNumberPagination):\n    def get_paginated_response(self, data):\n        return Response({\n            'links': {\n               'next': self.get_next_link(),\n               'previous': self.get_previous_link()\n            },\n            'count': self.page.paginator.count,\n            'results': data\n        })\n\n\n\nWe'd then need to setup the custom class in our configuration:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nNote that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an \nOrderedDict\n when constructing the body of paginated responses, but this is optional.\n\n\nHeader based pagination\n\n\nLet's modify the built-in \nPageNumberPagination\n style, so that instead of include the pagination links in the body of the response, we'll instead include a \nLink\n header, in a \nsimilar style to the GitHub API\n.\n\n\nclass LinkHeaderPagination(pagination.PageNumberPagination):\n    def get_paginated_response(self, data):\n        next_url = self.get_next_link()\n        previous_url = self.get_previous_link()\n\n        if next_url is not None and previous_url is not None:\n            link = '\n{next_url}\n; rel=\"next\", \n{previous_url}\n; rel=\"prev\"'\n        elif next_url is not None:\n            link = '\n{next_url}\n; rel=\"next\"'\n        elif previous_url is not None:\n            link = '\n{previous_url}\n; rel=\"prev\"'\n        else:\n            link = ''\n\n        link = link.format(next_url=next_url, previous_url=previous_url)\n        headers = {'Link': link} if link else {}\n\n        return Response(data, headers=headers)\n\n\n\nUsing your custom pagination class\n\n\nTo have your custom pagination class be used by default, use the \nDEFAULT_PAGINATION_CLASS\n setting:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nAPI responses for list endpoints will now include a \nLink\n header, instead of including the pagination links as part of the body of the response, for example:\n\n\n\n\n\n\nA custom pagination style, using the 'Link' header'\n\n\n\n\nHTML pagination controls\n\n\nBy 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 \nPageNumberPagination\n and \nLimitOffsetPagination\n classes display a list of page numbers with previous and next controls. The \nCursorPagination\n class displays a simpler style that only displays a previous and next control.\n\n\nCustomizing the controls\n\n\nYou can override the templates that render the HTML pagination controls. The two built-in styles are:\n\n\n\n\nrest_framework/pagination/numbers.html\n\n\nrest_framework/pagination/previous_and_next.html\n\n\n\n\nProviding a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.\n\n\nAlternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting \ntemplate = None\n as an attribute on the class. You'll then need to configure your \nDEFAULT_PAGINATION_CLASS\n settings key to use your custom class as the default pagination style.\n\n\nLow-level API\n\n\nThe low-level API for determining if a pagination class should display the controls or not is exposed as a \ndisplay_page_controls\n attribute on the pagination instance. Custom pagination classes should be set to \nTrue\n in the \npaginate_queryset\n method if they require the HTML pagination controls to be displayed.\n\n\nThe \n.to_html()\n and \n.get_html_context()\n methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF-extensions\n\n\nThe \nDRF-extensions\n package\n includes a \nPaginateByMaxMixin\n mixin class\n that allows your API clients to specify \n?page_size=max\n to obtain the maximum allowed page size.", 
    +            "text": "Pagination\n\n\n\n\nDjango provides a few classes that help you manage paginated data \u2013 that is, data that\u2019s split across several pages, with \u201cPrevious/Next\u201d links.\n\n\n \nDjango documentation\n\n\n\n\nREST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.\n\n\nThe pagination API can support either:\n\n\n\n\nPagination links that are provided as part of the content of the response.\n\n\nPagination links that are included in response headers, such as \nContent-Range\n or \nLink\n.\n\n\n\n\nThe 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.\n\n\nPagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular \nAPIView\n, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the \nmixins.ListModelMixin\n and \ngenerics.GenericAPIView\n classes for an example.\n\n\nPagination can be turned off by setting the pagination class to \nNone\n.\n\n\nSetting the pagination style\n\n\nThe default pagination style may be set globally, using the \nDEFAULT_PAGINATION_CLASS\n and \nPAGE_SIZE\n setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nNote that you need to set both the pagination class, and the page size that should be used.\n\n\nYou can also set the pagination class on an individual view by using the \npagination_class\n 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.\n\n\nModifying the pagination style\n\n\nIf 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.\n\n\nclass LargeResultsSetPagination(PageNumberPagination):\n    page_size = 1000\n    page_size_query_param = 'page_size'\n    max_page_size = 10000\n\nclass StandardResultsSetPagination(PageNumberPagination):\n    page_size = 100\n    page_size_query_param = 'page_size'\n    max_page_size = 1000\n\n\n\nYou can then apply your new style to a view using the \n.pagination_class\n attribute:\n\n\nclass BillingRecordsView(generics.ListAPIView):\n    queryset = Billing.objects.all()\n    serializer_class = BillingRecordsSerializer\n    pagination_class = LargeResultsSetPagination\n\n\n\nOr apply the style globally, using the \nDEFAULT_PAGINATION_CLASS\n settings key. For example:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'\n}\n\n\n\n\n\nAPI Reference\n\n\nPageNumberPagination\n\n\nThis pagination style accepts a single number page number in the request query parameters.\n\n\nRequest\n:\n\n\nGET https://api.example.org/accounts/?page=4\n\n\n\nResponse\n:\n\n\nHTTP 200 OK\n{\n    \"count\": 1023\n    \"next\": \"https://api.example.org/accounts/?page=5\",\n    \"previous\": \"https://api.example.org/accounts/?page=3\",\n    \"results\": [\n       \u2026\n    ]\n}\n\n\n\nSetup\n\n\nTo enable the \nPageNumberPagination\n style globally, use the following configuration, modifying the \nPAGE_SIZE\n as desired:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nPageNumberPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nPageNumberPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nPageNumberPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\ndjango_paginator_class\n - The Django Paginator class to use. Default is \ndjango.core.paginator.Paginator\n, which should be fine for most use cases.\n\n\npage_size\n - A numeric value indicating the page size. If set, this overrides the \nPAGE_SIZE\n setting. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\npage_query_param\n - A string value indicating the name of the query parameter to use for the pagination control.\n\n\npage_size_query_param\n - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to \nNone\n, indicating that the client may not control the requested page size.\n\n\nmax_page_size\n - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if \npage_size_query_param\n is also set.\n\n\nlast_page_strings\n - A list or tuple of string values indicating values that may be used with the \npage_query_param\n to request the final page in the set. Defaults to \n('last',)\n\n\ntemplate\n - 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/numbers.html\"\n.\n\n\n\n\n\n\nLimitOffsetPagination\n\n\nThis pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an\n\"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the \npage_size\n in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.\n\n\nRequest\n:\n\n\nGET https://api.example.org/accounts/?limit=100\noffset=400\n\n\n\nResponse\n:\n\n\nHTTP 200 OK\n{\n    \"count\": 1023\n    \"next\": \"https://api.example.org/accounts/?limit=100\noffset=500\",\n    \"previous\": \"https://api.example.org/accounts/?limit=100\noffset=300\",\n    \"results\": [\n       \u2026\n    ]\n}\n\n\n\nSetup\n\n\nTo enable the \nLimitOffsetPagination\n style globally, use the following configuration:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n}\n\n\n\nOptionally, you may also set a \nPAGE_SIZE\n key. If the \nPAGE_SIZE\n parameter is also used then the \nlimit\n query parameter will be optional, and may be omitted by the client.\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nLimitOffsetPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nLimitOffsetPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nLimitOffsetPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\ndefault_limit\n - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\nlimit_query_param\n - A string value indicating the name of the \"limit\" query parameter. Defaults to \n'limit'\n.\n\n\noffset_query_param\n - A string value indicating the name of the \"offset\" query parameter. Defaults to \n'offset'\n.\n\n\nmax_limit\n - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to \nNone\n.\n\n\ntemplate\n - 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/numbers.html\"\n.\n\n\n\n\n\n\nCursorPagination\n\n\nThe 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.\n\n\nCursor 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.\n\n\nCursor 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:\n\n\n\n\nProvides a consistent pagination view. When used properly \nCursorPagination\n 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.\n\n\nSupports 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.\n\n\n\n\nDetails and limitations\n\n\nProper 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 \n\"-created\"\n. This assumes that \nthere must be a 'created' timestamp field\n on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first.\n\n\nYou can modify the ordering by overriding the \n'ordering'\n attribute on the pagination class, or by using the \nOrderingFilter\n filter class together with \nCursorPagination\n. When used with \nOrderingFilter\n you should strongly consider restricting the fields that the user may order by.\n\n\nProper usage of cursor pagination should have an ordering field that satisfies the following:\n\n\n\n\nShould be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.\n\n\nShould be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering.\n\n\nShould be a non-nullable value that can be coerced to a string.\n\n\nThe field should have a database index.\n\n\n\n\nUsing an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.\n\n\nFor more technical details on the implementation we use for cursor pagination, the \n\"Building cursors for the Disqus API\"\n blog post gives a good overview of the basic approach.\n\n\nSetup\n\n\nTo enable the \nCursorPagination\n style globally, use the following configuration, modifying the \nPAGE_SIZE\n as desired:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nOn \nGenericAPIView\n subclasses you may also set the \npagination_class\n attribute to select \nCursorPagination\n on a per-view basis.\n\n\nConfiguration\n\n\nThe \nCursorPagination\n class includes a number of attributes that may be overridden to modify the pagination style.\n\n\nTo set these attributes you should override the \nCursorPagination\n class, and then enable your custom pagination class as above.\n\n\n\n\npage_size\n = A numeric value indicating the page size. If set, this overrides the \nPAGE_SIZE\n setting. Defaults to the same value as the \nPAGE_SIZE\n settings key.\n\n\ncursor_query_param\n = A string value indicating the name of the \"cursor\" query parameter. Defaults to \n'cursor'\n.\n\n\nordering\n = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: \nordering = 'slug'\n. Defaults to \n-created\n. This value may also be overridden by using \nOrderingFilter\n on the view.\n\n\ntemplate\n = 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 \nNone\n to disable HTML pagination controls completely. Defaults to \n\"rest_framework/pagination/previous_and_next.html\"\n.\n\n\n\n\n\n\nCustom pagination styles\n\n\nTo create a custom pagination serializer class you should subclass \npagination.BasePagination\n and override the \npaginate_queryset(self, queryset, request, view=None)\n and \nget_paginated_response(self, data)\n methods:\n\n\n\n\nThe \npaginate_queryset\n method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.\n\n\nThe \nget_paginated_response\n method is passed the serialized page data and should return a \nResponse\n instance.\n\n\n\n\nNote that the \npaginate_queryset\n method may set state on the pagination instance, that may later be used by the \nget_paginated_response\n method.\n\n\nExample\n\n\nSuppose 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:\n\n\nclass CustomPagination(pagination.PageNumberPagination):\n    def get_paginated_response(self, data):\n        return Response({\n            'links': {\n               'next': self.get_next_link(),\n               'previous': self.get_previous_link()\n            },\n            'count': self.page.paginator.count,\n            'results': data\n        })\n\n\n\nWe'd then need to setup the custom class in our configuration:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nNote that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an \nOrderedDict\n when constructing the body of paginated responses, but this is optional.\n\n\nHeader based pagination\n\n\nLet's modify the built-in \nPageNumberPagination\n style, so that instead of include the pagination links in the body of the response, we'll instead include a \nLink\n header, in a \nsimilar style to the GitHub API\n.\n\n\nclass LinkHeaderPagination(pagination.PageNumberPagination):\n    def get_paginated_response(self, data):\n        next_url = self.get_next_link()\n        previous_url = self.get_previous_link()\n\n        if next_url is not None and previous_url is not None:\n            link = '\n{next_url}\n; rel=\"next\", \n{previous_url}\n; rel=\"prev\"'\n        elif next_url is not None:\n            link = '\n{next_url}\n; rel=\"next\"'\n        elif previous_url is not None:\n            link = '\n{previous_url}\n; rel=\"prev\"'\n        else:\n            link = ''\n\n        link = link.format(next_url=next_url, previous_url=previous_url)\n        headers = {'Link': link} if link else {}\n\n        return Response(data, headers=headers)\n\n\n\nUsing your custom pagination class\n\n\nTo have your custom pagination class be used by default, use the \nDEFAULT_PAGINATION_CLASS\n setting:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n    'PAGE_SIZE': 100\n}\n\n\n\nAPI responses for list endpoints will now include a \nLink\n header, instead of including the pagination links as part of the body of the response, for example:\n\n\nPagination \n schemas\n\n\nYou can also make the pagination controls available to the schema autogeneration\nthat REST framework provides, by implementing a \nget_schema_fields()\n method,\nwhich should return a list of \ncoreapi.Field\n instances.\n\n\n\n\n\n\nA custom pagination style, using the 'Link' header'\n\n\n\n\nHTML pagination controls\n\n\nBy 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 \nPageNumberPagination\n and \nLimitOffsetPagination\n classes display a list of page numbers with previous and next controls. The \nCursorPagination\n class displays a simpler style that only displays a previous and next control.\n\n\nCustomizing the controls\n\n\nYou can override the templates that render the HTML pagination controls. The two built-in styles are:\n\n\n\n\nrest_framework/pagination/numbers.html\n\n\nrest_framework/pagination/previous_and_next.html\n\n\n\n\nProviding a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.\n\n\nAlternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting \ntemplate = None\n as an attribute on the class. You'll then need to configure your \nDEFAULT_PAGINATION_CLASS\n settings key to use your custom class as the default pagination style.\n\n\nLow-level API\n\n\nThe low-level API for determining if a pagination class should display the controls or not is exposed as a \ndisplay_page_controls\n attribute on the pagination instance. Custom pagination classes should be set to \nTrue\n in the \npaginate_queryset\n method if they require the HTML pagination controls to be displayed.\n\n\nThe \n.to_html()\n and \n.get_html_context()\n methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF-extensions\n\n\nThe \nDRF-extensions\n package\n includes a \nPaginateByMaxMixin\n mixin class\n that allows your API clients to specify \n?page_size=max\n to obtain the maximum allowed page size.", 
                 "title": "Pagination"
             }, 
             {
    @@ -2812,9 +2827,14 @@
             }, 
             {
                 "location": "/api-guide/pagination/#using-your-custom-pagination-class", 
    -            "text": "To have your custom pagination class be used by default, use the  DEFAULT_PAGINATION_CLASS  setting:  REST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n    'PAGE_SIZE': 100\n}  API responses for list endpoints will now include a  Link  header, instead of including the pagination links as part of the body of the response, for example:    A custom pagination style, using the 'Link' header'", 
    +            "text": "To have your custom pagination class be used by default, use the  DEFAULT_PAGINATION_CLASS  setting:  REST_FRAMEWORK = {\n    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n    'PAGE_SIZE': 100\n}  API responses for list endpoints will now include a  Link  header, instead of including the pagination links as part of the body of the response, for example:", 
                 "title": "Using your custom pagination class"
             }, 
    +        {
    +            "location": "/api-guide/pagination/#pagination-schemas", 
    +            "text": "You can also make the pagination controls available to the schema autogeneration\nthat REST framework provides, by implementing a  get_schema_fields()  method,\nwhich should return a list of  coreapi.Field  instances.    A custom pagination style, using the 'Link' header'", 
    +            "title": "Pagination & schemas"
    +        }, 
             {
                 "location": "/api-guide/pagination/#html-pagination-controls", 
                 "text": "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  PageNumberPagination  and  LimitOffsetPagination  classes display a list of page numbers with previous and next controls. The  CursorPagination  class displays a simpler style that only displays a previous and next control.", 
    @@ -2987,7 +3007,7 @@
             }, 
             {
                 "location": "/api-guide/schemas/", 
    -            "text": "Schemas\n\n\n\n\nA machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.\n\n\n Heroku, \nJSON Schema for the Heroku Platform API\n\n\n\n\nAPI schemas are a useful tool that allow for a range of use cases, including\ngenerating reference documentation, or driving dynamic client libraries that\ncan interact with your API.\n\n\nRepresenting schemas internally\n\n\nREST framework uses \nCore API\n in order to model schema information in\na format-independent representation. This information can then be rendered\ninto various different schema formats, or used to generate API documentation.\n\n\nWhen using Core API, a schema is represented as a \nDocument\n which is the\ntop-level container object for information about the API. Available API\ninteractions are represented using \nLink\n objects. Each link includes a URL,\nHTTP method, and may include a list of \nField\n instances, which describe any\nparameters that may be accepted by the API endpoint. The \nLink\n and \nField\n\ninstances may also include descriptions, that allow an API schema to be\nrendered into user documentation.\n\n\nHere's an example of an API description that includes a single \nsearch\n\nendpoint:\n\n\ncoreapi.Document(\n    title='Flight Search API',\n    url='https://api.example.org/',\n    content={\n        'search': coreapi.Link(\n            url='/search/',\n            action='get',\n            fields=[\n                coreapi.Field(\n                    name='from',\n                    required=True,\n                    location='query',\n                    description='City name or airport code.'\n                ),\n                coreapi.Field(\n                    name='to',\n                    required=True,\n                    location='query',\n                    description='City name or airport code.'\n                ),\n                coreapi.Field(\n                    name='date',\n                    required=True,\n                    location='query',\n                    description='Flight date in \"YYYY-MM-DD\" format.'\n                )\n            ],\n            description='Return flight availability and prices.'\n        )\n    }\n)\n\n\n\nSchema output formats\n\n\nIn order to be presented in an HTTP response, the internal representation\nhas to be rendered into the actual bytes that are used in the response.\n\n\nCore JSON\n is designed as a canonical format for use with Core API.\nREST framework includes a renderer class for handling this media type, which\nis available as \nrenderers.CoreJSONRenderer\n.\n\n\nOther schema formats such as \nOpen API\n (\"Swagger\"),\n\nJSON HyperSchema\n, or \nAPI Blueprint\n can\nalso be supported by implementing a custom renderer class.\n\n\nSchemas vs Hypermedia\n\n\nIt's worth pointing out here that Core API can also be used to model hypermedia\nresponses, which present an alternative interaction style to API schemas.\n\n\nWith an API schema, the entire available interface is presented up-front\nas a single endpoint. Responses to individual API endpoints are then typically\npresented as plain data, without any further interactions contained in each\nresponse.\n\n\nWith Hypermedia, the client is instead presented with a document containing\nboth data and available interactions. Each interaction results in a new\ndocument, detailing both the current state and the available interactions.\n\n\nFurther information and support on building Hypermedia APIs with REST framework\nis planned for a future version.\n\n\n\n\nAdding a schema\n\n\nYou'll need to install the \ncoreapi\n package in order to add schema support\nfor REST framework.\n\n\npip install coreapi\n\n\n\nREST framework includes functionality for auto-generating a schema,\nor allows you to specify one explicitly. There are a few different ways to\nadd a schema to your API, depending on exactly what you need.\n\n\nUsing DefaultRouter\n\n\nIf you're using \nDefaultRouter\n then you can include an auto-generated schema,\nsimply by adding a \nschema_title\n argument to the router.\n\n\nrouter = DefaultRouter(schema_title='Server Monitoring API')\n\n\n\nThe schema will be included at the root URL, \n/\n, and presented to clients\nthat include the Core JSON media type in their \nAccept\n header.\n\n\n$ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Server Monitoring API\"\n    },\n    \"_type\": \"document\",\n    ...\n}\n\n\n\nThis is a great zero-configuration option for when you want to get up and\nrunning really quickly.\n\n\nThe other available options to \nDefaultRouter\n are:\n\n\nschema_renderers\n\n\nMay be used to pass the set of renderer classes that can be used to render schema output.\n\n\nfrom rest_framework.renderers import CoreJSONRenderer\nfrom my_custom_package import APIBlueprintRenderer\n\nrouter = DefaultRouter(schema_title='Server Monitoring API', schema_renderers=[\n    CoreJSONRenderer, APIBlueprintRenderer\n])\n\n\n\nschema_url\n\n\nMay be used to pass the root URL for the schema. This can either be used to ensure that\nthe schema URLs include a canonical hostname and schema, or to ensure that all the\nschema URLs include a path prefix.\n\n\nrouter = DefaultRouter(\n    schema_title='Server Monitoring API',\n    schema_url='https://www.example.org/api/'\n)\n\n\n\nIf you want more flexibility over the schema output then you'll need to consider\nusing \nSchemaGenerator\n instead.\n\n\nroot_renderers\n\n\nMay be used to pass the set of renderer classes that can be used to render the API root endpoint.\n\n\nUsing SchemaGenerator\n\n\nThe most common way to add a schema to your API is to use the \nSchemaGenerator\n\nclass to auto-generate the \nDocument\n instance, and to return that from a view.\n\n\nThis option gives you the flexibility of setting up the schema endpoint\nwith whatever behavior you want. For example, you can apply different\npermission, throttling or authentication policies to the schema endpoint.\n\n\nHere's an example of using \nSchemaGenerator\n together with a view to\nreturn the schema.\n\n\nviews.py:\n\n\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response, schemas\n\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema())\n\n\n\nurls.py:\n\n\nurlpatterns = [\n    url('/', schema_view),\n    ...\n]\n\n\n\nYou can also serve different schemas to different users, depending on the\npermissions they have available. This approach can be used to ensure that\nunauthenticated requests are presented with a different schema to\nauthenticated requests, or to ensure that different parts of the API are\nmade visible to different users depending on their role.\n\n\nIn order to present a schema with endpoints filtered by user permissions,\nyou need to pass the \nrequest\n argument to the \nget_schema()\n method, like so:\n\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema(request=request))\n\n\n\nExplicit schema definition\n\n\nAn alternative to the auto-generated approach is to specify the API schema\nexplicitly, by declaring a \nDocument\n object in your codebase. Doing so is a\nlittle more work, but ensures that you have full control over the schema\nrepresentation.\n\n\nimport coreapi\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response\n\nschema = coreapi.Document(\n    title='Bookings API',\n    content={\n        ...\n    }\n)\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    return response.Response(schema)\n\n\n\nStatic schema file\n\n\nA final option is to write your API schema as a static file, using one\nof the available formats, such as Core JSON or Open API.\n\n\nYou could then either:\n\n\n\n\nWrite a schema definition as a static file, and \nserve the static file directly\n.\n\n\nWrite a schema definition that is loaded using \nCore API\n, and then\n  rendered to one of many available formats, depending on the client request.\n\n\n\n\n\n\nAlternate schema formats\n\n\nIn order to support an alternate schema format, you need to implement a custom renderer\nclass that handles converting a \nDocument\n instance into a bytestring representation.\n\n\nIf there is a Core API codec package that supports encoding into the format you\nwant to use then implementing the renderer class can be done by using the codec.\n\n\nExample\n\n\nFor example, the \nopenapi_codec\n package provides support for encoding or decoding\nto the Open API (\"Swagger\") format:\n\n\nfrom rest_framework import renderers\nfrom openapi_codec import OpenAPICodec\n\nclass SwaggerRenderer(renderers.BaseRenderer):\n    media_type = 'application/openapi+json'\n    format = 'swagger'\n\n    def render(self, data, media_type=None, renderer_context=None):\n        codec = OpenAPICodec()\n        return codec.dump(data)\n\n\n\n\n\nAPI Reference\n\n\nSchemaGenerator\n\n\nA class that deals with introspecting your API views, which can be used to\ngenerate a schema.\n\n\nTypically you'll instantiate \nSchemaGenerator\n with a single argument, like so:\n\n\ngenerator = SchemaGenerator(title='Stock Prices API')\n\n\n\nArguments:\n\n\n\n\ntitle\n - The name of the API. \nrequired\n\n\nurl\n - The root URL of the API schema. This option is not required unless the schema is included under path prefix.\n\n\npatterns\n - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.\n\n\nurlconf\n - A URL conf module name to use when generating the schema. Defaults to \nsettings.ROOT_URLCONF\n.\n\n\n\n\nget_schema()\n\n\nReturns a \ncoreapi.Document\n instance that represents the API schema.\n\n\n@api_view\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return Response(generator.get_schema())\n\n\n\nArguments:\n\n\n\n\nrequest\n - The incoming request. Optionally used if you want to apply per-user permissions to the schema-generation.\n\n\n\n\n\n\nCore API\n\n\nThis documentation gives a brief overview of the components within the \ncoreapi\n\npackage that are used to represent an API schema.\n\n\nNote that these classes are imported from the \ncoreapi\n package, rather than\nfrom the \nrest_framework\n package.\n\n\nDocument\n\n\nRepresents a container for the API schema.\n\n\ntitle\n\n\nA name for the API.\n\n\nurl\n\n\nA canonical URL for the API.\n\n\ncontent\n\n\nA dictionary, containing the \nLink\n objects that the schema contains.\n\n\nIn order to provide more structure to the schema, the \ncontent\n dictionary\nmay be nested, typically to a second level. For example:\n\n\ncontent={\n    \"bookings\": {\n        \"list\": Link(...),\n        \"create\": Link(...),\n        ...\n    },\n    \"venues\": {\n        \"list\": Link(...),\n        ...\n    },\n    ...\n}\n\n\n\nLink\n\n\nRepresents an individual API endpoint.\n\n\nurl\n\n\nThe URL of the endpoint. May be a URI template, such as \n/users/{username}/\n.\n\n\naction\n\n\nThe HTTP method associated with the endpoint. Note that URLs that support\nmore than one HTTP method, should correspond to a single \nLink\n for each.\n\n\nfields\n\n\nA list of \nField\n instances, describing the available parameters on the input.\n\n\ndescription\n\n\nA short description of the meaning and intended usage of the endpoint.\n\n\nField\n\n\nRepresents a single input parameter on a given API endpoint.\n\n\nname\n\n\nA descriptive name for the input.\n\n\nrequired\n\n\nA boolean, indicated if the client is required to included a value, or if\nthe parameter can be omitted.\n\n\nlocation\n\n\nDetermines how the information is encoded into the request. Should be one of\nthe following strings:\n\n\n\"path\"\n\n\nIncluded in a templated URI. For example a \nurl\n value of \n/products/{product_code}/\n could be used together with a \n\"path\"\n field, to handle API inputs in a URL path such as \n/products/slim-fit-jeans/\n.\n\n\nThese fields will normally correspond with \nnamed arguments in the project URL conf\n.\n\n\n\"query\"\n\n\nIncluded as a URL query parameter. For example \n?search=sale\n. Typically for \nGET\n requests.\n\n\nThese fields will normally correspond with pagination and filtering controls on a view.\n\n\n\"form\"\n\n\nIncluded in the request body, as a single item of a JSON object or HTML form. For example \n{\"colour\": \"blue\", ...}\n. Typically for \nPOST\n, \nPUT\n and \nPATCH\n requests. Multiple \n\"form\"\n fields may be included on a single link.\n\n\nThese fields will normally correspond with serializer fields on a view.\n\n\n\"body\"\n\n\nIncluded as the complete request body. Typically for \nPOST\n, \nPUT\n and \nPATCH\n requests. No more than one \n\"body\"\n field may exist on a link. May not be used together with \n\"form\"\n fields.\n\n\nThese fields will normally correspond with views that use \nListSerializer\n to validate the request input, or with file upload views.\n\n\nencoding\n\n\n\"application/json\"\n\n\nJSON encoded request content. Corresponds to views using \nJSONParser\n.\nValid only if either one or more \nlocation=\"form\"\n fields, or a single\n\nlocation=\"body\"\n field is included on the \nLink\n.\n\n\n\"multipart/form-data\"\n\n\nMultipart encoded request content. Corresponds to views using \nMultiPartParser\n.\nValid only if one or more \nlocation=\"form\"\n fields is included on the \nLink\n.\n\n\n\"application/x-www-form-urlencoded\"\n\n\nURL encoded request content. Corresponds to views using \nFormParser\n. Valid\nonly if one or more \nlocation=\"form\"\n fields is included on the \nLink\n.\n\n\n\"application/octet-stream\"\n\n\nBinary upload request content. Corresponds to views using \nFileUploadParser\n.\nValid only if a \nlocation=\"body\"\n field is included on the \nLink\n.\n\n\ndescription\n\n\nA short description of the meaning and intended usage of the input field.", 
    +            "text": "Schemas\n\n\n\n\nA machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.\n\n\n Heroku, \nJSON Schema for the Heroku Platform API\n\n\n\n\nAPI schemas are a useful tool that allow for a range of use cases, including\ngenerating reference documentation, or driving dynamic client libraries that\ncan interact with your API.\n\n\nRepresenting schemas internally\n\n\nREST framework uses \nCore API\n in order to model schema information in\na format-independent representation. This information can then be rendered\ninto various different schema formats, or used to generate API documentation.\n\n\nWhen using Core API, a schema is represented as a \nDocument\n which is the\ntop-level container object for information about the API. Available API\ninteractions are represented using \nLink\n objects. Each link includes a URL,\nHTTP method, and may include a list of \nField\n instances, which describe any\nparameters that may be accepted by the API endpoint. The \nLink\n and \nField\n\ninstances may also include descriptions, that allow an API schema to be\nrendered into user documentation.\n\n\nHere's an example of an API description that includes a single \nsearch\n\nendpoint:\n\n\ncoreapi.Document(\n    title='Flight Search API',\n    url='https://api.example.org/',\n    content={\n        'search': coreapi.Link(\n            url='/search/',\n            action='get',\n            fields=[\n                coreapi.Field(\n                    name='from',\n                    required=True,\n                    location='query',\n                    description='City name or airport code.'\n                ),\n                coreapi.Field(\n                    name='to',\n                    required=True,\n                    location='query',\n                    description='City name or airport code.'\n                ),\n                coreapi.Field(\n                    name='date',\n                    required=True,\n                    location='query',\n                    description='Flight date in \"YYYY-MM-DD\" format.'\n                )\n            ],\n            description='Return flight availability and prices.'\n        )\n    }\n)\n\n\n\nSchema output formats\n\n\nIn order to be presented in an HTTP response, the internal representation\nhas to be rendered into the actual bytes that are used in the response.\n\n\nCore JSON\n is designed as a canonical format for use with Core API.\nREST framework includes a renderer class for handling this media type, which\nis available as \nrenderers.CoreJSONRenderer\n.\n\n\nOther schema formats such as \nOpen API\n (\"Swagger\"),\n\nJSON HyperSchema\n, or \nAPI Blueprint\n can\nalso be supported by implementing a custom renderer class.\n\n\nSchemas vs Hypermedia\n\n\nIt's worth pointing out here that Core API can also be used to model hypermedia\nresponses, which present an alternative interaction style to API schemas.\n\n\nWith an API schema, the entire available interface is presented up-front\nas a single endpoint. Responses to individual API endpoints are then typically\npresented as plain data, without any further interactions contained in each\nresponse.\n\n\nWith Hypermedia, the client is instead presented with a document containing\nboth data and available interactions. Each interaction results in a new\ndocument, detailing both the current state and the available interactions.\n\n\nFurther information and support on building Hypermedia APIs with REST framework\nis planned for a future version.\n\n\n\n\nAdding a schema\n\n\nYou'll need to install the \ncoreapi\n package in order to add schema support\nfor REST framework.\n\n\npip install coreapi\n\n\n\nREST framework includes functionality for auto-generating a schema,\nor allows you to specify one explicitly. There are a few different ways to\nadd a schema to your API, depending on exactly what you need.\n\n\nThe get_schema_view shortcut\n\n\nThe simplest way to include a schema in your project is to use the\n\nget_schema_view()\n function.\n\n\nschema_view = get_schema_view(title=\"Server Monitoring API\")\n\nurlpatterns = [\n    url('^$', schema_view),\n    ...\n]\n\n\n\nOnce the view has been added, you'll be able to make API requests to retrieve\nthe auto-generated schema definition.\n\n\n$ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Server Monitoring API\"\n    },\n    \"_type\": \"document\",\n    ...\n}\n\n\n\nThe arguments to \nget_schema_view()\n are:\n\n\ntitle\n\n\nMay be used to provide a descriptive title for the schema definition.\n\n\nurl\n\n\nMay be used to pass a canonical URL for the schema.\n\n\nschema_view = get_schema_view(\n    title='Server Monitoring API',\n    url='https://www.example.org/api/'\n)\n\n\n\nrenderer_classes\n\n\nMay be used to pass the set of renderer classes that can be used to render the API root endpoint.\n\n\nfrom rest_framework.renderers import CoreJSONRenderer\nfrom my_custom_package import APIBlueprintRenderer\n\nschema_view = get_schema_view(\n    title='Server Monitoring API',\n    url='https://www.example.org/api/',\n    renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]\n)\n\n\n\nUsing an explicit schema view\n\n\nIf you need a little more control than the \nget_schema_view()\n shortcut gives you,\nthen you can use the \nSchemaGenerator\n class directly to auto-generate the\n\nDocument\n instance, and to return that from a view.\n\n\nThis option gives you the flexibility of setting up the schema endpoint\nwith whatever behaviour you want. For example, you can apply different\npermission, throttling, or authentication policies to the schema endpoint.\n\n\nHere's an example of using \nSchemaGenerator\n together with a view to\nreturn the schema.\n\n\nviews.py:\n\n\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response, schemas\n\ngenerator = schemas.SchemaGenerator(title='Bookings API')\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    schema = generator.get_schema(request)\n    return response.Response(schema)\n\n\n\nurls.py:\n\n\nurlpatterns = [\n    url('/', schema_view),\n    ...\n]\n\n\n\nYou can also serve different schemas to different users, depending on the\npermissions they have available. This approach can be used to ensure that\nunauthenticated requests are presented with a different schema to\nauthenticated requests, or to ensure that different parts of the API are\nmade visible to different users depending on their role.\n\n\nIn order to present a schema with endpoints filtered by user permissions,\nyou need to pass the \nrequest\n argument to the \nget_schema()\n method, like so:\n\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema(request=request))\n\n\n\nExplicit schema definition\n\n\nAn alternative to the auto-generated approach is to specify the API schema\nexplicitly, by declaring a \nDocument\n object in your codebase. Doing so is a\nlittle more work, but ensures that you have full control over the schema\nrepresentation.\n\n\nimport coreapi\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response\n\nschema = coreapi.Document(\n    title='Bookings API',\n    content={\n        ...\n    }\n)\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    return response.Response(schema)\n\n\n\nStatic schema file\n\n\nA final option is to write your API schema as a static file, using one\nof the available formats, such as Core JSON or Open API.\n\n\nYou could then either:\n\n\n\n\nWrite a schema definition as a static file, and \nserve the static file directly\n.\n\n\nWrite a schema definition that is loaded using \nCore API\n, and then\n  rendered to one of many available formats, depending on the client request.\n\n\n\n\n\n\nSchemas as documentation\n\n\nOne common usage of API schemas is to use them to build documentation pages.\n\n\nThe schema generation in REST framework uses docstrings to automatically\npopulate descriptions in the schema document.\n\n\nThese descriptions will be based on:\n\n\n\n\nThe corresponding method docstring if one exists.\n\n\nA named section within the class docstring, which can be either single line or multi-line.\n\n\nThe class docstring.\n\n\n\n\nExamples\n\n\nAn \nAPIView\n, with an explicit method docstring.\n\n\nclass ListUsernames(APIView):\n    def get(self, request):\n        \"\"\"\n        Return a list of all user names in the system.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)\n\n\n\nA \nViewSet\n, with an explict action docstring.\n\n\nclass ListUsernames(ViewSet):\n    def list(self, request):\n        \"\"\"\n        Return a list of all user names in the system.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)\n\n\n\nA generic view with sections in the class docstring, using single-line style.\n\n\nclass UserList(generics.ListCreateAPIView):\n    \"\"\"\n    get: Create a new user.\n    post: List all the users.\n    \"\"\"\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)\n\n\n\nA generic viewset with sections in the class docstring, using multi-line style.\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    API endpoint that allows users to be viewed or edited.\n\n    retrieve:\n    Return a user instance.\n\n    list:\n    Return all users, ordered by most recently joined.\n    \"\"\"\n    queryset = User.objects.all().order_by('-date_joined')\n    serializer_class = UserSerializer\n\n\n\n\n\nAlternate schema formats\n\n\nIn order to support an alternate schema format, you need to implement a custom renderer\nclass that handles converting a \nDocument\n instance into a bytestring representation.\n\n\nIf there is a Core API codec package that supports encoding into the format you\nwant to use then implementing the renderer class can be done by using the codec.\n\n\nExample\n\n\nFor example, the \nopenapi_codec\n package provides support for encoding or decoding\nto the Open API (\"Swagger\") format:\n\n\nfrom rest_framework import renderers\nfrom openapi_codec import OpenAPICodec\n\nclass SwaggerRenderer(renderers.BaseRenderer):\n    media_type = 'application/openapi+json'\n    format = 'swagger'\n\n    def render(self, data, media_type=None, renderer_context=None):\n        codec = OpenAPICodec()\n        return codec.dump(data)\n\n\n\n\n\nAPI Reference\n\n\nSchemaGenerator\n\n\nA class that deals with introspecting your API views, which can be used to\ngenerate a schema.\n\n\nTypically you'll instantiate \nSchemaGenerator\n with a single argument, like so:\n\n\ngenerator = SchemaGenerator(title='Stock Prices API')\n\n\n\nArguments:\n\n\n\n\ntitle\n - The name of the API. \nrequired\n\n\nurl\n - The root URL of the API schema. This option is not required unless the schema is included under path prefix.\n\n\npatterns\n - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.\n\n\nurlconf\n - A URL conf module name to use when generating the schema. Defaults to \nsettings.ROOT_URLCONF\n.\n\n\n\n\nget_schema()\n\n\nReturns a \ncoreapi.Document\n instance that represents the API schema.\n\n\n@api_view\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return Response(generator.get_schema())\n\n\n\nArguments:\n\n\n\n\nrequest\n - The incoming request. Optionally used if you want to apply per-user permissions to the schema-generation.\n\n\n\n\n\n\nCore API\n\n\nThis documentation gives a brief overview of the components within the \ncoreapi\n\npackage that are used to represent an API schema.\n\n\nNote that these classes are imported from the \ncoreapi\n package, rather than\nfrom the \nrest_framework\n package.\n\n\nDocument\n\n\nRepresents a container for the API schema.\n\n\ntitle\n\n\nA name for the API.\n\n\nurl\n\n\nA canonical URL for the API.\n\n\ncontent\n\n\nA dictionary, containing the \nLink\n objects that the schema contains.\n\n\nIn order to provide more structure to the schema, the \ncontent\n dictionary\nmay be nested, typically to a second level. For example:\n\n\ncontent={\n    \"bookings\": {\n        \"list\": Link(...),\n        \"create\": Link(...),\n        ...\n    },\n    \"venues\": {\n        \"list\": Link(...),\n        ...\n    },\n    ...\n}\n\n\n\nLink\n\n\nRepresents an individual API endpoint.\n\n\nurl\n\n\nThe URL of the endpoint. May be a URI template, such as \n/users/{username}/\n.\n\n\naction\n\n\nThe HTTP method associated with the endpoint. Note that URLs that support\nmore than one HTTP method, should correspond to a single \nLink\n for each.\n\n\nfields\n\n\nA list of \nField\n instances, describing the available parameters on the input.\n\n\ndescription\n\n\nA short description of the meaning and intended usage of the endpoint.\n\n\nField\n\n\nRepresents a single input parameter on a given API endpoint.\n\n\nname\n\n\nA descriptive name for the input.\n\n\nrequired\n\n\nA boolean, indicated if the client is required to included a value, or if\nthe parameter can be omitted.\n\n\nlocation\n\n\nDetermines how the information is encoded into the request. Should be one of\nthe following strings:\n\n\n\"path\"\n\n\nIncluded in a templated URI. For example a \nurl\n value of \n/products/{product_code}/\n could be used together with a \n\"path\"\n field, to handle API inputs in a URL path such as \n/products/slim-fit-jeans/\n.\n\n\nThese fields will normally correspond with \nnamed arguments in the project URL conf\n.\n\n\n\"query\"\n\n\nIncluded as a URL query parameter. For example \n?search=sale\n. Typically for \nGET\n requests.\n\n\nThese fields will normally correspond with pagination and filtering controls on a view.\n\n\n\"form\"\n\n\nIncluded in the request body, as a single item of a JSON object or HTML form. For example \n{\"colour\": \"blue\", ...}\n. Typically for \nPOST\n, \nPUT\n and \nPATCH\n requests. Multiple \n\"form\"\n fields may be included on a single link.\n\n\nThese fields will normally correspond with serializer fields on a view.\n\n\n\"body\"\n\n\nIncluded as the complete request body. Typically for \nPOST\n, \nPUT\n and \nPATCH\n requests. No more than one \n\"body\"\n field may exist on a link. May not be used together with \n\"form\"\n fields.\n\n\nThese fields will normally correspond with views that use \nListSerializer\n to validate the request input, or with file upload views.\n\n\nencoding\n\n\n\"application/json\"\n\n\nJSON encoded request content. Corresponds to views using \nJSONParser\n.\nValid only if either one or more \nlocation=\"form\"\n fields, or a single\n\nlocation=\"body\"\n field is included on the \nLink\n.\n\n\n\"multipart/form-data\"\n\n\nMultipart encoded request content. Corresponds to views using \nMultiPartParser\n.\nValid only if one or more \nlocation=\"form\"\n fields is included on the \nLink\n.\n\n\n\"application/x-www-form-urlencoded\"\n\n\nURL encoded request content. Corresponds to views using \nFormParser\n. Valid\nonly if one or more \nlocation=\"form\"\n fields is included on the \nLink\n.\n\n\n\"application/octet-stream\"\n\n\nBinary upload request content. Corresponds to views using \nFileUploadParser\n.\nValid only if a \nlocation=\"body\"\n field is included on the \nLink\n.\n\n\ndescription\n\n\nA short description of the meaning and intended usage of the input field.", 
                 "title": "Schemas"
             }, 
             {
    @@ -3016,29 +3036,29 @@
                 "title": "Adding a schema"
             }, 
             {
    -            "location": "/api-guide/schemas/#using-defaultrouter", 
    -            "text": "If you're using  DefaultRouter  then you can include an auto-generated schema,\nsimply by adding a  schema_title  argument to the router.  router = DefaultRouter(schema_title='Server Monitoring API')  The schema will be included at the root URL,  / , and presented to clients\nthat include the Core JSON media type in their  Accept  header.  $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Server Monitoring API\"\n    },\n    \"_type\": \"document\",\n    ...\n}  This is a great zero-configuration option for when you want to get up and\nrunning really quickly.  The other available options to  DefaultRouter  are:", 
    -            "title": "Using DefaultRouter"
    +            "location": "/api-guide/schemas/#the-get_schema_view-shortcut", 
    +            "text": "The simplest way to include a schema in your project is to use the get_schema_view()  function.  schema_view = get_schema_view(title=\"Server Monitoring API\")\n\nurlpatterns = [\n    url('^$', schema_view),\n    ...\n]  Once the view has been added, you'll be able to make API requests to retrieve\nthe auto-generated schema definition.  $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/vnd.coreapi+json\n\n{\n    \"_meta\": {\n        \"title\": \"Server Monitoring API\"\n    },\n    \"_type\": \"document\",\n    ...\n}  The arguments to  get_schema_view()  are:", 
    +            "title": "The get_schema_view shortcut"
             }, 
             {
    -            "location": "/api-guide/schemas/#schema_renderers", 
    -            "text": "May be used to pass the set of renderer classes that can be used to render schema output.  from rest_framework.renderers import CoreJSONRenderer\nfrom my_custom_package import APIBlueprintRenderer\n\nrouter = DefaultRouter(schema_title='Server Monitoring API', schema_renderers=[\n    CoreJSONRenderer, APIBlueprintRenderer\n])", 
    -            "title": "schema_renderers"
    +            "location": "/api-guide/schemas/#title", 
    +            "text": "May be used to provide a descriptive title for the schema definition.", 
    +            "title": "title"
             }, 
             {
    -            "location": "/api-guide/schemas/#schema_url", 
    -            "text": "May be used to pass the root URL for the schema. This can either be used to ensure that\nthe schema URLs include a canonical hostname and schema, or to ensure that all the\nschema URLs include a path prefix.  router = DefaultRouter(\n    schema_title='Server Monitoring API',\n    schema_url='https://www.example.org/api/'\n)  If you want more flexibility over the schema output then you'll need to consider\nusing  SchemaGenerator  instead.", 
    -            "title": "schema_url"
    +            "location": "/api-guide/schemas/#url", 
    +            "text": "May be used to pass a canonical URL for the schema.  schema_view = get_schema_view(\n    title='Server Monitoring API',\n    url='https://www.example.org/api/'\n)", 
    +            "title": "url"
             }, 
             {
    -            "location": "/api-guide/schemas/#root_renderers", 
    -            "text": "May be used to pass the set of renderer classes that can be used to render the API root endpoint.", 
    -            "title": "root_renderers"
    +            "location": "/api-guide/schemas/#renderer_classes", 
    +            "text": "May be used to pass the set of renderer classes that can be used to render the API root endpoint.  from rest_framework.renderers import CoreJSONRenderer\nfrom my_custom_package import APIBlueprintRenderer\n\nschema_view = get_schema_view(\n    title='Server Monitoring API',\n    url='https://www.example.org/api/',\n    renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]\n)", 
    +            "title": "renderer_classes"
             }, 
             {
    -            "location": "/api-guide/schemas/#using-schemagenerator", 
    -            "text": "The most common way to add a schema to your API is to use the  SchemaGenerator \nclass to auto-generate the  Document  instance, and to return that from a view.  This option gives you the flexibility of setting up the schema endpoint\nwith whatever behavior you want. For example, you can apply different\npermission, throttling or authentication policies to the schema endpoint.  Here's an example of using  SchemaGenerator  together with a view to\nreturn the schema.  views.py:  from rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response, schemas\n\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema())  urls.py:  urlpatterns = [\n    url('/', schema_view),\n    ...\n]  You can also serve different schemas to different users, depending on the\npermissions they have available. This approach can be used to ensure that\nunauthenticated requests are presented with a different schema to\nauthenticated requests, or to ensure that different parts of the API are\nmade visible to different users depending on their role.  In order to present a schema with endpoints filtered by user permissions,\nyou need to pass the  request  argument to the  get_schema()  method, like so:  @api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema(request=request))", 
    -            "title": "Using SchemaGenerator"
    +            "location": "/api-guide/schemas/#using-an-explicit-schema-view", 
    +            "text": "If you need a little more control than the  get_schema_view()  shortcut gives you,\nthen you can use the  SchemaGenerator  class directly to auto-generate the Document  instance, and to return that from a view.  This option gives you the flexibility of setting up the schema endpoint\nwith whatever behaviour you want. For example, you can apply different\npermission, throttling, or authentication policies to the schema endpoint.  Here's an example of using  SchemaGenerator  together with a view to\nreturn the schema.  views.py:  from rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework import renderers, response, schemas\n\ngenerator = schemas.SchemaGenerator(title='Bookings API')\n\n@api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    schema = generator.get_schema(request)\n    return response.Response(schema)  urls.py:  urlpatterns = [\n    url('/', schema_view),\n    ...\n]  You can also serve different schemas to different users, depending on the\npermissions they have available. This approach can be used to ensure that\nunauthenticated requests are presented with a different schema to\nauthenticated requests, or to ensure that different parts of the API are\nmade visible to different users depending on their role.  In order to present a schema with endpoints filtered by user permissions,\nyou need to pass the  request  argument to the  get_schema()  method, like so:  @api_view()\n@renderer_classes([renderers.CoreJSONRenderer])\ndef schema_view(request):\n    generator = schemas.SchemaGenerator(title='Bookings API')\n    return response.Response(generator.get_schema(request=request))", 
    +            "title": "Using an explicit schema view"
             }, 
             {
                 "location": "/api-guide/schemas/#explicit-schema-definition", 
    @@ -3050,6 +3070,16 @@
                 "text": "A final option is to write your API schema as a static file, using one\nof the available formats, such as Core JSON or Open API.  You could then either:   Write a schema definition as a static file, and  serve the static file directly .  Write a schema definition that is loaded using  Core API , and then\n  rendered to one of many available formats, depending on the client request.", 
                 "title": "Static schema file"
             }, 
    +        {
    +            "location": "/api-guide/schemas/#schemas-as-documentation", 
    +            "text": "One common usage of API schemas is to use them to build documentation pages.  The schema generation in REST framework uses docstrings to automatically\npopulate descriptions in the schema document.  These descriptions will be based on:   The corresponding method docstring if one exists.  A named section within the class docstring, which can be either single line or multi-line.  The class docstring.", 
    +            "title": "Schemas as documentation"
    +        }, 
    +        {
    +            "location": "/api-guide/schemas/#examples", 
    +            "text": "An  APIView , with an explicit method docstring.  class ListUsernames(APIView):\n    def get(self, request):\n        \"\"\"\n        Return a list of all user names in the system.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)  A  ViewSet , with an explict action docstring.  class ListUsernames(ViewSet):\n    def list(self, request):\n        \"\"\"\n        Return a list of all user names in the system.\n        \"\"\"\n        usernames = [user.username for user in User.objects.all()]\n        return Response(usernames)  A generic view with sections in the class docstring, using single-line style.  class UserList(generics.ListCreateAPIView):\n    \"\"\"\n    get: Create a new user.\n    post: List all the users.\n    \"\"\"\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n    permission_classes = (IsAdminUser,)  A generic viewset with sections in the class docstring, using multi-line style.  class UserViewSet(viewsets.ModelViewSet):\n    \"\"\"\n    API endpoint that allows users to be viewed or edited.\n\n    retrieve:\n    Return a user instance.\n\n    list:\n    Return all users, ordered by most recently joined.\n    \"\"\"\n    queryset = User.objects.all().order_by('-date_joined')\n    serializer_class = UserSerializer", 
    +            "title": "Examples"
    +        }, 
             {
                 "location": "/api-guide/schemas/#alternate-schema-formats", 
                 "text": "In order to support an alternate schema format, you need to implement a custom renderer\nclass that handles converting a  Document  instance into a bytestring representation.  If there is a Core API codec package that supports encoding into the format you\nwant to use then implementing the renderer class can be done by using the codec.", 
    @@ -3086,12 +3116,12 @@
                 "title": "Document"
             }, 
             {
    -            "location": "/api-guide/schemas/#title", 
    +            "location": "/api-guide/schemas/#title_1", 
                 "text": "A name for the API.", 
                 "title": "title"
             }, 
             {
    -            "location": "/api-guide/schemas/#url", 
    +            "location": "/api-guide/schemas/#url_1", 
                 "text": "A canonical URL for the API.", 
                 "title": "url"
             }, 
    @@ -3106,7 +3136,7 @@
                 "title": "Link"
             }, 
             {
    -            "location": "/api-guide/schemas/#url_1", 
    +            "location": "/api-guide/schemas/#url_2", 
                 "text": "The URL of the endpoint. May be a URI template, such as  /users/{username}/ .", 
                 "title": "url"
             }, 
    @@ -3187,7 +3217,7 @@
             }, 
             {
                 "location": "/api-guide/reverse/", 
    -            "text": "Returning URLs\n\n\n\n\nThe central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.\n\n\n Roy Fielding, \nArchitectural Styles and the Design of Network-based Software Architectures\n\n\n\n\nAs a rule, it's probably better practice to return absolute URIs from your Web APIs, such as \nhttp://example.com/foobar\n, rather than returning relative URIs, such as \n/foobar\n.\n\n\nThe advantages of doing so are:\n\n\n\n\nIt's more explicit.\n\n\nIt leaves less work for your API clients.\n\n\nThere's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.\n\n\nIt makes it easy to do things like markup HTML representations with hyperlinks.\n\n\n\n\nREST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.\n\n\nThere'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.\n\n\nreverse\n\n\nSignature:\n \nreverse(viewname, *args, **kwargs)\n\n\nHas the same behavior as \ndjango.core.urlresolvers.reverse\n, except that it returns a fully qualified URL, using the request to determine the host and port.\n\n\nYou should \ninclude the request as a keyword argument\n to the function, for example:\n\n\nfrom rest_framework.reverse import reverse\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n    def get(self, request):\n        year = now().year\n        data = {\n            ...\n            'year-summary-url': reverse('year-summary', args=[year], request=request)\n        }\n        return Response(data)\n\n\n\nreverse_lazy\n\n\nSignature:\n \nreverse_lazy(viewname, *args, **kwargs)\n\n\nHas the same behavior as \ndjango.core.urlresolvers.reverse_lazy\n, except that it returns a fully qualified URL, using the request to determine the host and port.\n\n\nAs with the \nreverse\n function, you should \ninclude the request as a keyword argument\n to the function, for example:\n\n\napi_root = reverse_lazy('api-root', request=request)", 
    +            "text": "Returning URLs\n\n\n\n\nThe central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.\n\n\n Roy Fielding, \nArchitectural Styles and the Design of Network-based Software Architectures\n\n\n\n\nAs a rule, it's probably better practice to return absolute URIs from your Web APIs, such as \nhttp://example.com/foobar\n, rather than returning relative URIs, such as \n/foobar\n.\n\n\nThe advantages of doing so are:\n\n\n\n\nIt's more explicit.\n\n\nIt leaves less work for your API clients.\n\n\nThere's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.\n\n\nIt makes it easy to do things like markup HTML representations with hyperlinks.\n\n\n\n\nREST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.\n\n\nThere'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.\n\n\nreverse\n\n\nSignature:\n \nreverse(viewname, *args, **kwargs)\n\n\nHas the same behavior as \ndjango.urls.reverse\n, except that it returns a fully qualified URL, using the request to determine the host and port.\n\n\nYou should \ninclude the request as a keyword argument\n to the function, for example:\n\n\nfrom rest_framework.reverse import reverse\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n    def get(self, request):\n        year = now().year\n        data = {\n            ...\n            'year-summary-url': reverse('year-summary', args=[year], request=request)\n        }\n        return Response(data)\n\n\n\nreverse_lazy\n\n\nSignature:\n \nreverse_lazy(viewname, *args, **kwargs)\n\n\nHas the same behavior as \ndjango.urls.reverse_lazy\n, except that it returns a fully qualified URL, using the request to determine the host and port.\n\n\nAs with the \nreverse\n function, you should \ninclude the request as a keyword argument\n to the function, for example:\n\n\napi_root = reverse_lazy('api-root', request=request)", 
                 "title": "Returning URLs"
             }, 
             {
    @@ -3197,17 +3227,17 @@
             }, 
             {
                 "location": "/api-guide/reverse/#reverse", 
    -            "text": "Signature:   reverse(viewname, *args, **kwargs)  Has the same behavior as  django.core.urlresolvers.reverse , except that it returns a fully qualified URL, using the request to determine the host and port.  You should  include the request as a keyword argument  to the function, for example:  from rest_framework.reverse import reverse\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n    def get(self, request):\n        year = now().year\n        data = {\n            ...\n            'year-summary-url': reverse('year-summary', args=[year], request=request)\n        }\n        return Response(data)", 
    +            "text": "Signature:   reverse(viewname, *args, **kwargs)  Has the same behavior as  django.urls.reverse , except that it returns a fully qualified URL, using the request to determine the host and port.  You should  include the request as a keyword argument  to the function, for example:  from rest_framework.reverse import reverse\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n    def get(self, request):\n        year = now().year\n        data = {\n            ...\n            'year-summary-url': reverse('year-summary', args=[year], request=request)\n        }\n        return Response(data)", 
                 "title": "reverse"
             }, 
             {
                 "location": "/api-guide/reverse/#reverse_lazy", 
    -            "text": "Signature:   reverse_lazy(viewname, *args, **kwargs)  Has the same behavior as  django.core.urlresolvers.reverse_lazy , except that it returns a fully qualified URL, using the request to determine the host and port.  As with the  reverse  function, you should  include the request as a keyword argument  to the function, for example:  api_root = reverse_lazy('api-root', request=request)", 
    +            "text": "Signature:   reverse_lazy(viewname, *args, **kwargs)  Has the same behavior as  django.urls.reverse_lazy , except that it returns a fully qualified URL, using the request to determine the host and port.  As with the  reverse  function, you should  include the request as a keyword argument  to the function, for example:  api_root = reverse_lazy('api-root', request=request)", 
                 "title": "reverse_lazy"
             }, 
             {
                 "location": "/api-guide/exceptions/", 
    -            "text": "Exceptions\n\n\n\n\nExceptions\u2026 allow error handling to be organized cleanly in a central or high-level place within the program structure.\n\n\n Doug Hellmann, \nPython Exception Handling Techniques\n\n\n\n\nException handling in REST framework views\n\n\nREST framework's views handle various exceptions, and deal with returning appropriate error responses.\n\n\nThe handled exceptions are:\n\n\n\n\nSubclasses of \nAPIException\n raised inside REST framework.\n\n\nDjango's \nHttp404\n exception.\n\n\nDjango's \nPermissionDenied\n exception.\n\n\n\n\nIn each case, REST framework will return a response with an appropriate status code and content-type.  The body of the response will include any additional details regarding the nature of the error.\n\n\nMost error responses will include a key \ndetail\n in the body of the response.\n\n\nFor example, the following request:\n\n\nDELETE http://api.example.com/foo/bar HTTP/1.1\nAccept: application/json\n\n\n\nMight receive an error response indicating that the \nDELETE\n method is not allowed on that resource:\n\n\nHTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 42\n\n{\"detail\": \"Method 'DELETE' not allowed.\"}\n\n\n\nValidation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the \"non_field_errors\" key, or whatever string value has been set for the \nNON_FIELD_ERRORS_KEY\n setting.\n\n\nAny example validation error might look like this:\n\n\nHTTP/1.1 400 Bad Request\nContent-Type: application/json\nContent-Length: 94\n\n{\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]}\n\n\n\nCustom exception handling\n\n\nYou 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.\n\n\nThe 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 \nResponse\n object, or return \nNone\n if the exception cannot be handled.  If the handler returns \nNone\n then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.\n\n\nFor example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:\n\n\nHTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 62\n\n{\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"}\n\n\n\nIn order to alter the style of the response, you could write the following custom exception handler:\n\n\nfrom rest_framework.views import exception_handler\n\ndef custom_exception_handler(exc, context):\n    # Call REST framework's default exception handler first,\n    # to get the standard error response.\n    response = exception_handler(exc, context)\n\n    #\u00a0Now add the HTTP status code to the response.\n    if response is not None:\n        response.data['status_code'] = response.status_code\n\n    return response\n\n\n\nThe context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as \ncontext['view']\n.\n\n\nThe exception handler must also be configured in your settings, using the \nEXCEPTION_HANDLER\n setting key. For example:\n\n\nREST_FRAMEWORK = {\n    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'\n}\n\n\n\nIf not specified, the \n'EXCEPTION_HANDLER'\n setting defaults to the standard exception handler provided by REST framework:\n\n\nREST_FRAMEWORK = {\n    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'\n}\n\n\n\nNote 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 \nHTTP_400_BAD_REQUEST\n responses that are returned by the generic views when serializer validation fails.\n\n\n\n\nAPI Reference\n\n\nAPIException\n\n\nSignature:\n \nAPIException()\n\n\nThe \nbase class\n for all exceptions raised inside an \nAPIView\n class or \n@api_view\n.\n\n\nTo provide a custom exception, subclass \nAPIException\n and set the \n.status_code\n and \n.default_detail\n properties on the class.\n\n\nFor example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code.  You could do this like so:\n\n\nfrom rest_framework.exceptions import APIException\n\nclass ServiceUnavailable(APIException):\n    status_code = 503\n    default_detail = 'Service temporarily unavailable, try again later.'\n\n\n\nParseError\n\n\nSignature:\n \nParseError(detail=None)\n\n\nRaised if the request contains malformed data when accessing \nrequest.data\n.\n\n\nBy default this exception results in a response with the HTTP status code \"400 Bad Request\".\n\n\nAuthenticationFailed\n\n\nSignature:\n \nAuthenticationFailed(detail=None)\n\n\nRaised when an incoming request includes incorrect authentication.\n\n\nBy 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 \nauthentication documentation\n for more details.\n\n\nNotAuthenticated\n\n\nSignature:\n \nNotAuthenticated(detail=None)\n\n\nRaised when an unauthenticated request fails the permission checks.\n\n\nBy 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 \nauthentication documentation\n for more details.\n\n\nPermissionDenied\n\n\nSignature:\n \nPermissionDenied(detail=None)\n\n\nRaised when an authenticated request fails the permission checks.\n\n\nBy default this exception results in a response with the HTTP status code \"403 Forbidden\".\n\n\nNotFound\n\n\nSignature:\n \nNotFound(detail=None)\n\n\nRaised when a resource does not exists at the given URL. This exception is equivalent to the standard \nHttp404\n Django exception.\n\n\nBy default this exception results in a response with the HTTP status code \"404 Not Found\".\n\n\nMethodNotAllowed\n\n\nSignature:\n \nMethodNotAllowed(method, detail=None)\n\n\nRaised when an incoming request occurs that does not map to a handler method on the view.\n\n\nBy default this exception results in a response with the HTTP status code \"405 Method Not Allowed\".\n\n\nNotAcceptable\n\n\nSignature:\n \nNotAcceptable(detail=None)\n\n\nRaised when an incoming request occurs with an \nAccept\n header that cannot be satisfied by any of the available renderers.\n\n\nBy default this exception results in a response with the HTTP status code \"406 Not Acceptable\".\n\n\nUnsupportedMediaType\n\n\nSignature:\n \nUnsupportedMediaType(media_type, detail=None)\n\n\nRaised if there are no parsers that can handle the content type of the request data when accessing \nrequest.data\n.\n\n\nBy default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\".\n\n\nThrottled\n\n\nSignature:\n \nThrottled(wait=None, detail=None)\n\n\nRaised when an incoming request fails the throttling checks.\n\n\nBy default this exception results in a response with the HTTP status code \"429 Too Many Requests\".\n\n\nValidationError\n\n\nSignature:\n \nValidationError(detail)\n\n\nThe \nValidationError\n exception is slightly different from the other \nAPIException\n classes:\n\n\n\n\nThe \ndetail\n argument is mandatory, not optional.\n\n\nThe \ndetail\n argument may be a list or dictionary of error details, and may also be a nested data structure.\n\n\nBy convention you should import the serializers module and use a fully qualified \nValidationError\n style, in order to differentiate it from Django's built-in validation error. For example. \nraise serializers.ValidationError('This field must be an integer value.')\n\n\n\n\nThe \nValidationError\n class should be used for serializer and field validation, and by validator classes. It is also raised when calling \nserializer.is_valid\n with the \nraise_exception\n keyword argument:\n\n\nserializer.is_valid(raise_exception=True)\n\n\n\nThe generic views use the \nraise_exception=True\n flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.\n\n\nBy default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
    +            "text": "Exceptions\n\n\n\n\nExceptions\u2026 allow error handling to be organized cleanly in a central or high-level place within the program structure.\n\n\n Doug Hellmann, \nPython Exception Handling Techniques\n\n\n\n\nException handling in REST framework views\n\n\nREST framework's views handle various exceptions, and deal with returning appropriate error responses.\n\n\nThe handled exceptions are:\n\n\n\n\nSubclasses of \nAPIException\n raised inside REST framework.\n\n\nDjango's \nHttp404\n exception.\n\n\nDjango's \nPermissionDenied\n exception.\n\n\n\n\nIn each case, REST framework will return a response with an appropriate status code and content-type.  The body of the response will include any additional details regarding the nature of the error.\n\n\nMost error responses will include a key \ndetail\n in the body of the response.\n\n\nFor example, the following request:\n\n\nDELETE http://api.example.com/foo/bar HTTP/1.1\nAccept: application/json\n\n\n\nMight receive an error response indicating that the \nDELETE\n method is not allowed on that resource:\n\n\nHTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 42\n\n{\"detail\": \"Method 'DELETE' not allowed.\"}\n\n\n\nValidation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the \"non_field_errors\" key, or whatever string value has been set for the \nNON_FIELD_ERRORS_KEY\n setting.\n\n\nAny example validation error might look like this:\n\n\nHTTP/1.1 400 Bad Request\nContent-Type: application/json\nContent-Length: 94\n\n{\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]}\n\n\n\nCustom exception handling\n\n\nYou 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.\n\n\nThe 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 \nResponse\n object, or return \nNone\n if the exception cannot be handled.  If the handler returns \nNone\n then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.\n\n\nFor example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:\n\n\nHTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 62\n\n{\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"}\n\n\n\nIn order to alter the style of the response, you could write the following custom exception handler:\n\n\nfrom rest_framework.views import exception_handler\n\ndef custom_exception_handler(exc, context):\n    # Call REST framework's default exception handler first,\n    # to get the standard error response.\n    response = exception_handler(exc, context)\n\n    #\u00a0Now add the HTTP status code to the response.\n    if response is not None:\n        response.data['status_code'] = response.status_code\n\n    return response\n\n\n\nThe context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as \ncontext['view']\n.\n\n\nThe exception handler must also be configured in your settings, using the \nEXCEPTION_HANDLER\n setting key. For example:\n\n\nREST_FRAMEWORK = {\n    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'\n}\n\n\n\nIf not specified, the \n'EXCEPTION_HANDLER'\n setting defaults to the standard exception handler provided by REST framework:\n\n\nREST_FRAMEWORK = {\n    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'\n}\n\n\n\nNote 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 \nHTTP_400_BAD_REQUEST\n responses that are returned by the generic views when serializer validation fails.\n\n\n\n\nAPI Reference\n\n\nAPIException\n\n\nSignature:\n \nAPIException()\n\n\nThe \nbase class\n for all exceptions raised inside an \nAPIView\n class or \n@api_view\n.\n\n\nTo provide a custom exception, subclass \nAPIException\n and set the \n.status_code\n, \n.default_detail\n, and \ndefault_code\n attributes on the class.\n\n\nFor example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code.  You could do this like so:\n\n\nfrom rest_framework.exceptions import APIException\n\nclass ServiceUnavailable(APIException):\n    status_code = 503\n    default_detail = 'Service temporarily unavailable, try again later.'\n    default_code = 'service_unavailable'\n\n\n\nInspecting API exceptions\n\n\nThere are a number of different properties available for inspecting the status\nof an API exception. You can use these to build custom exception handling\nfor your project.\n\n\nThe available attributes and methods are:\n\n\n\n\n.detail\n - Return the textual description of the error.\n\n\n.get_codes()\n - Return the code identifier of the error.\n\n\n.full_details()\n - Return both the textual description and the code identifier.\n\n\n\n\nIn most cases the error detail will be a simple item:\n\n\n print(exc.detail)\nYou do not have permission to perform this action.\n\n print(exc.get_codes())\npermission_denied\n\n print(exc.full_details())\n{'message':'You do not have permission to perform this action.','code':'permission_denied'}\n\n\n\nIn the case of validation errors the error detail will be either a list or\ndictionary of items:\n\n\n print(exc.detail)\n{\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"}\n\n print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}\n\n print(exc.get_full_details())\n{\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}}\n\n\n\nParseError\n\n\nSignature:\n \nParseError(detail=None, code=None)\n\n\nRaised if the request contains malformed data when accessing \nrequest.data\n.\n\n\nBy default this exception results in a response with the HTTP status code \"400 Bad Request\".\n\n\nAuthenticationFailed\n\n\nSignature:\n \nAuthenticationFailed(detail=None, code=None)\n\n\nRaised when an incoming request includes incorrect authentication.\n\n\nBy 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 \nauthentication documentation\n for more details.\n\n\nNotAuthenticated\n\n\nSignature:\n \nNotAuthenticated(detail=None, code=None)\n\n\nRaised when an unauthenticated request fails the permission checks.\n\n\nBy 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 \nauthentication documentation\n for more details.\n\n\nPermissionDenied\n\n\nSignature:\n \nPermissionDenied(detail=None, code=None)\n\n\nRaised when an authenticated request fails the permission checks.\n\n\nBy default this exception results in a response with the HTTP status code \"403 Forbidden\".\n\n\nNotFound\n\n\nSignature:\n \nNotFound(detail=None, code=None)\n\n\nRaised when a resource does not exists at the given URL. This exception is equivalent to the standard \nHttp404\n Django exception.\n\n\nBy default this exception results in a response with the HTTP status code \"404 Not Found\".\n\n\nMethodNotAllowed\n\n\nSignature:\n \nMethodNotAllowed(method, detail=None, code=None)\n\n\nRaised when an incoming request occurs that does not map to a handler method on the view.\n\n\nBy default this exception results in a response with the HTTP status code \"405 Method Not Allowed\".\n\n\nNotAcceptable\n\n\nSignature:\n \nNotAcceptable(detail=None, code=None)\n\n\nRaised when an incoming request occurs with an \nAccept\n header that cannot be satisfied by any of the available renderers.\n\n\nBy default this exception results in a response with the HTTP status code \"406 Not Acceptable\".\n\n\nUnsupportedMediaType\n\n\nSignature:\n \nUnsupportedMediaType(media_type, detail=None, code=None)\n\n\nRaised if there are no parsers that can handle the content type of the request data when accessing \nrequest.data\n.\n\n\nBy default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\".\n\n\nThrottled\n\n\nSignature:\n \nThrottled(wait=None, detail=None, code=None)\n\n\nRaised when an incoming request fails the throttling checks.\n\n\nBy default this exception results in a response with the HTTP status code \"429 Too Many Requests\".\n\n\nValidationError\n\n\nSignature:\n \nValidationError(detail, code=None)\n\n\nThe \nValidationError\n exception is slightly different from the other \nAPIException\n classes:\n\n\n\n\nThe \ndetail\n argument is mandatory, not optional.\n\n\nThe \ndetail\n argument may be a list or dictionary of error details, and may also be a nested data structure.\n\n\nBy convention you should import the serializers module and use a fully qualified \nValidationError\n style, in order to differentiate it from Django's built-in validation error. For example. \nraise serializers.ValidationError('This field must be an integer value.')\n\n\n\n\nThe \nValidationError\n class should be used for serializer and field validation, and by validator classes. It is also raised when calling \nserializer.is_valid\n with the \nraise_exception\n keyword argument:\n\n\nserializer.is_valid(raise_exception=True)\n\n\n\nThe generic views use the \nraise_exception=True\n flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.\n\n\nBy default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
                 "title": "Exceptions"
             }, 
             {
    @@ -3232,57 +3262,62 @@
             }, 
             {
                 "location": "/api-guide/exceptions/#apiexception", 
    -            "text": "Signature:   APIException()  The  base class  for all exceptions raised inside an  APIView  class or  @api_view .  To provide a custom exception, subclass  APIException  and set the  .status_code  and  .default_detail  properties on the class.  For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code.  You could do this like so:  from rest_framework.exceptions import APIException\n\nclass ServiceUnavailable(APIException):\n    status_code = 503\n    default_detail = 'Service temporarily unavailable, try again later.'", 
    +            "text": "Signature:   APIException()  The  base class  for all exceptions raised inside an  APIView  class or  @api_view .  To provide a custom exception, subclass  APIException  and set the  .status_code ,  .default_detail , and  default_code  attributes on the class.  For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code.  You could do this like so:  from rest_framework.exceptions import APIException\n\nclass ServiceUnavailable(APIException):\n    status_code = 503\n    default_detail = 'Service temporarily unavailable, try again later.'\n    default_code = 'service_unavailable'", 
                 "title": "APIException"
             }, 
    +        {
    +            "location": "/api-guide/exceptions/#inspecting-api-exceptions", 
    +            "text": "There are a number of different properties available for inspecting the status\nof an API exception. You can use these to build custom exception handling\nfor your project.  The available attributes and methods are:   .detail  - Return the textual description of the error.  .get_codes()  - Return the code identifier of the error.  .full_details()  - Return both the textual description and the code identifier.   In most cases the error detail will be a simple item:   print(exc.detail)\nYou do not have permission to perform this action.  print(exc.get_codes())\npermission_denied  print(exc.full_details())\n{'message':'You do not have permission to perform this action.','code':'permission_denied'}  In the case of validation errors the error detail will be either a list or\ndictionary of items:   print(exc.detail)\n{\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"}  print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}  print(exc.get_full_details())\n{\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}}", 
    +            "title": "Inspecting API exceptions"
    +        }, 
             {
                 "location": "/api-guide/exceptions/#parseerror", 
    -            "text": "Signature:   ParseError(detail=None)  Raised if the request contains malformed data when accessing  request.data .  By default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
    +            "text": "Signature:   ParseError(detail=None, code=None)  Raised if the request contains malformed data when accessing  request.data .  By default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
                 "title": "ParseError"
             }, 
             {
                 "location": "/api-guide/exceptions/#authenticationfailed", 
    -            "text": "Signature:   AuthenticationFailed(detail=None)  Raised when an incoming request includes incorrect authentication.  By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use.  See the  authentication documentation  for more details.", 
    +            "text": "Signature:   AuthenticationFailed(detail=None, code=None)  Raised when an incoming request includes incorrect authentication.  By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use.  See the  authentication documentation  for more details.", 
                 "title": "AuthenticationFailed"
             }, 
             {
                 "location": "/api-guide/exceptions/#notauthenticated", 
    -            "text": "Signature:   NotAuthenticated(detail=None)  Raised when an unauthenticated request fails the permission checks.  By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use.  See the  authentication documentation  for more details.", 
    +            "text": "Signature:   NotAuthenticated(detail=None, code=None)  Raised when an unauthenticated request fails the permission checks.  By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use.  See the  authentication documentation  for more details.", 
                 "title": "NotAuthenticated"
             }, 
             {
                 "location": "/api-guide/exceptions/#permissiondenied", 
    -            "text": "Signature:   PermissionDenied(detail=None)  Raised when an authenticated request fails the permission checks.  By default this exception results in a response with the HTTP status code \"403 Forbidden\".", 
    +            "text": "Signature:   PermissionDenied(detail=None, code=None)  Raised when an authenticated request fails the permission checks.  By default this exception results in a response with the HTTP status code \"403 Forbidden\".", 
                 "title": "PermissionDenied"
             }, 
             {
                 "location": "/api-guide/exceptions/#notfound", 
    -            "text": "Signature:   NotFound(detail=None)  Raised when a resource does not exists at the given URL. This exception is equivalent to the standard  Http404  Django exception.  By default this exception results in a response with the HTTP status code \"404 Not Found\".", 
    +            "text": "Signature:   NotFound(detail=None, code=None)  Raised when a resource does not exists at the given URL. This exception is equivalent to the standard  Http404  Django exception.  By default this exception results in a response with the HTTP status code \"404 Not Found\".", 
                 "title": "NotFound"
             }, 
             {
                 "location": "/api-guide/exceptions/#methodnotallowed", 
    -            "text": "Signature:   MethodNotAllowed(method, detail=None)  Raised when an incoming request occurs that does not map to a handler method on the view.  By default this exception results in a response with the HTTP status code \"405 Method Not Allowed\".", 
    +            "text": "Signature:   MethodNotAllowed(method, detail=None, code=None)  Raised when an incoming request occurs that does not map to a handler method on the view.  By default this exception results in a response with the HTTP status code \"405 Method Not Allowed\".", 
                 "title": "MethodNotAllowed"
             }, 
             {
                 "location": "/api-guide/exceptions/#notacceptable", 
    -            "text": "Signature:   NotAcceptable(detail=None)  Raised when an incoming request occurs with an  Accept  header that cannot be satisfied by any of the available renderers.  By default this exception results in a response with the HTTP status code \"406 Not Acceptable\".", 
    +            "text": "Signature:   NotAcceptable(detail=None, code=None)  Raised when an incoming request occurs with an  Accept  header that cannot be satisfied by any of the available renderers.  By default this exception results in a response with the HTTP status code \"406 Not Acceptable\".", 
                 "title": "NotAcceptable"
             }, 
             {
                 "location": "/api-guide/exceptions/#unsupportedmediatype", 
    -            "text": "Signature:   UnsupportedMediaType(media_type, detail=None)  Raised if there are no parsers that can handle the content type of the request data when accessing  request.data .  By default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\".", 
    +            "text": "Signature:   UnsupportedMediaType(media_type, detail=None, code=None)  Raised if there are no parsers that can handle the content type of the request data when accessing  request.data .  By default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\".", 
                 "title": "UnsupportedMediaType"
             }, 
             {
                 "location": "/api-guide/exceptions/#throttled", 
    -            "text": "Signature:   Throttled(wait=None, detail=None)  Raised when an incoming request fails the throttling checks.  By default this exception results in a response with the HTTP status code \"429 Too Many Requests\".", 
    +            "text": "Signature:   Throttled(wait=None, detail=None, code=None)  Raised when an incoming request fails the throttling checks.  By default this exception results in a response with the HTTP status code \"429 Too Many Requests\".", 
                 "title": "Throttled"
             }, 
             {
                 "location": "/api-guide/exceptions/#validationerror", 
    -            "text": "Signature:   ValidationError(detail)  The  ValidationError  exception is slightly different from the other  APIException  classes:   The  detail  argument is mandatory, not optional.  The  detail  argument may be a list or dictionary of error details, and may also be a nested data structure.  By convention you should import the serializers module and use a fully qualified  ValidationError  style, in order to differentiate it from Django's built-in validation error. For example.  raise serializers.ValidationError('This field must be an integer value.')   The  ValidationError  class should be used for serializer and field validation, and by validator classes. It is also raised when calling  serializer.is_valid  with the  raise_exception  keyword argument:  serializer.is_valid(raise_exception=True)  The generic views use the  raise_exception=True  flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.  By default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
    +            "text": "Signature:   ValidationError(detail, code=None)  The  ValidationError  exception is slightly different from the other  APIException  classes:   The  detail  argument is mandatory, not optional.  The  detail  argument may be a list or dictionary of error details, and may also be a nested data structure.  By convention you should import the serializers module and use a fully qualified  ValidationError  style, in order to differentiate it from Django's built-in validation error. For example.  raise serializers.ValidationError('This field must be an integer value.')   The  ValidationError  class should be used for serializer and field validation, and by validator classes. It is also raised when calling  serializer.is_valid  with the  raise_exception  keyword argument:  serializer.is_valid(raise_exception=True)  The generic views use the  raise_exception=True  flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.  By default this exception results in a response with the HTTP status code \"400 Bad Request\".", 
                 "title": "ValidationError"
             }, 
             {
    @@ -3327,7 +3362,7 @@
             }, 
             {
                 "location": "/api-guide/testing/", 
    -            "text": "Testing\n\n\n\n\nCode without tests is broken as designed.\n\n\n \nJacob Kaplan-Moss\n\n\n\n\nREST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.\n\n\nAPIRequestFactory\n\n\nExtends \nDjango's existing \nRequestFactory\n class\n.\n\n\nCreating test requests\n\n\nThe \nAPIRequestFactory\n class supports an almost identical API to Django's standard \nRequestFactory\n class.  This means that the standard \n.get()\n, \n.post()\n, \n.put()\n, \n.patch()\n, \n.delete()\n, \n.head()\n and \n.options()\n methods are all available.\n\n\nfrom rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'})\n\n\n\nUsing the \nformat\n argument\n\n\nMethods which create a request body, such as \npost\n, \nput\n and \npatch\n, include a \nformat\n argument, which make it easy to generate requests using a content type other than multipart form data.  For example:\n\n\n# Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json')\n\n\n\nBy default the available formats are \n'multipart'\n and \n'json'\n.  For compatibility with Django's existing \nRequestFactory\n the default format is \n'multipart'\n.\n\n\nTo support a wider set of request formats, or change the default format, \nsee the configuration section\n.\n\n\nExplicitly encoding the request body\n\n\nIf you need to explicitly encode the request body, you can do so by setting the \ncontent_type\n flag.  For example:\n\n\nrequest = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')\n\n\n\nPUT and PATCH with form data\n\n\nOne difference worth noting between Django's \nRequestFactory\n and REST framework's \nAPIRequestFactory\n is that multipart form data will be encoded for methods other than just \n.post()\n.\n\n\nFor example, using \nAPIRequestFactory\n, you can make a form PUT request like so:\n\n\nfactory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'})\n\n\n\nUsing Django's \nRequestFactory\n, you'd need to explicitly encode the data yourself:\n\n\nfrom django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)\n\n\n\nForcing authentication\n\n\nWhen 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.\n\n\nTo forcibly authenticate a request, use the \nforce_authenticate()\n method.\n\n\nfrom rest_framework.test import force_authenticate\n\nfactory = APIRequestFactory()\nuser = User.objects.get(username='olivia')\nview = AccountDetail.as_view()\n\n# Make an authenticated request to the view...\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user)\nresponse = view(request)\n\n\n\nThe signature for the method is \nforce_authenticate(request, user=None, token=None)\n.  When making the call, either or both of the user and token may be set.\n\n\nFor example, when forcibly authenticating using a token, you might do something like the following:\n\n\nuser = User.objects.get(username='olivia')\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user, token=user.token)\n\n\n\n\n\nNote\n: When using \nAPIRequestFactory\n, the object that is returned is Django's standard \nHttpRequest\n, and not REST framework's \nRequest\n object, which is only generated once the view is called.\n\n\nThis means that setting attributes directly on the request object may not always have the effect you expect.  For example, setting \n.token\n directly will have no effect, and setting \n.user\n directly will only work if session authentication is being used.\n\n\n# Request will only authenticate if `SessionAuthentication` is in use.\nrequest = factory.get('/accounts/django-superstars/')\nrequest.user = user\nresponse = view(request)\n\n\n\n\n\nForcing CSRF validation\n\n\nBy default, requests created with \nAPIRequestFactory\n 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 \nenforce_csrf_checks\n flag when instantiating the factory.\n\n\nfactory = APIRequestFactory(enforce_csrf_checks=True)\n\n\n\n\n\nNote\n: It's worth noting that Django's standard \nRequestFactory\n 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.\n\n\n\n\nAPIClient\n\n\nExtends \nDjango's existing \nClient\n class\n.\n\n\nMaking requests\n\n\nThe \nAPIClient\n class supports the same request interface as Django's standard \nClient\n class.  This means the that standard \n.get()\n, \n.post()\n, \n.put()\n, \n.patch()\n, \n.delete()\n, \n.head()\n and \n.options()\n methods are all available.  For example:\n\n\nfrom rest_framework.test import APIClient\n\nclient = APIClient()\nclient.post('/notes/', {'title': 'new idea'}, format='json')\n\n\n\nTo support a wider set of request formats, or change the default format, \nsee the configuration section\n.\n\n\nAuthenticating\n\n\n.login(**kwargs)\n\n\nThe \nlogin\n method functions exactly as it does with Django's regular \nClient\n class.  This allows you to authenticate requests against any views which include \nSessionAuthentication\n.\n\n\n# Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret')\n\n\n\nTo logout, call the \nlogout\n method as usual.\n\n\n# Log out\nclient.logout()\n\n\n\nThe \nlogin\n method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.\n\n\n.credentials(**kwargs)\n\n\nThe \ncredentials\n method can be used to set headers that will then be included on all subsequent requests by the test client.\n\n\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n\n\n\nNote that calling \ncredentials\n a second time overwrites any existing credentials.  You can unset any existing credentials by calling the method with no arguments.\n\n\n# Stop including any credentials\nclient.credentials()\n\n\n\nThe \ncredentials\n method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.\n\n\n.force_authenticate(user=None, token=None)\n\n\nSometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.\n\n\nThis 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.\n\n\nuser = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user)\n\n\n\nTo unauthenticate subsequent requests, call \nforce_authenticate\n setting the user and/or token to \nNone\n.\n\n\nclient.force_authenticate(user=None)\n\n\n\nCSRF validation\n\n\nBy default CSRF validation is not applied when using \nAPIClient\n.  If you need to explicitly enable CSRF validation, you can do so by setting the \nenforce_csrf_checks\n flag when instantiating the client.\n\n\nclient = APIClient(enforce_csrf_checks=True)\n\n\n\nAs 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 \nlogin()\n.\n\n\n\n\nTest cases\n\n\nREST framework includes the following test case classes, that mirror the existing Django test case classes, but use \nAPIClient\n instead of Django's default \nClient\n.\n\n\n\n\nAPISimpleTestCase\n\n\nAPITransactionTestCase\n\n\nAPITestCase\n\n\nAPILiveServerTestCase\n\n\n\n\nExample\n\n\nYou can use any of REST framework's test case classes as you would for the regular Django test case classes.  The \nself.client\n attribute will be an \nAPIClient\n instance.\n\n\nfrom django.core.urlresolvers import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n    def test_create_account(self):\n        \"\"\"\n        Ensure we can create a new account object.\n        \"\"\"\n        url = reverse('account-list')\n        data = {'name': 'DabApps'}\n        response = self.client.post(url, data, format='json')\n        self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n        self.assertEqual(Account.objects.count(), 1)\n        self.assertEqual(Account.objects.get().name, 'DabApps')\n\n\n\n\n\nTesting responses\n\n\nChecking the response data\n\n\nWhen 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.\n\n\nFor example, it's easier to inspect \nresponse.data\n:\n\n\nresponse = self.client.get('/users/4/')\nself.assertEqual(response.data, {'id': 4, 'username': 'lauren'})\n\n\n\nInstead of inspecting the result of parsing \nresponse.content\n:\n\n\nresponse = self.client.get('/users/4/')\nself.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})\n\n\n\nRendering responses\n\n\nIf you're testing views directly using \nAPIRequestFactory\n, 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 \nresponse.content\n, you'll first need to render the response.\n\n\nview = UserDetail.as_view()\nrequest = factory.get('/users/4')\nresponse = view(request, pk='4')\nresponse.render()  # Cannot access `response.content` without this.\nself.assertEqual(response.content, '{\"username\": \"lauren\", \"id\": 4}')\n\n\n\n\n\nConfiguration\n\n\nSetting the default format\n\n\nThe default format used to make test requests may be set using the \nTEST_REQUEST_DEFAULT_FORMAT\n setting key.  For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your \nsettings.py\n file:\n\n\nREST_FRAMEWORK = {\n    ...\n    'TEST_REQUEST_DEFAULT_FORMAT': 'json'\n}\n\n\n\nSetting the available formats\n\n\nIf you need to test requests using something other than multipart or json requests, you can do so by setting the \nTEST_REQUEST_RENDERER_CLASSES\n setting.\n\n\nFor example, to add support for using \nformat='html'\n in test requests, you might have something like this in your \nsettings.py\n file.\n\n\nREST_FRAMEWORK = {\n    ...\n    'TEST_REQUEST_RENDERER_CLASSES': (\n        'rest_framework.renderers.MultiPartRenderer',\n        'rest_framework.renderers.JSONRenderer',\n        'rest_framework.renderers.TemplateHTMLRenderer'\n    )\n}", 
    +            "text": "Testing\n\n\n\n\nCode without tests is broken as designed.\n\n\n \nJacob Kaplan-Moss\n\n\n\n\nREST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.\n\n\nAPIRequestFactory\n\n\nExtends \nDjango's existing \nRequestFactory\n class\n.\n\n\nCreating test requests\n\n\nThe \nAPIRequestFactory\n class supports an almost identical API to Django's standard \nRequestFactory\n class.  This means that the standard \n.get()\n, \n.post()\n, \n.put()\n, \n.patch()\n, \n.delete()\n, \n.head()\n and \n.options()\n methods are all available.\n\n\nfrom rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'})\n\n\n\nUsing the \nformat\n argument\n\n\nMethods which create a request body, such as \npost\n, \nput\n and \npatch\n, include a \nformat\n argument, which make it easy to generate requests using a content type other than multipart form data.  For example:\n\n\n# Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json')\n\n\n\nBy default the available formats are \n'multipart'\n and \n'json'\n.  For compatibility with Django's existing \nRequestFactory\n the default format is \n'multipart'\n.\n\n\nTo support a wider set of request formats, or change the default format, \nsee the configuration section\n.\n\n\nExplicitly encoding the request body\n\n\nIf you need to explicitly encode the request body, you can do so by setting the \ncontent_type\n flag.  For example:\n\n\nrequest = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')\n\n\n\nPUT and PATCH with form data\n\n\nOne difference worth noting between Django's \nRequestFactory\n and REST framework's \nAPIRequestFactory\n is that multipart form data will be encoded for methods other than just \n.post()\n.\n\n\nFor example, using \nAPIRequestFactory\n, you can make a form PUT request like so:\n\n\nfactory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'})\n\n\n\nUsing Django's \nRequestFactory\n, you'd need to explicitly encode the data yourself:\n\n\nfrom django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)\n\n\n\nForcing authentication\n\n\nWhen 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.\n\n\nTo forcibly authenticate a request, use the \nforce_authenticate()\n method.\n\n\nfrom rest_framework.test import force_authenticate\n\nfactory = APIRequestFactory()\nuser = User.objects.get(username='olivia')\nview = AccountDetail.as_view()\n\n# Make an authenticated request to the view...\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user)\nresponse = view(request)\n\n\n\nThe signature for the method is \nforce_authenticate(request, user=None, token=None)\n.  When making the call, either or both of the user and token may be set.\n\n\nFor example, when forcibly authenticating using a token, you might do something like the following:\n\n\nuser = User.objects.get(username='olivia')\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user, token=user.token)\n\n\n\n\n\nNote\n: When using \nAPIRequestFactory\n, the object that is returned is Django's standard \nHttpRequest\n, and not REST framework's \nRequest\n object, which is only generated once the view is called.\n\n\nThis means that setting attributes directly on the request object may not always have the effect you expect.  For example, setting \n.token\n directly will have no effect, and setting \n.user\n directly will only work if session authentication is being used.\n\n\n# Request will only authenticate if `SessionAuthentication` is in use.\nrequest = factory.get('/accounts/django-superstars/')\nrequest.user = user\nresponse = view(request)\n\n\n\n\n\nForcing CSRF validation\n\n\nBy default, requests created with \nAPIRequestFactory\n 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 \nenforce_csrf_checks\n flag when instantiating the factory.\n\n\nfactory = APIRequestFactory(enforce_csrf_checks=True)\n\n\n\n\n\nNote\n: It's worth noting that Django's standard \nRequestFactory\n 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.\n\n\n\n\nAPIClient\n\n\nExtends \nDjango's existing \nClient\n class\n.\n\n\nMaking requests\n\n\nThe \nAPIClient\n class supports the same request interface as Django's standard \nClient\n class.  This means the that standard \n.get()\n, \n.post()\n, \n.put()\n, \n.patch()\n, \n.delete()\n, \n.head()\n and \n.options()\n methods are all available.  For example:\n\n\nfrom rest_framework.test import APIClient\n\nclient = APIClient()\nclient.post('/notes/', {'title': 'new idea'}, format='json')\n\n\n\nTo support a wider set of request formats, or change the default format, \nsee the configuration section\n.\n\n\nAuthenticating\n\n\n.login(**kwargs)\n\n\nThe \nlogin\n method functions exactly as it does with Django's regular \nClient\n class.  This allows you to authenticate requests against any views which include \nSessionAuthentication\n.\n\n\n# Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret')\n\n\n\nTo logout, call the \nlogout\n method as usual.\n\n\n# Log out\nclient.logout()\n\n\n\nThe \nlogin\n method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.\n\n\n.credentials(**kwargs)\n\n\nThe \ncredentials\n method can be used to set headers that will then be included on all subsequent requests by the test client.\n\n\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n\n\n\nNote that calling \ncredentials\n a second time overwrites any existing credentials.  You can unset any existing credentials by calling the method with no arguments.\n\n\n# Stop including any credentials\nclient.credentials()\n\n\n\nThe \ncredentials\n method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.\n\n\n.force_authenticate(user=None, token=None)\n\n\nSometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.\n\n\nThis 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.\n\n\nuser = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user)\n\n\n\nTo unauthenticate subsequent requests, call \nforce_authenticate\n setting the user and/or token to \nNone\n.\n\n\nclient.force_authenticate(user=None)\n\n\n\nCSRF validation\n\n\nBy default CSRF validation is not applied when using \nAPIClient\n.  If you need to explicitly enable CSRF validation, you can do so by setting the \nenforce_csrf_checks\n flag when instantiating the client.\n\n\nclient = APIClient(enforce_csrf_checks=True)\n\n\n\nAs 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 \nlogin()\n.\n\n\n\n\nRequestsClient\n\n\nREST framework also includes a client for interacting with your application\nusing the popular Python library, \nrequests\n.\n\n\nThis exposes exactly the same interface as if you were using a requests session\ndirectly.\n\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\n\n\n\nNote that the requests client requires you to pass fully qualified URLs.\n\n\nHeaders \n Authentication\n\n\nCustom headers and authentication credentials can be provided in the same way\nas \nwhen using a standard \nrequests.Session\n instance\n.\n\n\nfrom requests.auth import HTTPBasicAuth\n\nclient.auth = HTTPBasicAuth('user', 'pass')\nclient.headers.update({'x-test': 'true'})\n\n\n\nCSRF\n\n\nIf you're using \nSessionAuthentication\n then you'll need to include a CSRF token\nfor any \nPOST\n, \nPUT\n, \nPATCH\n or \nDELETE\n requests.\n\n\nYou can do so by following the same flow that a JavaScript based client would use.\nFirst make a \nGET\n request in order to obtain a CRSF token, then present that\ntoken in the following request.\n\n\nFor example...\n\n\nclient = RequestsClient()\n\n# Obtain a CSRF token.\nresponse = client.get('/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('/organisations/', json={\n    'name': 'MegaCorp',\n    'status': 'active'\n}, headers={'X-CSRFToken': csrftoken})\nassert response.status_code == 200\n\n\n\nLive tests\n\n\nWith careful usage both the \nRequestsClient\n and the \nCoreAPIClient\n provide\nthe ability to write test cases that can run either in development, or be run\ndirectly against your staging server or production environment.\n\n\nUsing this style to create basic tests of a few core piece of functionality is\na powerful way to validate your live service. Doing so may require some careful\nattention to setup and teardown to ensure that the tests run in a way that they\ndo not directly affect customer data.\n\n\n\n\nCoreAPIClient\n\n\nThe CoreAPIClient allows you to interact with your API using the Python\n\ncoreapi\n client library.\n\n\n# Fetch the API schema\nurl = reverse('schema')\nclient = CoreAPIClient()\nschema = client.get(url)\n\n# Create a new organisation\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organisations', 'create'], params)\n\n# Ensure that the organisation exists in the listing\ndata = client.action(schema, ['organisations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])\n\n\n\nHeaders \n Authentication\n\n\nCustom headers and authentication may be used with \nCoreAPIClient\n in a\nsimilar way as with \nRequestsClient\n.\n\n\nfrom requests.auth import HTTPBasicAuth\n\nclient = CoreAPIClient()\nclient.session.auth = HTTPBasicAuth('user', 'pass')\nclient.session.headers.update({'x-test': 'true'})\n\n\n\n\n\nTest cases\n\n\nREST framework includes the following test case classes, that mirror the existing Django test case classes, but use \nAPIClient\n instead of Django's default \nClient\n.\n\n\n\n\nAPISimpleTestCase\n\n\nAPITransactionTestCase\n\n\nAPITestCase\n\n\nAPILiveServerTestCase\n\n\n\n\nExample\n\n\nYou can use any of REST framework's test case classes as you would for the regular Django test case classes.  The \nself.client\n attribute will be an \nAPIClient\n instance.\n\n\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n    def test_create_account(self):\n        \"\"\"\n        Ensure we can create a new account object.\n        \"\"\"\n        url = reverse('account-list')\n        data = {'name': 'DabApps'}\n        response = self.client.post(url, data, format='json')\n        self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n        self.assertEqual(Account.objects.count(), 1)\n        self.assertEqual(Account.objects.get().name, 'DabApps')\n\n\n\n\n\nTesting responses\n\n\nChecking the response data\n\n\nWhen 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.\n\n\nFor example, it's easier to inspect \nresponse.data\n:\n\n\nresponse = self.client.get('/users/4/')\nself.assertEqual(response.data, {'id': 4, 'username': 'lauren'})\n\n\n\nInstead of inspecting the result of parsing \nresponse.content\n:\n\n\nresponse = self.client.get('/users/4/')\nself.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})\n\n\n\nRendering responses\n\n\nIf you're testing views directly using \nAPIRequestFactory\n, 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 \nresponse.content\n, you'll first need to render the response.\n\n\nview = UserDetail.as_view()\nrequest = factory.get('/users/4')\nresponse = view(request, pk='4')\nresponse.render()  # Cannot access `response.content` without this.\nself.assertEqual(response.content, '{\"username\": \"lauren\", \"id\": 4}')\n\n\n\n\n\nConfiguration\n\n\nSetting the default format\n\n\nThe default format used to make test requests may be set using the \nTEST_REQUEST_DEFAULT_FORMAT\n setting key.  For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your \nsettings.py\n file:\n\n\nREST_FRAMEWORK = {\n    ...\n    'TEST_REQUEST_DEFAULT_FORMAT': 'json'\n}\n\n\n\nSetting the available formats\n\n\nIf you need to test requests using something other than multipart or json requests, you can do so by setting the \nTEST_REQUEST_RENDERER_CLASSES\n setting.\n\n\nFor example, to add support for using \nformat='html'\n in test requests, you might have something like this in your \nsettings.py\n file.\n\n\nREST_FRAMEWORK = {\n    ...\n    'TEST_REQUEST_RENDERER_CLASSES': (\n        'rest_framework.renderers.MultiPartRenderer',\n        'rest_framework.renderers.JSONRenderer',\n        'rest_framework.renderers.TemplateHTMLRenderer'\n    )\n}", 
                 "title": "Testing"
             }, 
             {
    @@ -3405,6 +3440,36 @@
                 "text": "By default CSRF validation is not applied when using  APIClient .  If you need to explicitly enable CSRF validation, you can do so by setting the  enforce_csrf_checks  flag when instantiating the client.  client = APIClient(enforce_csrf_checks=True)  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  login() .", 
                 "title": "CSRF validation"
             }, 
    +        {
    +            "location": "/api-guide/testing/#requestsclient", 
    +            "text": "REST framework also includes a client for interacting with your application\nusing the popular Python library,  requests .  This exposes exactly the same interface as if you were using a requests session\ndirectly.  client = RequestsClient()\nresponse = client.get('http://testserver/users/')  Note that the requests client requires you to pass fully qualified URLs.", 
    +            "title": "RequestsClient"
    +        }, 
    +        {
    +            "location": "/api-guide/testing/#headers-authentication", 
    +            "text": "Custom headers and authentication credentials can be provided in the same way\nas  when using a standard  requests.Session  instance .  from requests.auth import HTTPBasicAuth\n\nclient.auth = HTTPBasicAuth('user', 'pass')\nclient.headers.update({'x-test': 'true'})", 
    +            "title": "Headers & Authentication"
    +        }, 
    +        {
    +            "location": "/api-guide/testing/#csrf", 
    +            "text": "If you're using  SessionAuthentication  then you'll need to include a CSRF token\nfor any  POST ,  PUT ,  PATCH  or  DELETE  requests.  You can do so by following the same flow that a JavaScript based client would use.\nFirst make a  GET  request in order to obtain a CRSF token, then present that\ntoken in the following request.  For example...  client = RequestsClient()\n\n# Obtain a CSRF token.\nresponse = client.get('/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('/organisations/', json={\n    'name': 'MegaCorp',\n    'status': 'active'\n}, headers={'X-CSRFToken': csrftoken})\nassert response.status_code == 200", 
    +            "title": "CSRF"
    +        }, 
    +        {
    +            "location": "/api-guide/testing/#live-tests", 
    +            "text": "With careful usage both the  RequestsClient  and the  CoreAPIClient  provide\nthe ability to write test cases that can run either in development, or be run\ndirectly against your staging server or production environment.  Using this style to create basic tests of a few core piece of functionality is\na powerful way to validate your live service. Doing so may require some careful\nattention to setup and teardown to ensure that the tests run in a way that they\ndo not directly affect customer data.", 
    +            "title": "Live tests"
    +        }, 
    +        {
    +            "location": "/api-guide/testing/#coreapiclient", 
    +            "text": "The CoreAPIClient allows you to interact with your API using the Python coreapi  client library.  # Fetch the API schema\nurl = reverse('schema')\nclient = CoreAPIClient()\nschema = client.get(url)\n\n# Create a new organisation\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organisations', 'create'], params)\n\n# Ensure that the organisation exists in the listing\ndata = client.action(schema, ['organisations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])", 
    +            "title": "CoreAPIClient"
    +        }, 
    +        {
    +            "location": "/api-guide/testing/#headers-authentication_1", 
    +            "text": "Custom headers and authentication may be used with  CoreAPIClient  in a\nsimilar way as with  RequestsClient .  from requests.auth import HTTPBasicAuth\n\nclient = CoreAPIClient()\nclient.session.auth = HTTPBasicAuth('user', 'pass')\nclient.session.headers.update({'x-test': 'true'})", 
    +            "title": "Headers & Authentication"
    +        }, 
             {
                 "location": "/api-guide/testing/#test-cases", 
                 "text": "REST framework includes the following test case classes, that mirror the existing Django test case classes, but use  APIClient  instead of Django's default  Client .   APISimpleTestCase  APITransactionTestCase  APITestCase  APILiveServerTestCase", 
    @@ -3412,7 +3477,7 @@
             }, 
             {
                 "location": "/api-guide/testing/#example", 
    -            "text": "You can use any of REST framework's test case classes as you would for the regular Django test case classes.  The  self.client  attribute will be an  APIClient  instance.  from django.core.urlresolvers import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n    def test_create_account(self):\n        \"\"\"\n        Ensure we can create a new account object.\n        \"\"\"\n        url = reverse('account-list')\n        data = {'name': 'DabApps'}\n        response = self.client.post(url, data, format='json')\n        self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n        self.assertEqual(Account.objects.count(), 1)\n        self.assertEqual(Account.objects.get().name, 'DabApps')", 
    +            "text": "You can use any of REST framework's test case classes as you would for the regular Django test case classes.  The  self.client  attribute will be an  APIClient  instance.  from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n    def test_create_account(self):\n        \"\"\"\n        Ensure we can create a new account object.\n        \"\"\"\n        url = reverse('account-list')\n        data = {'name': 'DabApps'}\n        response = self.client.post(url, data, format='json')\n        self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n        self.assertEqual(Account.objects.count(), 1)\n        self.assertEqual(Account.objects.get().name, 'DabApps')", 
                 "title": "Example"
             }, 
             {
    @@ -3447,7 +3512,7 @@
             }, 
             {
                 "location": "/api-guide/settings/", 
    -            "text": "Settings\n\n\n\n\nNamespaces are one honking great idea - let's do more of those!\n\n\n \nThe Zen of Python\n\n\n\n\nConfiguration for REST framework is all namespaced inside a single Django setting, named \nREST_FRAMEWORK\n.\n\n\nFor example your project's \nsettings.py\n file might include something like this:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_RENDERER_CLASSES': (\n        'rest_framework.renderers.JSONRenderer',\n    ),\n    'DEFAULT_PARSER_CLASSES': (\n        'rest_framework.parsers.JSONParser',\n    )\n}\n\n\n\nAccessing settings\n\n\nIf you need to access the values of REST framework's API settings in your project,\nyou should use the \napi_settings\n object.  For example.\n\n\nfrom rest_framework.settings import api_settings\n\nprint api_settings.DEFAULT_AUTHENTICATION_CLASSES\n\n\n\nThe \napi_settings\n 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.\n\n\n\n\nAPI Reference\n\n\nAPI policy settings\n\n\nThe following settings control the basic API policies, and are applied to every \nAPIView\n class-based view, or \n@api_view\n function based view.\n\n\nDEFAULT_RENDERER_CLASSES\n\n\nA list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a \nResponse\n object.\n\n\nDefault:\n\n\n(\n    'rest_framework.renderers.JSONRenderer',\n    'rest_framework.renderers.BrowsableAPIRenderer',\n)\n\n\n\nDEFAULT_PARSER_CLASSES\n\n\nA list or tuple of parser classes, that determines the default set of parsers used when accessing the \nrequest.data\n property.\n\n\nDefault:\n\n\n(\n    'rest_framework.parsers.JSONParser',\n    'rest_framework.parsers.FormParser',\n    'rest_framework.parsers.MultiPartParser'\n)\n\n\n\nDEFAULT_AUTHENTICATION_CLASSES\n\n\nA list or tuple of authentication classes, that determines the default set of authenticators used when accessing the \nrequest.user\n or \nrequest.auth\n properties.\n\n\nDefault:\n\n\n(\n    'rest_framework.authentication.SessionAuthentication',\n    'rest_framework.authentication.BasicAuthentication'\n)\n\n\n\nDEFAULT_PERMISSION_CLASSES\n\n\nA 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.\n\n\nDefault:\n\n\n(\n    'rest_framework.permissions.AllowAny',\n)\n\n\n\nDEFAULT_THROTTLE_CLASSES\n\n\nA list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.\n\n\nDefault: \n()\n\n\nDEFAULT_CONTENT_NEGOTIATION_CLASS\n\n\nA content negotiation class, that determines how a renderer is selected for the response, given an incoming request.\n\n\nDefault: \n'rest_framework.negotiation.DefaultContentNegotiation'\n\n\n\n\nGeneric view settings\n\n\nThe following settings control the behavior of the generic class-based views.\n\n\nDEFAULT_PAGINATION_SERIALIZER_CLASS\n\n\n\n\nThis setting has been removed.\n\n\nThe pagination API does not use serializers to determine the output format, and\nyou'll need to instead override the `get_paginated_response method on a\npagination class in order to specify how the output format is controlled.\n\n\n\n\nDEFAULT_FILTER_BACKENDS\n\n\nA list of filter backend classes that should be used for generic filtering.\nIf set to \nNone\n then generic filtering is disabled.\n\n\nPAGINATE_BY\n\n\n\n\nThis setting has been removed.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nPAGE_SIZE\n\n\nThe default page size to use for pagination.  If set to \nNone\n, pagination is disabled by default.\n\n\nDefault: \nNone\n\n\nPAGINATE_BY_PARAM\n\n\n\n\nThis setting has been removed.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nMAX_PAGINATE_BY\n\n\n\n\nThis setting is pending deprecation.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nSEARCH_PARAM\n\n\nThe name of a query parameter, which can be used to specify the search term used by \nSearchFilter\n.\n\n\nDefault: \nsearch\n\n\nORDERING_PARAM\n\n\nThe name of a query parameter, which can be used to specify the ordering of results returned by \nOrderingFilter\n.\n\n\nDefault: \nordering\n\n\n\n\nVersioning settings\n\n\nDEFAULT_VERSION\n\n\nThe value that should be used for \nrequest.version\n when no versioning information is present.\n\n\nDefault: \nNone\n\n\nALLOWED_VERSIONS\n\n\nIf 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.\n\n\nDefault: \nNone\n\n\nVERSION_PARAM\n\n\nThe string that should used for any versioning parameters, such as in the media type or URL query parameters.\n\n\nDefault: \n'version'\n\n\n\n\nAuthentication settings\n\n\nThe following settings control the behavior of unauthenticated requests.\n\n\nUNAUTHENTICATED_USER\n\n\nThe class that should be used to initialize \nrequest.user\n for unauthenticated requests.\n\n\nDefault: \ndjango.contrib.auth.models.AnonymousUser\n\n\nUNAUTHENTICATED_TOKEN\n\n\nThe class that should be used to initialize \nrequest.auth\n for unauthenticated requests.\n\n\nDefault: \nNone\n\n\n\n\nTest settings\n\n\nThe following settings control the behavior of APIRequestFactory and APIClient\n\n\nTEST_REQUEST_DEFAULT_FORMAT\n\n\nThe default format that should be used when making test requests.\n\n\nThis should match up with the format of one of the renderer classes in the \nTEST_REQUEST_RENDERER_CLASSES\n setting.\n\n\nDefault: \n'multipart'\n\n\nTEST_REQUEST_RENDERER_CLASSES\n\n\nThe renderer classes that are supported when building test requests.\n\n\nThe format of any of these renderer classes may be used when constructing a test request, for example: \nclient.post('/users', {'username': 'jamie'}, format='json')\n\n\nDefault:\n\n\n(\n    'rest_framework.renderers.MultiPartRenderer',\n    'rest_framework.renderers.JSONRenderer'\n)\n\n\n\n\n\nContent type controls\n\n\nURL_FORMAT_OVERRIDE\n\n\nThe name of a URL parameter that may be used to override the default content negotiation \nAccept\n header behavior, by using a \nformat=\u2026\n query parameter in the request URL.\n\n\nFor example: \nhttp://example.com/organizations/?format=csv\n\n\nIf the value of this setting is \nNone\n then URL format overrides will be disabled.\n\n\nDefault: \n'format'\n\n\nFORMAT_SUFFIX_KWARG\n\n\nThe name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using \nformat_suffix_patterns\n to include suffixed URL patterns.\n\n\nFor example: \nhttp://example.com/organizations.csv/\n\n\nDefault: \n'format'\n\n\n\n\nDate and time formatting\n\n\nThe following settings are used to control how date and time representations may be parsed and rendered.\n\n\nDATETIME_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nDateTimeField\n serializer fields.  If \nNone\n, then \nDateTimeField\n serializer fields will return Python \ndatetime\n objects, and the datetime encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nDATETIME_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nDateTimeField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\nDATE_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nDateField\n serializer fields.  If \nNone\n, then \nDateField\n serializer fields will return Python \ndate\n objects, and the date encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nDATE_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nDateField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\nTIME_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nTimeField\n serializer fields.  If \nNone\n, then \nTimeField\n serializer fields will return Python \ntime\n objects, and the time encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nTIME_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nTimeField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\n\n\nEncodings\n\n\nUNICODE_JSON\n\n\nWhen set to \nTrue\n, JSON responses will allow unicode characters in responses. For example:\n\n\n{\"unicode black star\":\"\u2605\"}\n\n\n\nWhen set to \nFalse\n, JSON responses will escape non-ascii characters, like so:\n\n\n{\"unicode black star\":\"\\u2605\"}\n\n\n\nBoth styles conform to \nRFC 4627\n, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.\n\n\nDefault: \nTrue\n\n\nCOMPACT_JSON\n\n\nWhen set to \nTrue\n, JSON responses will return compact representations, with no spacing after \n':'\n and \n','\n characters. For example:\n\n\n{\"is_admin\":false,\"email\":\"jane@example\"}\n\n\n\nWhen set to \nFalse\n, JSON responses will return slightly more verbose representations, like so:\n\n\n{\"is_admin\": false, \"email\": \"jane@example\"}\n\n\n\nThe default style is to return minified responses, in line with \nHeroku's API design guidelines\n.\n\n\nDefault: \nTrue\n\n\nCOERCE_DECIMAL_TO_STRING\n\n\nWhen 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.\n\n\nWhen set to \nTrue\n, the serializer \nDecimalField\n class will return strings instead of \nDecimal\n objects. When set to \nFalse\n, serializers will return \nDecimal\n objects, which the default JSON encoder will return as floats.\n\n\nDefault: \nTrue\n\n\n\n\nView names and descriptions\n\n\nThe following settings are used to generate the view names and descriptions, as used in responses to \nOPTIONS\n requests, and as used in the browsable API.\n\n\nVIEW_NAME_FUNCTION\n\n\nA string representing the function that should be used when generating view names.\n\n\nThis should be a function with the following signature:\n\n\nview_name(cls, suffix=None)\n\n\n\n\n\ncls\n: The view class.  Typically the name function would inspect the name of the class when generating a descriptive name, by accessing \ncls.__name__\n.\n\n\nsuffix\n: The optional suffix used when differentiating individual views in a viewset.\n\n\n\n\nDefault: \n'rest_framework.views.get_view_name'\n\n\nVIEW_DESCRIPTION_FUNCTION\n\n\nA string representing the function that should be used when generating view descriptions.\n\n\nThis setting can be changed to support markup styles other than the default markdown.  For example, you can use it to support \nrst\n markup in your view docstrings being output in the browsable API.\n\n\nThis should be a function with the following signature:\n\n\nview_description(cls, html=False)\n\n\n\n\n\ncls\n: The view class.  Typically the description function would inspect the docstring of the class when generating a description, by accessing \ncls.__doc__\n\n\nhtml\n: A boolean indicating if HTML output is required.  \nTrue\n when used in the browsable API, and \nFalse\n when used in generating \nOPTIONS\n responses.\n\n\n\n\nDefault: \n'rest_framework.views.get_view_description'\n\n\n\n\nMiscellaneous settings\n\n\nEXCEPTION_HANDLER\n\n\nA string representing the function that should be used when returning a response for any given exception.  If the function returns \nNone\n, a 500 error will be raised.\n\n\nThis setting can be changed to support error responses other than the default \n{\"detail\": \"Failure...\"}\n responses.  For example, you can use it to provide API responses like \n{\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]}\n.\n\n\nThis should be a function with the following signature:\n\n\nexception_handler(exc, context)\n\n\n\n\n\nexc\n: The exception.\n\n\n\n\nDefault: \n'rest_framework.views.exception_handler'\n\n\nNON_FIELD_ERRORS_KEY\n\n\nA string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.\n\n\nDefault: \n'non_field_errors'\n\n\nURL_FIELD_NAME\n\n\nA string representing the key that should be used for the URL fields generated by \nHyperlinkedModelSerializer\n.\n\n\nDefault: \n'url'\n\n\nNUM_PROXIES\n\n\nAn 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 \nNone\n then less strict IP matching will be used by the throttle classes.\n\n\nDefault: \nNone", 
    +            "text": "Settings\n\n\n\n\nNamespaces are one honking great idea - let's do more of those!\n\n\n \nThe Zen of Python\n\n\n\n\nConfiguration for REST framework is all namespaced inside a single Django setting, named \nREST_FRAMEWORK\n.\n\n\nFor example your project's \nsettings.py\n file might include something like this:\n\n\nREST_FRAMEWORK = {\n    'DEFAULT_RENDERER_CLASSES': (\n        'rest_framework.renderers.JSONRenderer',\n    ),\n    'DEFAULT_PARSER_CLASSES': (\n        'rest_framework.parsers.JSONParser',\n    )\n}\n\n\n\nAccessing settings\n\n\nIf you need to access the values of REST framework's API settings in your project,\nyou should use the \napi_settings\n object.  For example.\n\n\nfrom rest_framework.settings import api_settings\n\nprint api_settings.DEFAULT_AUTHENTICATION_CLASSES\n\n\n\nThe \napi_settings\n 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.\n\n\n\n\nAPI Reference\n\n\nAPI policy settings\n\n\nThe following settings control the basic API policies, and are applied to every \nAPIView\n class-based view, or \n@api_view\n function based view.\n\n\nDEFAULT_RENDERER_CLASSES\n\n\nA list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a \nResponse\n object.\n\n\nDefault:\n\n\n(\n    'rest_framework.renderers.JSONRenderer',\n    'rest_framework.renderers.BrowsableAPIRenderer',\n)\n\n\n\nDEFAULT_PARSER_CLASSES\n\n\nA list or tuple of parser classes, that determines the default set of parsers used when accessing the \nrequest.data\n property.\n\n\nDefault:\n\n\n(\n    'rest_framework.parsers.JSONParser',\n    'rest_framework.parsers.FormParser',\n    'rest_framework.parsers.MultiPartParser'\n)\n\n\n\nDEFAULT_AUTHENTICATION_CLASSES\n\n\nA list or tuple of authentication classes, that determines the default set of authenticators used when accessing the \nrequest.user\n or \nrequest.auth\n properties.\n\n\nDefault:\n\n\n(\n    'rest_framework.authentication.SessionAuthentication',\n    'rest_framework.authentication.BasicAuthentication'\n)\n\n\n\nDEFAULT_PERMISSION_CLASSES\n\n\nA 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.\n\n\nDefault:\n\n\n(\n    'rest_framework.permissions.AllowAny',\n)\n\n\n\nDEFAULT_THROTTLE_CLASSES\n\n\nA list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.\n\n\nDefault: \n()\n\n\nDEFAULT_CONTENT_NEGOTIATION_CLASS\n\n\nA content negotiation class, that determines how a renderer is selected for the response, given an incoming request.\n\n\nDefault: \n'rest_framework.negotiation.DefaultContentNegotiation'\n\n\n\n\nGeneric view settings\n\n\nThe following settings control the behavior of the generic class-based views.\n\n\nDEFAULT_PAGINATION_SERIALIZER_CLASS\n\n\n\n\nThis setting has been removed.\n\n\nThe pagination API does not use serializers to determine the output format, and\nyou'll need to instead override the `get_paginated_response method on a\npagination class in order to specify how the output format is controlled.\n\n\n\n\nDEFAULT_FILTER_BACKENDS\n\n\nA list of filter backend classes that should be used for generic filtering.\nIf set to \nNone\n then generic filtering is disabled.\n\n\nPAGINATE_BY\n\n\n\n\nThis setting has been removed.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nPAGE_SIZE\n\n\nThe default page size to use for pagination.  If set to \nNone\n, pagination is disabled by default.\n\n\nDefault: \nNone\n\n\nPAGINATE_BY_PARAM\n\n\n\n\nThis setting has been removed.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nMAX_PAGINATE_BY\n\n\n\n\nThis setting is pending deprecation.\n\n\nSee the pagination documentation for further guidance on \nsetting the pagination style\n.\n\n\n\n\nSEARCH_PARAM\n\n\nThe name of a query parameter, which can be used to specify the search term used by \nSearchFilter\n.\n\n\nDefault: \nsearch\n\n\nORDERING_PARAM\n\n\nThe name of a query parameter, which can be used to specify the ordering of results returned by \nOrderingFilter\n.\n\n\nDefault: \nordering\n\n\n\n\nVersioning settings\n\n\nDEFAULT_VERSION\n\n\nThe value that should be used for \nrequest.version\n when no versioning information is present.\n\n\nDefault: \nNone\n\n\nALLOWED_VERSIONS\n\n\nIf 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.\n\n\nDefault: \nNone\n\n\nVERSION_PARAM\n\n\nThe string that should used for any versioning parameters, such as in the media type or URL query parameters.\n\n\nDefault: \n'version'\n\n\n\n\nAuthentication settings\n\n\nThe following settings control the behavior of unauthenticated requests.\n\n\nUNAUTHENTICATED_USER\n\n\nThe class that should be used to initialize \nrequest.user\n for unauthenticated requests.\n\n\nDefault: \ndjango.contrib.auth.models.AnonymousUser\n\n\nUNAUTHENTICATED_TOKEN\n\n\nThe class that should be used to initialize \nrequest.auth\n for unauthenticated requests.\n\n\nDefault: \nNone\n\n\n\n\nTest settings\n\n\nThe following settings control the behavior of APIRequestFactory and APIClient\n\n\nTEST_REQUEST_DEFAULT_FORMAT\n\n\nThe default format that should be used when making test requests.\n\n\nThis should match up with the format of one of the renderer classes in the \nTEST_REQUEST_RENDERER_CLASSES\n setting.\n\n\nDefault: \n'multipart'\n\n\nTEST_REQUEST_RENDERER_CLASSES\n\n\nThe renderer classes that are supported when building test requests.\n\n\nThe format of any of these renderer classes may be used when constructing a test request, for example: \nclient.post('/users', {'username': 'jamie'}, format='json')\n\n\nDefault:\n\n\n(\n    'rest_framework.renderers.MultiPartRenderer',\n    'rest_framework.renderers.JSONRenderer'\n)\n\n\n\n\n\nSchema generation controls\n\n\nSCHEMA_COERCE_PATH_PK\n\n\nIf set, this maps the \n'pk'\n identifier in the URL conf onto the actual field\nname when generating a schema path parameter. Typically this will be \n'id'\n.\nThis gives a more suitable representation as \"primary key\" is an implementation\ndetail, wheras \"identifier\" is a more general concept.\n\n\nDefault: \nTrue\n\n\nSCHEMA_COERCE_METHOD_NAMES\n\n\nIf set, this is used to map internal viewset method names onto external action\nnames used in the schema generation. This allows us to generate names that\nare more suitable for an external representation than those that are used\ninternally in the codebase.\n\n\nDefault: \n{'retrieve': 'read', 'destroy': 'delete'}\n\n\n\n\nContent type controls\n\n\nURL_FORMAT_OVERRIDE\n\n\nThe name of a URL parameter that may be used to override the default content negotiation \nAccept\n header behavior, by using a \nformat=\u2026\n query parameter in the request URL.\n\n\nFor example: \nhttp://example.com/organizations/?format=csv\n\n\nIf the value of this setting is \nNone\n then URL format overrides will be disabled.\n\n\nDefault: \n'format'\n\n\nFORMAT_SUFFIX_KWARG\n\n\nThe name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using \nformat_suffix_patterns\n to include suffixed URL patterns.\n\n\nFor example: \nhttp://example.com/organizations.csv/\n\n\nDefault: \n'format'\n\n\n\n\nDate and time formatting\n\n\nThe following settings are used to control how date and time representations may be parsed and rendered.\n\n\nDATETIME_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nDateTimeField\n serializer fields.  If \nNone\n, then \nDateTimeField\n serializer fields will return Python \ndatetime\n objects, and the datetime encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nDATETIME_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nDateTimeField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\nDATE_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nDateField\n serializer fields.  If \nNone\n, then \nDateField\n serializer fields will return Python \ndate\n objects, and the date encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nDATE_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nDateField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\nTIME_FORMAT\n\n\nA format string that should be used by default for rendering the output of \nTimeField\n serializer fields.  If \nNone\n, then \nTimeField\n serializer fields will return Python \ntime\n objects, and the time encoding will be determined by the renderer.\n\n\nMay be any of \nNone\n, \n'iso-8601'\n or a Python \nstrftime format\n string.\n\n\nDefault: \n'iso-8601'\n\n\nTIME_INPUT_FORMATS\n\n\nA list of format strings that should be used by default for parsing inputs to \nTimeField\n serializer fields.\n\n\nMay be a list including the string \n'iso-8601'\n or Python \nstrftime format\n strings.\n\n\nDefault: \n['iso-8601']\n\n\n\n\nEncodings\n\n\nUNICODE_JSON\n\n\nWhen set to \nTrue\n, JSON responses will allow unicode characters in responses. For example:\n\n\n{\"unicode black star\":\"\u2605\"}\n\n\n\nWhen set to \nFalse\n, JSON responses will escape non-ascii characters, like so:\n\n\n{\"unicode black star\":\"\\u2605\"}\n\n\n\nBoth styles conform to \nRFC 4627\n, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.\n\n\nDefault: \nTrue\n\n\nCOMPACT_JSON\n\n\nWhen set to \nTrue\n, JSON responses will return compact representations, with no spacing after \n':'\n and \n','\n characters. For example:\n\n\n{\"is_admin\":false,\"email\":\"jane@example\"}\n\n\n\nWhen set to \nFalse\n, JSON responses will return slightly more verbose representations, like so:\n\n\n{\"is_admin\": false, \"email\": \"jane@example\"}\n\n\n\nThe default style is to return minified responses, in line with \nHeroku's API design guidelines\n.\n\n\nDefault: \nTrue\n\n\nCOERCE_DECIMAL_TO_STRING\n\n\nWhen 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.\n\n\nWhen set to \nTrue\n, the serializer \nDecimalField\n class will return strings instead of \nDecimal\n objects. When set to \nFalse\n, serializers will return \nDecimal\n objects, which the default JSON encoder will return as floats.\n\n\nDefault: \nTrue\n\n\n\n\nView names and descriptions\n\n\nThe following settings are used to generate the view names and descriptions, as used in responses to \nOPTIONS\n requests, and as used in the browsable API.\n\n\nVIEW_NAME_FUNCTION\n\n\nA string representing the function that should be used when generating view names.\n\n\nThis should be a function with the following signature:\n\n\nview_name(cls, suffix=None)\n\n\n\n\n\ncls\n: The view class.  Typically the name function would inspect the name of the class when generating a descriptive name, by accessing \ncls.__name__\n.\n\n\nsuffix\n: The optional suffix used when differentiating individual views in a viewset.\n\n\n\n\nDefault: \n'rest_framework.views.get_view_name'\n\n\nVIEW_DESCRIPTION_FUNCTION\n\n\nA string representing the function that should be used when generating view descriptions.\n\n\nThis setting can be changed to support markup styles other than the default markdown.  For example, you can use it to support \nrst\n markup in your view docstrings being output in the browsable API.\n\n\nThis should be a function with the following signature:\n\n\nview_description(cls, html=False)\n\n\n\n\n\ncls\n: The view class.  Typically the description function would inspect the docstring of the class when generating a description, by accessing \ncls.__doc__\n\n\nhtml\n: A boolean indicating if HTML output is required.  \nTrue\n when used in the browsable API, and \nFalse\n when used in generating \nOPTIONS\n responses.\n\n\n\n\nDefault: \n'rest_framework.views.get_view_description'\n\n\nHTML Select Field cutoffs\n\n\nGlobal settings for \nselect field cutoffs for rendering relational fields\n in the browsable API.\n\n\nHTML_SELECT_CUTOFF\n\n\nGlobal setting for the \nhtml_cutoff\n value.  Must be an integer.\n\n\nDefault: 1000\n\n\nHTML_SELECT_CUTOFF_TEXT\n\n\nA string representing a global setting for \nhtml_cutoff_text\n.\n\n\nDefault: \n\"More than {count} items...\"\n\n\n\n\nMiscellaneous settings\n\n\nEXCEPTION_HANDLER\n\n\nA string representing the function that should be used when returning a response for any given exception.  If the function returns \nNone\n, a 500 error will be raised.\n\n\nThis setting can be changed to support error responses other than the default \n{\"detail\": \"Failure...\"}\n responses.  For example, you can use it to provide API responses like \n{\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]}\n.\n\n\nThis should be a function with the following signature:\n\n\nexception_handler(exc, context)\n\n\n\n\n\nexc\n: The exception.\n\n\n\n\nDefault: \n'rest_framework.views.exception_handler'\n\n\nNON_FIELD_ERRORS_KEY\n\n\nA string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.\n\n\nDefault: \n'non_field_errors'\n\n\nURL_FIELD_NAME\n\n\nA string representing the key that should be used for the URL fields generated by \nHyperlinkedModelSerializer\n.\n\n\nDefault: \n'url'\n\n\nNUM_PROXIES\n\n\nAn 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 \nNone\n then less strict IP matching will be used by the throttle classes.\n\n\nDefault: \nNone", 
                 "title": "Settings"
             }, 
             {
    @@ -3595,6 +3660,21 @@
                 "text": "The renderer classes that are supported when building test requests.  The format of any of these renderer classes may be used when constructing a test request, for example:  client.post('/users', {'username': 'jamie'}, format='json')  Default:  (\n    'rest_framework.renderers.MultiPartRenderer',\n    'rest_framework.renderers.JSONRenderer'\n)", 
                 "title": "TEST_REQUEST_RENDERER_CLASSES"
             }, 
    +        {
    +            "location": "/api-guide/settings/#schema-generation-controls", 
    +            "text": "", 
    +            "title": "Schema generation controls"
    +        }, 
    +        {
    +            "location": "/api-guide/settings/#schema_coerce_path_pk", 
    +            "text": "If set, this maps the  'pk'  identifier in the URL conf onto the actual field\nname when generating a schema path parameter. Typically this will be  'id' .\nThis gives a more suitable representation as \"primary key\" is an implementation\ndetail, wheras \"identifier\" is a more general concept.  Default:  True", 
    +            "title": "SCHEMA_COERCE_PATH_PK"
    +        }, 
    +        {
    +            "location": "/api-guide/settings/#schema_coerce_method_names", 
    +            "text": "If set, this is used to map internal viewset method names onto external action\nnames used in the schema generation. This allows us to generate names that\nare more suitable for an external representation than those that are used\ninternally in the codebase.  Default:  {'retrieve': 'read', 'destroy': 'delete'}", 
    +            "title": "SCHEMA_COERCE_METHOD_NAMES"
    +        }, 
             {
                 "location": "/api-guide/settings/#content-type-controls", 
                 "text": "", 
    @@ -3680,6 +3760,21 @@
                 "text": "A string representing the function that should be used when generating view descriptions.  This setting can be changed to support markup styles other than the default markdown.  For example, you can use it to support  rst  markup in your view docstrings being output in the browsable API.  This should be a function with the following signature:  view_description(cls, html=False)   cls : The view class.  Typically the description function would inspect the docstring of the class when generating a description, by accessing  cls.__doc__  html : A boolean indicating if HTML output is required.   True  when used in the browsable API, and  False  when used in generating  OPTIONS  responses.   Default:  'rest_framework.views.get_view_description'", 
                 "title": "VIEW_DESCRIPTION_FUNCTION"
             }, 
    +        {
    +            "location": "/api-guide/settings/#html-select-field-cutoffs", 
    +            "text": "Global settings for  select field cutoffs for rendering relational fields  in the browsable API.", 
    +            "title": "HTML Select Field cutoffs"
    +        }, 
    +        {
    +            "location": "/api-guide/settings/#html_select_cutoff", 
    +            "text": "Global setting for the  html_cutoff  value.  Must be an integer.  Default: 1000", 
    +            "title": "HTML_SELECT_CUTOFF"
    +        }, 
    +        {
    +            "location": "/api-guide/settings/#html_select_cutoff_text", 
    +            "text": "A string representing a global setting for  html_cutoff_text .  Default:  \"More than {count} items...\"", 
    +            "title": "HTML_SELECT_CUTOFF_TEXT"
    +        }, 
             {
                 "location": "/api-guide/settings/#miscellaneous-settings", 
                 "text": "", 
    @@ -3917,7 +4012,7 @@
             }, 
             {
                 "location": "/topics/html-and-forms/", 
    -            "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n 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.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n    renderer_classes = [TemplateHTMLRenderer]\n    template_name = 'profile_list.html'\n\n    def get(self, request):\n        queryset = Profile.objects.all()\n        return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n    {% for profile in profiles %}\n    \nli\n{{ profile.name }}\n/li\n\n    {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n    renderer_classes = [TemplateHTMLRenderer]\n    template_name = 'profile_detail.html'\n\n    def get(self, request, pk):\n        profile = get_object_or_404(Profile, pk=pk)\n        serializer = ProfileSerializer(profile)\n        return Response({'serializer': serializer, 'profile': profile})\n\n    def post(self, request, pk):\n        profile = get_object_or_404(Profile, pk=pk)\n        serializer = ProfileSerializer(profile, data=request.data)\n        if not serializer.is_valid():\n            return Response({'serializer': serializer, 'profile': profile})\n        serializer.save()\n        return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\"\n\n    {% csrf_token %}\n    {% render_form serializer %}\n    \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n    \u2026\n    \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n    email = serializers.EmailField(\n        max_length=100,\n        style={'placeholder': 'Email'}\n    )\n    password = serializers.CharField(\n        max_length=100,\n        style={'input_type': 'password', 'placeholder': 'Password'}\n    )\n    remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer template_pack='rest_framework/vertical' %}\n    \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer %}\n    \ndiv class=\"form-group\"\n\n        \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n            \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n        \n/div\n\n    \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer template_pack='rest_framework/inline' %}\n    \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\nor relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\nor relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\nor relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\nor relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\nor nested serializer with \nmany=True\n\n\nhide_label", 
    +            "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n 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.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n    renderer_classes = [TemplateHTMLRenderer]\n    template_name = 'profile_list.html'\n\n    def get(self, request):\n        queryset = Profile.objects.all()\n        return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n    {% for profile in profiles %}\n    \nli\n{{ profile.name }}\n/li\n\n    {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n    renderer_classes = [TemplateHTMLRenderer]\n    template_name = 'profile_detail.html'\n\n    def get(self, request, pk):\n        profile = get_object_or_404(Profile, pk=pk)\n        serializer = ProfileSerializer(profile)\n        return Response({'serializer': serializer, 'profile': profile})\n\n    def post(self, request, pk):\n        profile = get_object_or_404(Profile, pk=pk)\n        serializer = ProfileSerializer(profile, data=request.data)\n        if not serializer.is_valid():\n            return Response({'serializer': serializer, 'profile': profile})\n        serializer.save()\n        return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\"\n\n    {% csrf_token %}\n    {% render_form serializer %}\n    \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n    \u2026\n    \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n    email = serializers.EmailField(\n        max_length=100,\n        style={'placeholder': 'Email'}\n    )\n    password = serializers.CharField(\n        max_length=100,\n        style={'input_type': 'password', 'placeholder': 'Password'}\n    )\n    remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer template_pack='rest_framework/vertical' %}\n    \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer %}\n    \ndiv class=\"form-group\"\n\n        \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n            \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n        \n/div\n\n    \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n    {% csrf_token %}\n    {% render_form serializer template_pack='rest_framework/inline' %}\n    \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\n or relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\n or relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\n or nested serializer with \nmany=True\n\n\nhide_label", 
                 "title": "HTML & Forms"
             }, 
             {
    @@ -3957,7 +4052,7 @@
             }, 
             {
                 "location": "/topics/html-and-forms/#field-styles", 
    -            "text": "Serializer fields can have their rendering style customized by using the  style  keyword argument. This argument is a dictionary of options that control the template and layout used.  The most common way to customize the field style is to use the  base_template  style keyword argument to select which template in the template pack should be use.  For example, to render a  CharField  as an HTML textarea rather than the default HTML input, you would use something like this:  details = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html'}\n)  If you instead want a field to be rendered using a custom template that is  not part of an included template pack , you can instead use the  template  style option, to fully specify a template name:  details = serializers.CharField(\n    max_length=1000,\n    style={'template': 'my-field-templates/custom-input.html'}\n)  Field templates can also use additional style properties, depending on their type. For example, the  textarea.html  template also accepts a  rows  property that can be used to affect the sizing of the control.  details = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html', 'rows': 10}\n)  The complete list of  base_template  options and their associated style options is listed below.     base_template  Valid field types  Additional style options      input.html  Any string, numeric or date/time field  input_type, placeholder, hide_label    textarea.html  CharField  rows, placeholder, hide_label    select.html  ChoiceField or relational field types  hide_label    radio.html  ChoiceField or relational field types  inline, hide_label    select_multiple.html  MultipleChoiceField or relational fields with  many=True  hide_label    checkbox_multiple.html  MultipleChoiceField or relational fields with  many=True  inline, hide_label    checkbox.html  BooleanField  hide_label    fieldset.html  Nested serializer  hide_label    list_fieldset.html  ListField or nested serializer with  many=True  hide_label", 
    +            "text": "Serializer fields can have their rendering style customized by using the  style  keyword argument. This argument is a dictionary of options that control the template and layout used.  The most common way to customize the field style is to use the  base_template  style keyword argument to select which template in the template pack should be use.  For example, to render a  CharField  as an HTML textarea rather than the default HTML input, you would use something like this:  details = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html'}\n)  If you instead want a field to be rendered using a custom template that is  not part of an included template pack , you can instead use the  template  style option, to fully specify a template name:  details = serializers.CharField(\n    max_length=1000,\n    style={'template': 'my-field-templates/custom-input.html'}\n)  Field templates can also use additional style properties, depending on their type. For example, the  textarea.html  template also accepts a  rows  property that can be used to affect the sizing of the control.  details = serializers.CharField(\n    max_length=1000,\n    style={'base_template': 'textarea.html', 'rows': 10}\n)  The complete list of  base_template  options and their associated style options is listed below.     base_template  Valid field types  Additional style options      input.html  Any string, numeric or date/time field  input_type, placeholder, hide_label    textarea.html  CharField  rows, placeholder, hide_label    select.html  ChoiceField  or relational field types  hide_label    radio.html  ChoiceField  or relational field types  inline, hide_label    select_multiple.html  MultipleChoiceField  or relational fields with  many=True  hide_label    checkbox_multiple.html  MultipleChoiceField  or relational fields with  many=True  inline, hide_label    checkbox.html  BooleanField  hide_label    fieldset.html  Nested serializer  hide_label    list_fieldset.html  ListField  or nested serializer with  many=True  hide_label", 
                 "title": "Field styles"
             }, 
             {
    @@ -4102,7 +4197,7 @@
             }, 
             {
                 "location": "/topics/third-party-resources/", 
    -            "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n 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.\n\n\nIf 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 \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n 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.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n 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.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n    git tag -a {0} -m 'version 0.1.0'\n    git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, 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 \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\nhtml-json-forms\n: Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - 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.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\ndjango-rest-framework-version-transforms\n - Enables the use of delta transformations for versioning of DRF resource representations.\n\n\ndjango-rest-messaging\n, \ndjango-rest-messaging-centrifugo\n and \ndjango-rest-messaging-js\n - A real-time pluggable messaging service using DRM.\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\nDjango REST Framework course\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nBlog posts about Django REST framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework", 
    +            "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n 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.\n\n\nIf 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 \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n 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.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n 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.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n    git tag -a {0} -m 'version 0.1.0'\n    git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, 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 \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\nhtml-json-forms\n: Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - 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.\n\n\ndrf-url-filter\n is a simple Django app to apply filters on drf \nModelViewSet\n's \nQueryset\n in a clean, simple and configurable way. It also supports validations on incoming query params and their values.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\ndjango-rest-framework-version-transforms\n - Enables the use of delta transformations for versioning of DRF resource representations.\n\n\ndjango-rest-messaging\n, \ndjango-rest-messaging-centrifugo\n and \ndjango-rest-messaging-js\n - A real-time pluggable messaging service using DRM.\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\nDjango REST Framework course\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nBlog posts about Django REST framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework", 
                 "title": "Third Party Resources"
             }, 
             {
    @@ -4232,7 +4327,7 @@
             }, 
             {
                 "location": "/topics/third-party-resources/#filtering", 
    -            "text": "djangorestframework-chain  - Allows arbitrary chaining of both relations and lookup filters.  django-url-filter  - 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.", 
    +            "text": "djangorestframework-chain  - Allows arbitrary chaining of both relations and lookup filters.  django-url-filter  - 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.  drf-url-filter  is a simple Django app to apply filters on drf  ModelViewSet 's  Queryset  in a clean, simple and configurable way. It also supports validations on incoming query params and their values.", 
                 "title": "Filtering"
             }, 
             {
    @@ -4267,7 +4362,7 @@
             }, 
             {
                 "location": "/topics/contributing/", 
    -            "text": "Contributing to REST framework\n\n\n\n\nThe world can only really be changed one piece at a time.  The art is picking that piece.\n\n\n \nTim Berners-Lee\n\n\n\n\nThere 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.\n\n\nCommunity\n\n\nThe 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.\n\n\nIf 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.\n\n\nOther really great ways you can help move the community forward include helping to answer questions on the \ndiscussion group\n, or setting up an \nemail alert on StackOverflow\n so that you get notified of any new questions with the \ndjango-rest-framework\n tag.\n\n\nWhen 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.\n\n\nCode of conduct\n\n\nPlease keep the tone polite \n 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.\n\n\nBe 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.\n\n\nThe \nDjango code of conduct\n gives a fuller set of guidelines for participating in community forums.\n\n\nIssues\n\n\nIt's really helpful if you can make sure to address issues on the correct channel.  Usage questions should be directed to the \ndiscussion group\n.  Feature requests, bug reports and other issues should be raised on the GitHub \nissue tracker\n.\n\n\nSome tips on good issue reporting:\n\n\n\n\nWhen describing issues try to phrase your ticket in terms of the \nbehavior\n you think needs changing rather than the \ncode\n you think need changing.\n\n\nSearch the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.\n\n\nIf reporting a bug, then try to include a pull request with a failing test case.  This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.\n\n\nFeature 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.\n\n\nClosing 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.\n\n\n\n\nTriaging issues\n\n\nGetting 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\n\n\n\n\nRead through the ticket - does it make sense, is it missing any context that would help explain it better?\n\n\nIs the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?\n\n\nIf the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?\n\n\nIf the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?\n\n\nIf 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.\n\n\n\n\nDevelopment\n\n\nTo start developing on Django REST framework, clone the repo:\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nChanges should broadly follow the \nPEP 8\n style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.\n\n\nTesting\n\n\nTo run the tests, clone the repository, and then:\n\n\n# Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py\n\n\n\nTest options\n\n\nRun using a more concise output style.\n\n\n./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n./runtests.py test_this_method\n\n\n\nNote: 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.\n\n\nRunning against multiple environments\n\n\nYou can also use the excellent \ntox\n testing tool to run the tests against all supported versions of Python and Django.  Install \ntox\n globally, and then simply run:\n\n\ntox\n\n\n\nPull requests\n\n\nIt'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.\n\n\nIt'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.\n\n\nIt'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.\n\n\nGitHub's documentation for working on pull requests is \navailable here\n.\n\n\nAlways run the tests before submitting pull requests, and ideally run \ntox\n in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.\n\n\nOnce 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.\n\n\n\n\nAbove: Travis build notifications\n\n\nManaging compatibility issues\n\n\nSometimes, 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 \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nDocumentation\n\n\nThe documentation for REST framework is built from the \nMarkdown\n source files in \nthe docs directory\n.\n\n\nThere are many great Markdown editors that make working with the documentation really easy.  The \nMou editor for Mac\n is one such editor that comes highly recommended.\n\n\nBuilding the documentation\n\n\nTo build the documentation, install MkDocs with \npip install mkdocs\n and then run the following command.\n\n\nmkdocs build\n\n\n\nThis will build the documentation into the \nsite\n directory.\n\n\nYou can build the documentation and open a preview in a browser window by using the \nserve\n command.\n\n\nmkdocs serve\n\n\n\nLanguage style\n\n\nDocumentation 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.\n\n\nSome other tips:\n\n\n\n\nKeep paragraphs reasonably short.\n\n\nDon't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.\n\n\n\n\nMarkdown style\n\n\nThere are a couple of conventions you should follow when working on the documentation.\n\n\n1. Headers\n\n\nHeaders should use the hash style.  For example:\n\n\n### Some important topic\n\n\n\nThe underline style should not be used.  \nDon't do this:\n\n\nSome important topic\n====================\n\n\n\n2. Links\n\n\nLinks should always use the reference style, with the referenced hyperlinks kept at the end of the document.\n\n\nHere is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing\n\n\n\nThis style helps keep the documentation source consistent and readable.\n\n\nIf you are hyperlinking to another REST framework document, you should use a relative link, and link to the \n.md\n suffix.  For example:\n\n\n[authentication]: ../api-guide/authentication.md\n\n\n\nLinking 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.\n\n\n3. Notes\n\n\nIf you want to draw attention to a note or warning, use a pair of enclosing lines, like so:\n\n\n---\n\n**Note:** A useful documentation note.\n\n---", 
    +            "text": "Contributing to REST framework\n\n\n\n\nThe world can only really be changed one piece at a time.  The art is picking that piece.\n\n\n \nTim Berners-Lee\n\n\n\n\nThere 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.\n\n\nCommunity\n\n\nThe 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.\n\n\nIf 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.\n\n\nOther really great ways you can help move the community forward include helping to answer questions on the \ndiscussion group\n, or setting up an \nemail alert on StackOverflow\n so that you get notified of any new questions with the \ndjango-rest-framework\n tag.\n\n\nWhen 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.\n\n\nCode of conduct\n\n\nPlease keep the tone polite \n 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.\n\n\nBe 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.\n\n\nThe \nDjango code of conduct\n gives a fuller set of guidelines for participating in community forums.\n\n\nIssues\n\n\nIt's really helpful if you can make sure to address issues on the correct channel.  Usage questions should be directed to the \ndiscussion group\n.  Feature requests, bug reports and other issues should be raised on the GitHub \nissue tracker\n.\n\n\nSome tips on good issue reporting:\n\n\n\n\nWhen describing issues try to phrase your ticket in terms of the \nbehavior\n you think needs changing rather than the \ncode\n you think need changing.\n\n\nSearch the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.\n\n\nIf reporting a bug, then try to include a pull request with a failing test case.  This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.\n\n\nFeature 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.\n\n\nClosing 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.\n\n\n\n\nTriaging issues\n\n\nGetting 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\n\n\n\n\nRead through the ticket - does it make sense, is it missing any context that would help explain it better?\n\n\nIs the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?\n\n\nIf the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?\n\n\nIf the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?\n\n\nIf 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.\n\n\n\n\nDevelopment\n\n\nTo start developing on Django REST framework, clone the repo:\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nChanges should broadly follow the \nPEP 8\n style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.\n\n\nTesting\n\n\nTo run the tests, clone the repository, and then:\n\n\n# Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install django\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py\n\n\n\nTest options\n\n\nRun using a more concise output style.\n\n\n./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n./runtests.py test_this_method\n\n\n\nNote: 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.\n\n\nRunning against multiple environments\n\n\nYou can also use the excellent \ntox\n testing tool to run the tests against all supported versions of Python and Django.  Install \ntox\n globally, and then simply run:\n\n\ntox\n\n\n\nPull requests\n\n\nIt'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.\n\n\nIt'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.\n\n\nIt'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.\n\n\nGitHub's documentation for working on pull requests is \navailable here\n.\n\n\nAlways run the tests before submitting pull requests, and ideally run \ntox\n in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.\n\n\nOnce 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.\n\n\n\n\nAbove: Travis build notifications\n\n\nManaging compatibility issues\n\n\nSometimes, 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 \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nDocumentation\n\n\nThe documentation for REST framework is built from the \nMarkdown\n source files in \nthe docs directory\n.\n\n\nThere are many great Markdown editors that make working with the documentation really easy.  The \nMou editor for Mac\n is one such editor that comes highly recommended.\n\n\nBuilding the documentation\n\n\nTo build the documentation, install MkDocs with \npip install mkdocs\n and then run the following command.\n\n\nmkdocs build\n\n\n\nThis will build the documentation into the \nsite\n directory.\n\n\nYou can build the documentation and open a preview in a browser window by using the \nserve\n command.\n\n\nmkdocs serve\n\n\n\nLanguage style\n\n\nDocumentation 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.\n\n\nSome other tips:\n\n\n\n\nKeep paragraphs reasonably short.\n\n\nDon't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.\n\n\n\n\nMarkdown style\n\n\nThere are a couple of conventions you should follow when working on the documentation.\n\n\n1. Headers\n\n\nHeaders should use the hash style.  For example:\n\n\n### Some important topic\n\n\n\nThe underline style should not be used.  \nDon't do this:\n\n\nSome important topic\n====================\n\n\n\n2. Links\n\n\nLinks should always use the reference style, with the referenced hyperlinks kept at the end of the document.\n\n\nHere is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing\n\n\n\nThis style helps keep the documentation source consistent and readable.\n\n\nIf you are hyperlinking to another REST framework document, you should use a relative link, and link to the \n.md\n suffix.  For example:\n\n\n[authentication]: ../api-guide/authentication.md\n\n\n\nLinking 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.\n\n\n3. Notes\n\n\nIf you want to draw attention to a note or warning, use a pair of enclosing lines, like so:\n\n\n---\n\n**Note:** A useful documentation note.\n\n---", 
                 "title": "Contributing to REST framework"
             }, 
             {
    @@ -4302,7 +4397,7 @@
             }, 
             {
                 "location": "/topics/contributing/#testing", 
    -            "text": "To run the tests, clone the repository, and then:  # Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py", 
    +            "text": "To run the tests, clone the repository, and then:  # Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install django\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py", 
                 "title": "Testing"
             }, 
             {
    @@ -4362,12 +4457,12 @@
             }, 
             {
                 "location": "/topics/project-management/", 
    -            "text": "Project management\n\n\n\n\n\"No one can whistle a symphony; it takes a whole orchestra to play it\"\n\n\n Halford E. Luccock\n\n\n\n\nThis document outlines our project management processes for REST framework.\n\n\nThe aim is to ensure that the project has a high \n\n\"bus factor\"\n, and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.\n\n\n\n\nMaintenance team\n\n\nWe 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.\n\n\nCurrent team\n\n\nThe \nmaintenance team for Q4 2015\n:\n\n\n\n\n@tomchristie\n\n\n@xordoquy\n (Release manager.)\n\n\n@carltongibson\n\n\n@kevin-brown\n\n\n@jpadilla\n\n\n\n\nMaintenance cycles\n\n\nEach maintenance cycle is initiated by an issue being opened with the \nProcess\n label.\n\n\n\n\nTo be considered for a maintainer role simply comment against the issue.\n\n\nExisting members must explicitly opt-in to the next cycle by check-marking their name.\n\n\nThe final decision on the incoming team will be made by \n@tomchristie\n.\n\n\n\n\nMembers of the maintenance team will be added as collaborators to the repository.\n\n\nThe following template should be used for the description of the issue, and serves as the formal process for selecting the team.\n\n\nThis issue is for determining the maintenance team for the *** period.\n\nPlease see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.\n\n---\n\n#### Renewing existing members.\n\nThe following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.\n\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n\n---\n\n#### New members.\n\nIf you wish to be considered for this or a future date, please comment against this or subsequent issues.\n\nTo 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.\n\n\n\nResponsibilities of team members\n\n\nTeam members have the following responsibilities.\n\n\n\n\nClose invalid or resolved tickets.\n\n\nAdd triage labels and milestones to tickets.\n\n\nMerge finalized pull requests.\n\n\nBuild and deploy the documentation, using \nmkdocs gh-deploy\n.\n\n\nBuild and update the included translation packs.\n\n\n\n\nFurther notes for maintainers:\n\n\n\n\nCode changes should come in the form of a pull request - do not push directly to master.\n\n\nMaintainers should typically not merge their own pull requests.\n\n\nEach issue/pull request should have exactly one label once triaged.\n\n\nSearch for un-triaged issues with \nis:open no:label\n.\n\n\n\n\nIt should be noted that participating actively in the REST framework project clearly \ndoes not require being part of the maintenance team\n. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.\n\n\n\n\nRelease process\n\n\nThe release manager is selected on every quarterly maintenance cycle.\n\n\n\n\nThe manager should be selected by \n@tomchristie\n.\n\n\nThe manager will then have the maintainer role added to PyPI package.\n\n\nThe previous manager will then have the maintainer role removed from the PyPI package.\n\n\n\n\nOur PyPI releases will be handled by either the current release manager, or by \n@tomchristie\n. Every release should have an open issue tagged with the \nRelease\n label and marked against the appropriate milestone.\n\n\nThe following template should be used for the description of the issue, and serves as a release checklist.\n\n\nRelease manager is @***.\nPull request is #***.\n\nDuring development cycle:\n\n- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).\n- [ ] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Push the package to PyPI with `./setup.py publish`.\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.\n\n\n\nWhen pushing the release to PyPI ensure that your environment has been installed from our development \nrequirement.txt\n, so that documentation and PyPI installs are consistently being built against a pinned set of packages.\n\n\n\n\nTranslations\n\n\nThe maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the \ntransifex service\n.\n\n\nManaging Transifex\n\n\nThe \nofficial Transifex client\n is used to upload and download translations to Transifex. The client is installed using pip:\n\n\npip install transifex-client\n\n\n\nTo use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a \n~/.transifexrc\n file which contains your credentials.\n\n\n[https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com\n\n\n\nUpload new source files\n\n\nWhen 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:\n\n\n# 1. Update the source django.po file, which is the US English version.\ncd rest_framework\ndjango-admin.py makemessages -l en_US\n# 2. Push the source django.po file to Transifex.\ncd ..\ntx push -s\n\n\n\nWhen pushing source files, Transifex will update the source strings of a resource to match those from the new source file.\n\n\nHere's how differences between the old and new source files will be handled:\n\n\n\n\nNew strings will be added.\n\n\nModified strings will be added as well.\n\n\nStrings 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 \nTransifex Translation Memory\n will automatically include the translation string.\n\n\n\n\nDownload translations\n\n\nWhen a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:\n\n\n# 3. Pull the translated django.po files from Transifex.\ntx pull -a\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages\n\n\n\n\n\nProject requirements\n\n\nAll our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the \nrequirements\n directory. The requirements files are referenced from the \ntox.ini\n configuration file, ensuring we have a single source of truth for package versions used in testing.\n\n\nPackage 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 \npip list --outdated\n.\n\n\n\n\nProject ownership\n\n\nThe PyPI package is owned by \n@tomchristie\n. As a backup \n@j4mie\n also has ownership of the package.\n\n\nIf \n@tomchristie\n ceases to participate in the project then \n@j4mie\n has responsibility for handing over ownership duties.\n\n\nOutstanding management \n ownership issues\n\n\nThe following issues still need to be addressed:\n\n\n\n\nConsider moving the repo into a proper GitHub organization\n.\n\n\nEnsure \n@jamie\n has back-up access to the \ndjango-rest-framework.org\n domain setup and admin.\n\n\nDocument ownership of the \nlive example\n API.\n\n\nDocument ownership of the \nmailing list\n and IRC channel.\n\n\nDocument ownership and management of the security mailing list.", 
    +            "text": "Project management\n\n\n\n\n\"No one can whistle a symphony; it takes a whole orchestra to play it\"\n\n\n Halford E. Luccock\n\n\n\n\nThis document outlines our project management processes for REST framework.\n\n\nThe aim is to ensure that the project has a high\n\n\"bus factor\"\n, and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.\n\n\n\n\nMaintenance team\n\n\nWe 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.\n\n\nCurrent team\n\n\nThe \nmaintenance team for Q4 2015\n:\n\n\n\n\n@tomchristie\n\n\n@xordoquy\n (Release manager.)\n\n\n@carltongibson\n\n\n@kevin-brown\n\n\n@jpadilla\n\n\n\n\nMaintenance cycles\n\n\nEach maintenance cycle is initiated by an issue being opened with the \nProcess\n label.\n\n\n\n\nTo be considered for a maintainer role simply comment against the issue.\n\n\nExisting members must explicitly opt-in to the next cycle by check-marking their name.\n\n\nThe final decision on the incoming team will be made by \n@tomchristie\n.\n\n\n\n\nMembers of the maintenance team will be added as collaborators to the repository.\n\n\nThe following template should be used for the description of the issue, and serves as the formal process for selecting the team.\n\n\nThis issue is for determining the maintenance team for the *** period.\n\nPlease see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.\n\n---\n\n#### Renewing existing members.\n\nThe following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.\n\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n\n---\n\n#### New members.\n\nIf you wish to be considered for this or a future date, please comment against this or subsequent issues.\n\nTo 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.\n\n\n\nResponsibilities of team members\n\n\nTeam members have the following responsibilities.\n\n\n\n\nClose invalid or resolved tickets.\n\n\nAdd triage labels and milestones to tickets.\n\n\nMerge finalized pull requests.\n\n\nBuild and deploy the documentation, using \nmkdocs gh-deploy\n.\n\n\nBuild and update the included translation packs.\n\n\n\n\nFurther notes for maintainers:\n\n\n\n\nCode changes should come in the form of a pull request - do not push directly to master.\n\n\nMaintainers should typically not merge their own pull requests.\n\n\nEach issue/pull request should have exactly one label once triaged.\n\n\nSearch for un-triaged issues with \nis:open no:label\n.\n\n\n\n\nIt should be noted that participating actively in the REST framework project clearly \ndoes not require being part of the maintenance team\n. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.\n\n\n\n\nRelease process\n\n\nThe release manager is selected on every quarterly maintenance cycle.\n\n\n\n\nThe manager should be selected by \n@tomchristie\n.\n\n\nThe manager will then have the maintainer role added to PyPI package.\n\n\nThe previous manager will then have the maintainer role removed from the PyPI package.\n\n\n\n\nOur PyPI releases will be handled by either the current release manager, or by \n@tomchristie\n. Every release should have an open issue tagged with the \nRelease\n label and marked against the appropriate milestone.\n\n\nThe following template should be used for the description of the issue, and serves as a release checklist.\n\n\nRelease manager is @***.\nPull request is #***.\n\nDuring development cycle:\n\n- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).\n- [ ] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Push the package to PyPI with `./setup.py publish`.\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.\n\n\n\nWhen pushing the release to PyPI ensure that your environment has been installed from our development \nrequirement.txt\n, so that documentation and PyPI installs are consistently being built against a pinned set of packages.\n\n\n\n\nTranslations\n\n\nThe maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the \ntransifex service\n.\n\n\nManaging Transifex\n\n\nThe \nofficial Transifex client\n is used to upload and download translations to Transifex. The client is installed using pip:\n\n\npip install transifex-client\n\n\n\nTo use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a \n~/.transifexrc\n file which contains your credentials.\n\n\n[https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com\n\n\n\nUpload new source files\n\n\nWhen 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:\n\n\n# 1. Update the source django.po file, which is the US English version.\ncd rest_framework\ndjango-admin.py makemessages -l en_US\n# 2. Push the source django.po file to Transifex.\ncd ..\ntx push -s\n\n\n\nWhen pushing source files, Transifex will update the source strings of a resource to match those from the new source file.\n\n\nHere's how differences between the old and new source files will be handled:\n\n\n\n\nNew strings will be added.\n\n\nModified strings will be added as well.\n\n\nStrings 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 \nTransifex Translation Memory\n will automatically include the translation string.\n\n\n\n\nDownload translations\n\n\nWhen a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:\n\n\n# 3. Pull the translated django.po files from Transifex.\ntx pull -a --minimum-perc 10\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages\n\n\n\n\n\nProject requirements\n\n\nAll our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the \nrequirements\n directory. The requirements files are referenced from the \ntox.ini\n configuration file, ensuring we have a single source of truth for package versions used in testing.\n\n\nPackage 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 \npip list --outdated\n.\n\n\n\n\nProject ownership\n\n\nThe PyPI package is owned by \n@tomchristie\n. As a backup \n@j4mie\n also has ownership of the package.\n\n\nIf \n@tomchristie\n ceases to participate in the project then \n@j4mie\n has responsibility for handing over ownership duties.\n\n\nOutstanding management \n ownership issues\n\n\nThe following issues still need to be addressed:\n\n\n\n\nConsider moving the repo into a proper GitHub organization\n.\n\n\nEnsure \n@jamie\n has back-up access to the \ndjango-rest-framework.org\n domain setup and admin.\n\n\nDocument ownership of the \nlive example\n API.\n\n\nDocument ownership of the \nmailing list\n and IRC channel.\n\n\nDocument ownership and management of the security mailing list.", 
                 "title": "Project management"
             }, 
             {
                 "location": "/topics/project-management/#project-management", 
    -            "text": "\"No one can whistle a symphony; it takes a whole orchestra to play it\"   Halford E. Luccock   This document outlines our project management processes for REST framework.  The aim is to ensure that the project has a high  \"bus factor\" , and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.", 
    +            "text": "\"No one can whistle a symphony; it takes a whole orchestra to play it\"   Halford E. Luccock   This document outlines our project management processes for REST framework.  The aim is to ensure that the project has a high \"bus factor\" , and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.", 
                 "title": "Project management"
             }, 
             {
    @@ -4412,7 +4507,7 @@
             }, 
             {
                 "location": "/topics/project-management/#download-translations", 
    -            "text": "When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:  # 3. Pull the translated django.po files from Transifex.\ntx pull -a\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages", 
    +            "text": "When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:  # 3. Pull the translated django.po files from Transifex.\ntx pull -a --minimum-perc 10\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages", 
                 "title": "Download translations"
             }, 
             {
    @@ -4432,7 +4527,7 @@
             }, 
             {
                 "location": "/topics/3.0-announcement/", 
    -            "text": "Django REST framework 3.0\n\n\nThe 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.\n\n\nThis release is incremental in nature. There \nare\n some breaking API changes, and upgrading \nwill\n require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.\n\n\nThe difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.\n\n\n3.0 is the first of three releases that have been funded by our recent \nKickstarter campaign\n.\n\n\nAs ever, a huge thank you to our many \nwonderful sponsors\n. 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.\n\n\n\n\nNew features\n\n\nNotable features of this new release include:\n\n\n\n\nPrintable representations on serializers that allow you to inspect exactly what fields are present on the instance.\n\n\nSimple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit \nModelSerializer\n class and the explicit \nSerializer\n class.\n\n\nA new \nBaseSerializer\n class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.\n\n\nA cleaner fields API including new classes such as \nListField\n and \nMultipleChoiceField\n.\n\n\nSuper simple default implementations\n for the generic views.\n\n\nSupport for overriding how validation errors are handled by your API.\n\n\nA metadata API that allows you to customize how \nOPTIONS\n requests are handled by your API.\n\n\nA more compact JSON output with unicode style encoding turned on by default.\n\n\nTemplated based HTML form rendering for serializers. This will be finalized as  public API in the upcoming 3.1 release.\n\n\n\n\nSignificant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two \nKickstarter stretch goals\n - \"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.\n\n\n\n\nREST framework: Under the hood.\n\n\nThis talk from the \nDjango: Under the Hood\n event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.\n\n\n\n\n\n\n\nBelow is an in-depth guide to the API changes and migration notes for 3.0.\n\n\nRequest objects\n\n\n.query_params\n properties.\nThe \n.data\n and \n\n\nThe usage of \nrequest.DATA\n and \nrequest.FILES\n is now pending deprecation in favor of a single \nrequest.data\n attribute that contains \nall\n the parsed data.\n\n\nHaving 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.\n\n\nYou may now pass all the request data to a serializer class in a single argument:\n\n\n# Do this...\nExampleSerializer(data=request.data)\n\n\n\nInstead of passing the files argument separately:\n\n\n# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n\n\n\nThe usage of \nrequest.QUERY_PARAMS\n is now pending deprecation in favor of the lowercased \nrequest.query_params\n.\n\n\n\n\nSerializers\n\n\nSingle-step object creation.\n\n\nPreviously the serializers used a two-step object creation, as follows:\n\n\n\n\nValidating the data would create an object instance. This instance would be available as \nserializer.object\n.\n\n\nCalling \nserializer.save()\n would then save the object instance to the database.\n\n\n\n\nThis style is in-line with how the \nModelForm\n class works in Django, but is problematic for a number of reasons:\n\n\n\n\nSome data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when \n.save()\n is called.\n\n\nInstantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. \nExampleModel.objects.create(...)\n. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.\n\n\nThe two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?\n\n\n\n\nWe now use single-step object creation, like so:\n\n\n\n\nValidating the data makes the cleaned data available as \nserializer.validated_data\n.\n\n\nCalling \nserializer.save()\n then saves and returns the new object instance.\n\n\n\n\nThe resulting API changes are further detailed below.\n\n\n.update()\n methods.\nThe \n.create()\n and \n\n\nThe \n.restore_object()\n method is now removed, and we instead have two separate methods, \n.create()\n and \n.update()\n. These methods work slightly different to the previous \n.restore_object()\n.\n\n\nWhen using the \n.create()\n and \n.update()\n methods you should both create \nand save\n the object instance. This is in contrast to the previous \n.restore_object()\n behavior that would instantiate the object but not save it.\n\n\nThese methods also replace the optional \n.save_object()\n method, which no longer exists.\n\n\nThe following example from the tutorial previously used \nrestore_object()\n to handle both creating and updating object instances.\n\n\ndef restore_object(self, attrs, instance=None):\n    if instance:\n        # Update existing instance\n        instance.title = attrs.get('title', instance.title)\n        instance.code = attrs.get('code', instance.code)\n        instance.linenos = attrs.get('linenos', instance.linenos)\n        instance.language = attrs.get('language', instance.language)\n        instance.style = attrs.get('style', instance.style)\n        return instance\n\n    # Create new instance\n    return Snippet(**attrs)\n\n\n\nThis would now be split out into two separate methods.\n\n\ndef update(self, instance, validated_data):\n    instance.title = validated_data.get('title', instance.title)\n    instance.code = validated_data.get('code', instance.code)\n    instance.linenos = validated_data.get('linenos', instance.linenos)\n    instance.language = validated_data.get('language', instance.language)\n    instance.style = validated_data.get('style', instance.style)\n    instance.save()\n    return instance\n\ndef create(self, validated_data):\n    return Snippet.objects.create(**validated_data)\n\n\n\nNote that these methods should return the newly created object instance.\n\n\n.object\n.\nUse \n.validated_data\n instead of \n\n\nYou must now use the \n.validated_data\n attribute if you need to inspect the data before saving, rather than using the \n.object\n attribute, which no longer exists.\n\n\nFor example the following code \nis no longer valid\n:\n\n\nif serializer.is_valid():\n    name = serializer.object.name  # Inspect validated field data.\n    logging.info('Creating ticket \"%s\"' % name)\n    serializer.object.user = request.user  # Include the user when saving.\n    serializer.save()\n\n\n\nInstead of using \n.object\n to inspect a partially constructed instance, you would now use \n.validated_data\n to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the \n.save()\n method as keyword arguments.\n\n\nThe corresponding code would now look like this:\n\n\nif serializer.is_valid():\n    name = serializer.validated_data['name']  # Inspect validated field data.\n    logging.info('Creating ticket \"%s\"' % name)\n    serializer.save(user=request.user)  # Include the user when saving.\n\n\n\nUsing \n.is_valid(raise_exception=True)\n\n\nThe \n.is_valid()\n method now takes an optional boolean flag, \nraise_exception\n.\n\n\nCalling \n.is_valid(raise_exception=True)\n will cause a \nValidationError\n 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.\n\n\nThe handling and formatting of error responses may be altered globally by using the \nEXCEPTION_HANDLER\n settings key.\n\n\nThis 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.\n\n\nUsing \nserializers.ValidationError\n.\n\n\nPreviously \nserializers.ValidationError\n error was simply a synonym for \ndjango.core.exceptions.ValidationError\n. This has now been altered so that it inherits from the standard \nAPIException\n base class.\n\n\nThe reason behind this is that Django's \nValidationError\n 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.\n\n\nFor 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 \nserializers.ValidationError\n exception class, and not Django's built-in exception.\n\n\nWe strongly recommend that you use the namespaced import style of \nimport serializers\n and not \nfrom serializers import ValidationError\n in order to avoid any potential confusion.\n\n\nChange to \nvalidate_\nfield_name\n.\n\n\nThe \nvalidate_\nfield_name\n 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:\n\n\ndef validate_score(self, attrs, source):\n    if attrs['score'] % 10 != 0:\n        raise serializers.ValidationError('This field should be a multiple of ten.')\n    return attrs\n\n\n\nThis is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.\n\n\ndef validate_score(self, value):\n    if value % 10 != 0:\n        raise serializers.ValidationError('This field should be a multiple of ten.')\n    return value\n\n\n\nAny ad-hoc validation that applies to more than one field should go in the \n.validate(self, attrs)\n method as usual.\n\n\nBecause \n.validate_\nfield_name\n would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use \n.validate()\n instead.\n\n\nYou can either return \nnon_field_errors\n from the validate method by raising a simple \nValidationError\n\n\ndef validate(self, attrs):\n    # serializer.errors == {'non_field_errors': ['A non field error']}\n    raise serializers.ValidationError('A non field error')\n\n\n\nAlternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the \nValidationError\n, like so:\n\n\ndef validate(self, attrs):\n    # serializer.errors == {'my_field': ['A field error']}\n    raise serializers.ValidationError({'my_field': 'A field error'})\n\n\n\nThis ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.\n\n\nRemoval of \ntransform_\nfield_name\n.\n\n\nThe under-used \ntransform_\nfield_name\n on serializer classes is no longer provided. Instead you should just override \nto_representation()\n if you need to apply any modifications to the representation style.\n\n\nFor example:\n\n\ndef to_representation(self, instance):\n    ret = super(UserSerializer, self).to_representation(instance)\n    ret['username'] = ret['username'].lower()\n    return ret\n\n\n\nDropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.\n\n\nIf you absolutely need to preserve \ntransform_\nfield_name\n behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:\n\n\nclass BaseModelSerializer(ModelSerializer):\n    \"\"\"\n    A custom ModelSerializer class that preserves 2.x style `transform_\nfield_name\n` behavior.\n    \"\"\"\n    def to_representation(self, instance):\n        ret = super(BaseModelSerializer, self).to_representation(instance)\n        for key, value in ret.items():\n            method = getattr(self, 'transform_' + key, None)\n            if method is not None:\n                ret[key] = method(value)\n        return ret\n\n\n\nDifferences between ModelSerializer validation and ModelForm.\n\n\nThis change also means that we no longer use the \n.full_clean()\n 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 \nModelSerializer\n classes that can't also be easily replicated on regular \nSerializer\n classes.\n\n\nFor 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.\n\n\nThe one difference that you do need to note is that the \n.clean()\n method will not be called as part of serializer validation, as it would be if using a \nModelForm\n. Use the serializer \n.validate()\n method to perform a final validation step on incoming data where required.\n\n\nThere may be some cases where you really do need to keep validation logic in the model \n.clean()\n method, and cannot instead separate it into the serializer \n.validate()\n. You can do so by explicitly instantiating a model instance in the \n.validate()\n method.\n\n\ndef validate(self, attrs):\n    instance = ExampleModel(**attrs)\n    instance.clean()\n    return attrs\n\n\n\nAgain, 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.\n\n\nWritable nested serialization.\n\n\nREST 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:\n\n\n\n\nThere can be complex dependencies involved in order of saving multiple related model instances.\n\n\nIt's unclear what behavior the user should expect when related models are passed \nNone\n data.\n\n\nIt's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.\n\n\n\n\nUsing the \ndepth\n option on \nModelSerializer\n will now create \nread-only nested serializers\n by default.\n\n\nIf you try to use a writable nested serializer without writing a custom \ncreate()\n and/or \nupdate()\n method you'll see an assertion error when you attempt to save the serializer. For example:\n\n\n class ProfileSerializer(serializers.ModelSerializer):\n\n     class Meta:\n\n         model = Profile\n\n         fields = ('address', 'phone')\n\n\n\n class UserSerializer(serializers.ModelSerializer):\n\n     profile = ProfileSerializer()\n\n     class Meta:\n\n         model = User\n\n         fields = ('username', 'email', 'profile')\n\n\n\n data = {\n\n     'username': 'lizzy',\n\n     'email': 'lizzy@example.com',\n\n     'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n\n }\n\n\n\n serializer = UserSerializer(data=data)\n\n serializer.save()\nAssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.\n\n\n\nTo use writable nested serialization you'll want to declare a nested field on the serializer class, and write the \ncreate()\n and/or \nupdate()\n methods explicitly.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n    profile = ProfileSerializer()\n\n    class Meta:\n        model = User\n        fields = ('username', 'email', 'profile')\n\n    def create(self, validated_data):\n        profile_data = validated_data.pop('profile')\n        user = User.objects.create(**validated_data)\n        Profile.objects.create(user=user, **profile_data)\n        return user\n\n\n\nThe single-step object creation makes this far simpler and more obvious than the previous \n.restore_object()\n behavior.\n\n\nPrintable serializer representations.\n\n\nSerializer instances now support a printable representation that allows you to inspect the fields present on the instance.\n\n\nFor instance, given the following example model:\n\n\nclass LocationRating(models.Model):\n    location = models.CharField(max_length=100)\n    rating = models.IntegerField()\n    created_by = models.ForeignKey(User)\n\n\n\nLet's create a simple \nModelSerializer\n class corresponding to the \nLocationRating\n model.\n\n\nclass LocationRatingSerializer(serializer.ModelSerializer):\n    class Meta:\n        model = LocationRating\n\n\n\nWe can now inspect the serializer representation in the Django shell, using \npython manage.py shell\n...\n\n\n serializer = LocationRatingSerializer()\n\n print(serializer)  # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    location = CharField(max_length=100)\n    rating = IntegerField()\n    created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nThe \nextra_kwargs\n option.\n\n\nThe \nwrite_only_fields\n option on \nModelSerializer\n has been moved to \nPendingDeprecation\n and replaced with a more generic \nextra_kwargs\n.\n\n\nclass MySerializer(serializer.ModelSerializer):\n    class Meta:\n        model = MyModel\n        fields = ('id', 'email', 'notes', 'is_admin')\n        extra_kwargs = {\n                'is_admin': {'write_only': True}\n        }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.ModelSerializer):\n    is_admin = serializers.BooleanField(write_only=True)\n\n    class Meta:\n        model = MyModel\n        fields = ('id', 'email', 'notes', 'is_admin')\n\n\n\nThe \nread_only_fields\n option remains as a convenient shortcut for the more common case.\n\n\nChanges to \nHyperlinkedModelSerializer\n.\n\n\nThe \nview_name\n and \nlookup_field\n options have been moved to \nPendingDeprecation\n. They are no longer required, as you can use the \nextra_kwargs\n argument instead:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n    class Meta:\n        model = MyModel\n        fields = ('url', 'email', 'notes', 'is_admin')\n        extra_kwargs = {\n            'url': {'lookup_field': 'uuid'}\n        }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n    url = serializers.HyperlinkedIdentityField(\n        view_name='mymodel-detail',\n        lookup_field='uuid'\n    )\n\n    class Meta:\n        model = MyModel\n        fields = ('url', 'email', 'notes', 'is_admin')\n\n\n\nFields for model methods and properties.\n\n\nWith \nModelSerializer\n you can now specify field names in the \nfields\n option that refer to model methods or properties. For example, suppose you have the following model:\n\n\nclass Invitation(models.Model):\n    created = models.DateTimeField()\n    to_email = models.EmailField()\n    message = models.CharField(max_length=1000)\n\n    def expiry_date(self):\n        return self.created + datetime.timedelta(days=30)\n\n\n\nYou can include \nexpiry_date\n as a field option on a \nModelSerializer\n class.\n\n\nclass InvitationSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Invitation\n        fields = ('to_email', 'message', 'expiry_date')\n\n\n\nThese fields will be mapped to \nserializers.ReadOnlyField()\n instances.\n\n\n serializer = InvitationSerializer()\n\n print repr(serializer)\nInvitationSerializer():\n    to_email = EmailField(max_length=75)\n    message = CharField(max_length=1000)\n    expiry_date = ReadOnlyField()\n\n\n\nThe \nListSerializer\n class.\n\n\nThe \nListSerializer\n class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.\n\n\nclass MultipleUserSerializer(ListSerializer):\n    child = UserSerializer()\n\n\n\nYou can also still use the \nmany=True\n argument to serializer classes. It's worth noting that \nmany=True\n argument transparently creates a \nListSerializer\n instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.\n\n\nYou will typically want to \ncontinue to use the existing \nmany=True\n flag\n rather than declaring \nListSerializer\n classes explicitly, but declaring the classes explicitly can be useful if you need to write custom \ncreate\n or \nupdate\n methods for bulk updates, or provide for other custom behavior.\n\n\nSee also the new \nListField\n class, which validates input in the same way, but does not include the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nBaseSerializer\n class.\n\n\nREST framework now includes a simple \nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns an errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class-based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes.\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    player_name = models.CharField(max_length=10)\n    score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n    instance = HighScore.objects.get(pk=pk)\n    serializer = HighScoreSerializer(instance)\n    return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n    queryset = HighScore.objects.order_by('-score')\n    serializer = HighScoreSerializer(queryset, many=True)\n    return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes.\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_internal_value(self, data):\n        score = data.get('score')\n        player_name = data.get('player_name')\n\n        # Perform the data validation.\n        if not score:\n            raise ValidationError({\n                'score': 'This field is required.'\n            })\n        if not player_name:\n            raise ValidationError({\n                'player_name': 'This field is required.'\n            })\n        if len(player_name) \n 10:\n            raise ValidationError({\n                'player_name': 'May not be more than 10 characters.'\n            })\n\n        # Return the validated values. This will be available as\n        # the `.validated_data` property.\n        return {\n            'score': int(score),\n            'player_name': player_name\n        }\n\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n    def create(self, validated_data):\n        return HighScore.objects.create(**validated_data)\n\n\n\nCreating new generic serializers with \nBaseSerializer\n.\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n    \"\"\"\n    A read-only serializer that coerces arbitrary complex objects\n    into primitive representations.\n    \"\"\"\n    def to_representation(self, obj):\n        for attribute_name in dir(obj):\n            attribute = getattr(obj, attribute_name)\n            if attribute_name('_'):\n                # Ignore private attributes.\n                pass\n            elif hasattr(attribute, '__call__'):\n                # Ignore methods and other callables.\n                pass\n            elif isinstance(attribute, (str, int, bool, float, type(None))):\n                # Primitive types can be passed through unmodified.\n                output[attribute_name] = attribute\n            elif isinstance(attribute, list):\n                # Recursively deal with items in lists.\n                output[attribute_name] = [\n                    self.to_representation(item) for item in attribute\n                ]\n            elif isinstance(attribute, dict):\n                # Recursively deal with items in dictionaries.\n                output[attribute_name] = {\n                    str(key): self.to_representation(value)\n                    for key, value in attribute.items()\n                }\n            else:\n                # Force anything else to its string representation.\n                output[attribute_name] = str(attribute)\n\n\n\n\n\nSerializer fields\n\n\nReadOnly\n field classes.\nThe \nField\n and \n\n\nThere are some minor tweaks to the field base classes.\n\n\nPreviously we had these two base classes:\n\n\n\n\nField\n as the base class for read-only fields. A default implementation was included for serializing data.\n\n\nWritableField\n as the base class for read-write fields.\n\n\n\n\nWe now use the following:\n\n\n\n\nField\n is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.\n\n\nReadOnlyField\n is a concrete implementation for read-only fields that simply returns the attribute value without modification.\n\n\n\n\nallow_null\n, \ndefault\n arguments.\nThe \nrequired\n, \nallow_blank\n and \n\n\nREST framework now has more explicit and clear control over validating empty values for fields.\n\n\nPreviously the meaning of the \nrequired=False\n 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 \nNone\n or the empty string.\n\n\nWe now have a better separation, with separate \nrequired\n, \nallow_null\n and \nallow_blank\n arguments.\n\n\nThe following set of arguments are used to control validation of empty values:\n\n\n\n\nrequired=False\n: The value does not need to be present in the input, and will not be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\ndefault=\nvalue\n: The value does not need to be present in the input, and a default value will be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\nallow_null=True\n: \nNone\n is a valid input.\n\n\nallow_blank=True\n: \n''\n is valid input. For \nCharField\n and subclasses only.\n\n\n\n\nTypically you'll want to use \nrequired=False\n if the corresponding model field has a default value, and additionally set either \nallow_null=True\n or \nallow_blank=True\n if required.\n\n\nThe \ndefault\n argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the \nrequired\n argument when a default is specified, and doing so will result in an error.\n\n\nCoercing output types.\n\n\nThe previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an \nIntegerField\n 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.\n\n\nRemoval of \n.validate()\n.\n\n\nThe \n.validate()\n method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override \nto_internal_value()\n.\n\n\nclass UppercaseCharField(serializers.CharField):\n    def to_internal_value(self, data):\n        value = super(UppercaseCharField, self).to_internal_value(data)\n        if value != value.upper():\n            raise serializers.ValidationError('The input should be uppercase only.')\n        return value\n\n\n\nPreviously validation errors could be raised in either \n.to_native()\n or \n.validate()\n, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.\n\n\nThe \nListField\n class.\n\n\nThe \nListField\n class has now been added. This field validates list input. It takes a \nchild\n keyword argument which is used to specify the field used to validate each item in the list. For example:\n\n\nscores = ListField(child=IntegerField(min_value=0, max_value=100))\n\n\n\nYou can also use a declarative style to create new subclasses of \nListField\n, like this:\n\n\nclass ScoresField(ListField):\n    child = IntegerField(min_value=0, max_value=100)\n\n\n\nWe can now use the \nScoresField\n class inside another serializer:\n\n\nscores = ScoresField()\n\n\n\nSee also the new \nListSerializer\n class, which validates input in the same way, but also includes the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nChoiceField\n class may now accept a flat list.\n\n\nThe \nChoiceField\n class may now accept a list of choices in addition to the existing style of using a list of pairs of \n(name, display_value)\n. The following is now valid:\n\n\ncolor = ChoiceField(choices=['red', 'green', 'blue'])\n\n\n\nThe \nMultipleChoiceField\n class.\n\n\nThe \nMultipleChoiceField\n class has been added. This field acts like \nChoiceField\n, but returns a set, which may include none, one or many of the valid choices.\n\n\nChanges to the custom field API.\n\n\nThe \nfrom_native(self, value)\n and \nto_native(self, data)\n method names have been replaced with the more obviously named \nto_internal_value(self, data)\n and \nto_representation(self, value)\n.\n\n\nThe \nfield_from_native()\n and \nfield_to_native()\n 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...\n\n\ndef field_to_native(self, obj, field_name):\n    \"\"\"A custom read-only field that returns the class name.\"\"\"\n    return obj.__class__.__name__\n\n\n\nNow if you need to access the entire object you'll instead need to override one or both of the following:\n\n\n\n\nUse \nget_attribute\n to modify the attribute value passed to \nto_representation()\n.\n\n\nUse \nget_value\n to modify the data value passed \nto_internal_value()\n.\n\n\n\n\nFor example:\n\n\ndef get_attribute(self, obj):\n    # Pass the entire object through to `to_representation()`,\n    # instead of the standard attribute lookup.\n    return obj\n\ndef to_representation(self, value):\n    return value.__class__.__name__\n\n\n\nExplicit \nqueryset\n required on relational fields.\n\n\nPreviously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a \nModelSerializer\n.\n\n\nThis code \nwould be valid\n in \n2.4.3\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    organizations = serializers.SlugRelatedField(slug_field='name')\n\n    class Meta:\n        model = Account\n\n\n\nHowever this code \nwould not be valid\n in \n3.0\n:\n\n\n# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n    organizations = serializers.SlugRelatedField(slug_field='name')\n\n    def restore_object(self, attrs, instance=None):\n        # ...\n\n\n\nThe queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit \nModelSerializer\n classes and explicit \nSerializer\n classes.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    organizations = serializers.SlugRelatedField(\n        slug_field='name',\n        queryset=Organization.objects.all()\n    )\n\n    class Meta:\n        model = Account\n\n\n\nThe \nqueryset\n argument is only ever required for writable fields, and is not required or valid for fields with \nread_only=True\n.\n\n\nOptional argument to \nSerializerMethodField\n.\n\n\nThe argument to \nSerializerMethodField\n is now optional, and defaults to \nget_\nfield_name\n. For example the following is valid:\n\n\nclass AccountSerializer(serializers.Serializer):\n    # `method_name='get_billing_details'` by default.\n    billing_details = serializers.SerializerMethodField()\n\n    def get_billing_details(self, account):\n        return calculate_billing(account)\n\n\n\nIn 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 \nwill raise an error\n:\n\n\nbilling_details = serializers.SerializerMethodField('get_billing_details')\n\n\n\nEnforcing consistent \nsource\n usage.\n\n\nI've see several codebases that unnecessarily include the \nsource\n argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that \nsource\n is usually not required.\n\n\nThe following usage will \nnow raise an error\n:\n\n\nemail = serializers.EmailField(source='email')\n\n\n\nUniqueTogetherValidator\n classes.\nThe \nUniqueValidator\n and \n\n\nREST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit \nSerializer\n class instead of using \nModelSerializer\n.\n\n\nThe \nUniqueValidator\n should be applied to a serializer field, and takes a single \nqueryset\n argument.\n\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n    url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n    created = serializers.DateTimeField(read_only=True)\n    name = serializers.CharField(\n        max_length=100,\n        validators=UniqueValidator(queryset=Organization.objects.all())\n    )\n\n\n\nThe \nUniqueTogetherValidator\n should be applied to a serializer, and takes a \nqueryset\n argument and a \nfields\n argument which should be a list or tuple of field names.\n\n\nclass RaceResultSerializer(serializers.Serializer):\n    category = serializers.ChoiceField(['5k', '10k'])\n    position = serializers.IntegerField()\n    name = serializers.CharField(max_length=100)\n\n    class Meta:\n        validators = [UniqueTogetherValidator(\n            queryset=RaceResult.objects.all(),\n            fields=('category', 'position')\n        )]\n\n\n\nThe \nUniqueForDateValidator\n classes.\n\n\nREST framework also now includes explicit validator classes for validating the \nunique_for_date\n, \nunique_for_month\n, and \nunique_for_year\n model field constraints. These are used internally instead of calling into \nModel.full_clean()\n.\n\n\nThese classes are documented in the \nValidators\n section of the documentation.\n\n\n\n\nGeneric views\n\n\nSimplification of view logic.\n\n\nThe view logic for the default method handlers has been significantly simplified, due to the new serializers API.\n\n\nChanges to pre/post save hooks.\n\n\nThe \npre_save\n and \npost_save\n hooks no longer exist, but are replaced with \nperform_create(self, serializer)\n and \nperform_update(self, serializer)\n.\n\n\nThese methods should save the object instance by calling \nserializer.save()\n, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.\n\n\nFor example:\n\n\ndef perform_create(self, serializer):\n    # Include the owner attribute directly, rather than from request data.\n    instance = serializer.save(owner=self.request.user)\n    # Perform a custom post-save action.\n    send_email(instance.to_email, instance.message)\n\n\n\nThe \npre_delete\n and \npost_delete\n hooks no longer exist, and are replaced with \n.perform_destroy(self, instance)\n, which should delete the instance and perform any custom actions.\n\n\ndef perform_destroy(self, instance):\n    # Perform a custom pre-delete action.\n    send_deletion_alert(user=instance.created_by, deleted=instance)\n    # Delete the object instance.\n    instance.delete()\n\n\n\nRemoval of view attributes.\n\n\nThe \n.object\n and \n.object_list\n 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.\n\n\nI would personally recommend that developers treat view instances as immutable objects in their application code.\n\n\nPUT as create.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to restore the previous behavior you may want to include \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\nCustomizing error responses.\n\n\nThe generic views now raise \nValidationFailed\n exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a \n400 Bad Request\n response directly.\n\n\nThis 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.\n\n\n\n\nThe metadata API\n\n\nBehavior for dealing with \nOPTIONS\n 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.\n\n\nThis makes it far easier to use a different style for \nOPTIONS\n responses throughout your API, and makes it possible to create third-party metadata policies.\n\n\n\n\nSerializers as HTML forms\n\n\nREST framework 3.0 includes templated HTML form rendering for serializers.\n\n\nThis API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.\n\n\nSignificant changes that you do need to be aware of include:\n\n\n\n\nNested HTML forms are now supported, for example, a \nUserSerializer\n with a nested \nProfileSerializer\n will now render a nested \nfieldset\n when used in the browsable API.\n\n\nNested lists of HTML forms are not yet supported, but are planned for 3.1.\n\n\nBecause we now use templated HTML form generation, \nthe \nwidget\n option is no longer available for serializer fields\n. You can instead control the template that is used for a given field, by using the \nstyle\n dictionary.\n\n\n\n\nThe \nstyle\n keyword argument for serializer fields.\n\n\nThe \nstyle\n keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the \nHTMLFormRenderer\n uses the \nbase_template\n key to determine which template to render the field with.\n\n\nFor example, to use a \ntextarea\n control instead of the default \ninput\n control, you would use the following\u2026\n\n\nadditional_notes = serializers.CharField(\n    style={'base_template': 'textarea.html'}\n)\n\n\n\nSimilarly, to use a radio button control instead of the default \nselect\n control, you would use the following\u2026\n\n\ncolor_channel = serializers.ChoiceField(\n    choices=['red', 'blue', 'green'],\n    style={'base_template': 'radio.html'}\n)\n\n\n\nThis API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.\n\n\n\n\nAPI style\n\n\nThere are some improvements in the default style we use in our API responses.\n\n\nUnicode JSON by default.\n\n\nUnicode JSON is now the default. The \nUnicodeJSONRenderer\n class no longer exists, and the \nUNICODE_JSON\n setting has been added. To revert this behavior use the new setting:\n\n\nREST_FRAMEWORK = {\n    'UNICODE_JSON': False\n}\n\n\n\nCompact JSON by default.\n\n\nWe now output compact JSON in responses by default. For example, we return:\n\n\n{\"email\":\"amy@example.com\",\"is_admin\":true}\n\n\n\nInstead of the following:\n\n\n{\"email\": \"amy@example.com\", \"is_admin\": true}\n\n\n\nThe \nCOMPACT_JSON\n setting has been added, and can be used to revert this behavior if needed:\n\n\nREST_FRAMEWORK = {\n    'COMPACT_JSON': False\n}\n\n\n\nFile fields as URLs\n\n\nThe \nFileField\n and \nImageField\n classes are now represented as URLs by default. You should ensure you set Django's \nstandard \nMEDIA_URL\n setting\n appropriately, and ensure your application \nserves the uploaded files\n.\n\n\nYou can revert this behavior, and display filenames in the representation by using the \nUPLOADED_FILES_USE_URL\n settings key:\n\n\nREST_FRAMEWORK = {\n    'UPLOADED_FILES_USE_URL': False\n}\n\n\n\nYou can also modify serializer fields individually, using the \nuse_url\n argument:\n\n\nuploaded_file = serializers.FileField(use_url=False)\n\n\n\nAlso note that you should pass the \nrequest\n object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form \nhttps://example.com/url_path/filename.txt\n. For example:\n\n\ncontext = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n\n\n\nIf the request is omitted from the context, the returned URLs will be of the form \n/url_path/filename.txt\n.\n\n\nThrottle headers using \nRetry-After\n.\n\n\nThe custom \nX-Throttle-Wait-Second\n header has now been dropped in favor of the standard \nRetry-After\n header. You can revert this behavior if needed by writing a custom exception handler for your application.\n\n\nDate and time objects as ISO-8859-1 strings in serializer data.\n\n\nDate and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as \nDate\n, \nTime\n and \nDateTime\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by settings the existing \nDATE_FORMAT\n, \nDATETIME_FORMAT\n and \nTIME_FORMAT\n settings keys. Setting these values to \nNone\n instead of their default value of \n'iso-8859-1'\n will result in native objects being returned in serializer data.\n\n\nREST_FRAMEWORK = {\n    # Return native `Date` and `Time` objects in `serializer.data`\n    'DATETIME_FORMAT': None\n    'DATE_FORMAT': None\n    'TIME_FORMAT': None\n}\n\n\n\nYou can also modify serializer fields individually, using the \ndate_format\n, \ntime_format\n and \ndatetime_format\n arguments:\n\n\n# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n\n\n\nDecimals as strings in serializer data.\n\n\nDecimals are now coerced to strings by default in the serializer output. Previously they were returned as \nDecimal\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by using the \nCOERCE_DECIMAL_TO_STRING\n settings key.\n\n\nREST_FRAMEWORK = {\n    'COERCE_DECIMAL_TO_STRING': False\n}\n\n\n\nOr modify it on an individual serializer field, using the \ncoerce_to_string\n keyword argument.\n\n\n# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n    max_digits=10,\n    decimal_places=2,\n    coerce_to_string=False\n)\n\n\n\nThe default JSON renderer will return float objects for un-coerced \nDecimal\n instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.\n\n\n\n\nMiscellaneous notes\n\n\n\n\nThe serializer \nChoiceField\n does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.\n\n\nDue 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.\n\n\nSome of the default validation error messages were rewritten and might no longer be pre-translated. You can still \ncreate language files with Django\n if you wish to localize them.\n\n\nAPIException\n subclasses could previously take any arbitrary type in the \ndetail\n argument. These exceptions now use translatable text strings, and as a result call \nforce_text\n on the \ndetail\n argument, which \nmust be a string\n. If you need complex arguments to an \nAPIException\n class, you should subclass it and override the \n__init__()\n method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.\n\n\n\n\n\n\nWhat's coming next\n\n\n3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.\n\n\nThe 3.1 release is planned to address improvements in the following components:\n\n\n\n\nPublic API for using serializers as HTML forms.\n\n\nRequest parsing, mediatypes \n the implementation of the browsable API.\n\n\nIntroduction of a new pagination API.\n\n\nBetter support for API versioning.\n\n\n\n\nThe 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.\n\n\nYou can follow development on the GitHub site, where we use \nmilestones to indicate planning timescales\n.", 
    +            "text": "Django REST framework 3.0\n\n\nThe 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.\n\n\nThis release is incremental in nature. There \nare\n some breaking API changes, and upgrading \nwill\n require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.\n\n\nThe difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.\n\n\n3.0 is the first of three releases that have been funded by our recent \nKickstarter campaign\n.\n\n\nAs ever, a huge thank you to our many \nwonderful sponsors\n. 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.\n\n\n\n\nNew features\n\n\nNotable features of this new release include:\n\n\n\n\nPrintable representations on serializers that allow you to inspect exactly what fields are present on the instance.\n\n\nSimple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit \nModelSerializer\n class and the explicit \nSerializer\n class.\n\n\nA new \nBaseSerializer\n class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.\n\n\nA cleaner fields API including new classes such as \nListField\n and \nMultipleChoiceField\n.\n\n\nSuper simple default implementations\n for the generic views.\n\n\nSupport for overriding how validation errors are handled by your API.\n\n\nA metadata API that allows you to customize how \nOPTIONS\n requests are handled by your API.\n\n\nA more compact JSON output with unicode style encoding turned on by default.\n\n\nTemplated based HTML form rendering for serializers. This will be finalized as  public API in the upcoming 3.1 release.\n\n\n\n\nSignificant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two \nKickstarter stretch goals\n - \"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.\n\n\n\n\nREST framework: Under the hood.\n\n\nThis talk from the \nDjango: Under the Hood\n event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.\n\n\n\n\n\n\n\nBelow is an in-depth guide to the API changes and migration notes for 3.0.\n\n\nRequest objects\n\n\nThe \n.data\n and \n.query_params\n properties.\n\n\nThe usage of \nrequest.DATA\n and \nrequest.FILES\n is now pending deprecation in favor of a single \nrequest.data\n attribute that contains \nall\n the parsed data.\n\n\nHaving 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.\n\n\nYou may now pass all the request data to a serializer class in a single argument:\n\n\n# Do this...\nExampleSerializer(data=request.data)\n\n\n\nInstead of passing the files argument separately:\n\n\n# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n\n\n\nThe usage of \nrequest.QUERY_PARAMS\n is now pending deprecation in favor of the lowercased \nrequest.query_params\n.\n\n\n\n\nSerializers\n\n\nSingle-step object creation.\n\n\nPreviously the serializers used a two-step object creation, as follows:\n\n\n\n\nValidating the data would create an object instance. This instance would be available as \nserializer.object\n.\n\n\nCalling \nserializer.save()\n would then save the object instance to the database.\n\n\n\n\nThis style is in-line with how the \nModelForm\n class works in Django, but is problematic for a number of reasons:\n\n\n\n\nSome data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when \n.save()\n is called.\n\n\nInstantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. \nExampleModel.objects.create(...)\n. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.\n\n\nThe two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?\n\n\n\n\nWe now use single-step object creation, like so:\n\n\n\n\nValidating the data makes the cleaned data available as \nserializer.validated_data\n.\n\n\nCalling \nserializer.save()\n then saves and returns the new object instance.\n\n\n\n\nThe resulting API changes are further detailed below.\n\n\nThe \n.create()\n and \n.update()\n methods.\n\n\nThe \n.restore_object()\n method is now removed, and we instead have two separate methods, \n.create()\n and \n.update()\n. These methods work slightly different to the previous \n.restore_object()\n.\n\n\nWhen using the \n.create()\n and \n.update()\n methods you should both create \nand save\n the object instance. This is in contrast to the previous \n.restore_object()\n behavior that would instantiate the object but not save it.\n\n\nThese methods also replace the optional \n.save_object()\n method, which no longer exists.\n\n\nThe following example from the tutorial previously used \nrestore_object()\n to handle both creating and updating object instances.\n\n\ndef restore_object(self, attrs, instance=None):\n    if instance:\n        # Update existing instance\n        instance.title = attrs.get('title', instance.title)\n        instance.code = attrs.get('code', instance.code)\n        instance.linenos = attrs.get('linenos', instance.linenos)\n        instance.language = attrs.get('language', instance.language)\n        instance.style = attrs.get('style', instance.style)\n        return instance\n\n    # Create new instance\n    return Snippet(**attrs)\n\n\n\nThis would now be split out into two separate methods.\n\n\ndef update(self, instance, validated_data):\n    instance.title = validated_data.get('title', instance.title)\n    instance.code = validated_data.get('code', instance.code)\n    instance.linenos = validated_data.get('linenos', instance.linenos)\n    instance.language = validated_data.get('language', instance.language)\n    instance.style = validated_data.get('style', instance.style)\n    instance.save()\n    return instance\n\ndef create(self, validated_data):\n    return Snippet.objects.create(**validated_data)\n\n\n\nNote that these methods should return the newly created object instance.\n\n\nUse \n.validated_data\n instead of \n.object\n.\n\n\nYou must now use the \n.validated_data\n attribute if you need to inspect the data before saving, rather than using the \n.object\n attribute, which no longer exists.\n\n\nFor example the following code \nis no longer valid\n:\n\n\nif serializer.is_valid():\n    name = serializer.object.name  # Inspect validated field data.\n    logging.info('Creating ticket \"%s\"' % name)\n    serializer.object.user = request.user  # Include the user when saving.\n    serializer.save()\n\n\n\nInstead of using \n.object\n to inspect a partially constructed instance, you would now use \n.validated_data\n to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the \n.save()\n method as keyword arguments.\n\n\nThe corresponding code would now look like this:\n\n\nif serializer.is_valid():\n    name = serializer.validated_data['name']  # Inspect validated field data.\n    logging.info('Creating ticket \"%s\"' % name)\n    serializer.save(user=request.user)  # Include the user when saving.\n\n\n\nUsing \n.is_valid(raise_exception=True)\n\n\nThe \n.is_valid()\n method now takes an optional boolean flag, \nraise_exception\n.\n\n\nCalling \n.is_valid(raise_exception=True)\n will cause a \nValidationError\n 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.\n\n\nThe handling and formatting of error responses may be altered globally by using the \nEXCEPTION_HANDLER\n settings key.\n\n\nThis 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.\n\n\nUsing \nserializers.ValidationError\n.\n\n\nPreviously \nserializers.ValidationError\n error was simply a synonym for \ndjango.core.exceptions.ValidationError\n. This has now been altered so that it inherits from the standard \nAPIException\n base class.\n\n\nThe reason behind this is that Django's \nValidationError\n 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.\n\n\nFor 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 \nserializers.ValidationError\n exception class, and not Django's built-in exception.\n\n\nWe strongly recommend that you use the namespaced import style of \nimport serializers\n and not \nfrom serializers import ValidationError\n in order to avoid any potential confusion.\n\n\nChange to \nvalidate_\nfield_name\n.\n\n\nThe \nvalidate_\nfield_name\n 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:\n\n\ndef validate_score(self, attrs, source):\n    if attrs['score'] % 10 != 0:\n        raise serializers.ValidationError('This field should be a multiple of ten.')\n    return attrs\n\n\n\nThis is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.\n\n\ndef validate_score(self, value):\n    if value % 10 != 0:\n        raise serializers.ValidationError('This field should be a multiple of ten.')\n    return value\n\n\n\nAny ad-hoc validation that applies to more than one field should go in the \n.validate(self, attrs)\n method as usual.\n\n\nBecause \n.validate_\nfield_name\n would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use \n.validate()\n instead.\n\n\nYou can either return \nnon_field_errors\n from the validate method by raising a simple \nValidationError\n\n\ndef validate(self, attrs):\n    # serializer.errors == {'non_field_errors': ['A non field error']}\n    raise serializers.ValidationError('A non field error')\n\n\n\nAlternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the \nValidationError\n, like so:\n\n\ndef validate(self, attrs):\n    # serializer.errors == {'my_field': ['A field error']}\n    raise serializers.ValidationError({'my_field': 'A field error'})\n\n\n\nThis ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.\n\n\nRemoval of \ntransform_\nfield_name\n.\n\n\nThe under-used \ntransform_\nfield_name\n on serializer classes is no longer provided. Instead you should just override \nto_representation()\n if you need to apply any modifications to the representation style.\n\n\nFor example:\n\n\ndef to_representation(self, instance):\n    ret = super(UserSerializer, self).to_representation(instance)\n    ret['username'] = ret['username'].lower()\n    return ret\n\n\n\nDropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.\n\n\nIf you absolutely need to preserve \ntransform_\nfield_name\n behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:\n\n\nclass BaseModelSerializer(ModelSerializer):\n    \"\"\"\n    A custom ModelSerializer class that preserves 2.x style `transform_\nfield_name\n` behavior.\n    \"\"\"\n    def to_representation(self, instance):\n        ret = super(BaseModelSerializer, self).to_representation(instance)\n        for key, value in ret.items():\n            method = getattr(self, 'transform_' + key, None)\n            if method is not None:\n                ret[key] = method(value)\n        return ret\n\n\n\nDifferences between ModelSerializer validation and ModelForm.\n\n\nThis change also means that we no longer use the \n.full_clean()\n 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 \nModelSerializer\n classes that can't also be easily replicated on regular \nSerializer\n classes.\n\n\nFor 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.\n\n\nThe one difference that you do need to note is that the \n.clean()\n method will not be called as part of serializer validation, as it would be if using a \nModelForm\n. Use the serializer \n.validate()\n method to perform a final validation step on incoming data where required.\n\n\nThere may be some cases where you really do need to keep validation logic in the model \n.clean()\n method, and cannot instead separate it into the serializer \n.validate()\n. You can do so by explicitly instantiating a model instance in the \n.validate()\n method.\n\n\ndef validate(self, attrs):\n    instance = ExampleModel(**attrs)\n    instance.clean()\n    return attrs\n\n\n\nAgain, 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.\n\n\nWritable nested serialization.\n\n\nREST 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:\n\n\n\n\nThere can be complex dependencies involved in order of saving multiple related model instances.\n\n\nIt's unclear what behavior the user should expect when related models are passed \nNone\n data.\n\n\nIt's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.\n\n\n\n\nUsing the \ndepth\n option on \nModelSerializer\n will now create \nread-only nested serializers\n by default.\n\n\nIf you try to use a writable nested serializer without writing a custom \ncreate()\n and/or \nupdate()\n method you'll see an assertion error when you attempt to save the serializer. For example:\n\n\n class ProfileSerializer(serializers.ModelSerializer):\n\n     class Meta:\n\n         model = Profile\n\n         fields = ('address', 'phone')\n\n\n\n class UserSerializer(serializers.ModelSerializer):\n\n     profile = ProfileSerializer()\n\n     class Meta:\n\n         model = User\n\n         fields = ('username', 'email', 'profile')\n\n\n\n data = {\n\n     'username': 'lizzy',\n\n     'email': 'lizzy@example.com',\n\n     'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n\n }\n\n\n\n serializer = UserSerializer(data=data)\n\n serializer.save()\nAssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.\n\n\n\nTo use writable nested serialization you'll want to declare a nested field on the serializer class, and write the \ncreate()\n and/or \nupdate()\n methods explicitly.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n    profile = ProfileSerializer()\n\n    class Meta:\n        model = User\n        fields = ('username', 'email', 'profile')\n\n    def create(self, validated_data):\n        profile_data = validated_data.pop('profile')\n        user = User.objects.create(**validated_data)\n        Profile.objects.create(user=user, **profile_data)\n        return user\n\n\n\nThe single-step object creation makes this far simpler and more obvious than the previous \n.restore_object()\n behavior.\n\n\nPrintable serializer representations.\n\n\nSerializer instances now support a printable representation that allows you to inspect the fields present on the instance.\n\n\nFor instance, given the following example model:\n\n\nclass LocationRating(models.Model):\n    location = models.CharField(max_length=100)\n    rating = models.IntegerField()\n    created_by = models.ForeignKey(User)\n\n\n\nLet's create a simple \nModelSerializer\n class corresponding to the \nLocationRating\n model.\n\n\nclass LocationRatingSerializer(serializer.ModelSerializer):\n    class Meta:\n        model = LocationRating\n\n\n\nWe can now inspect the serializer representation in the Django shell, using \npython manage.py shell\n...\n\n\n serializer = LocationRatingSerializer()\n\n print(serializer)  # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n    id = IntegerField(label='ID', read_only=True)\n    location = CharField(max_length=100)\n    rating = IntegerField()\n    created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nThe \nextra_kwargs\n option.\n\n\nThe \nwrite_only_fields\n option on \nModelSerializer\n has been moved to \nPendingDeprecation\n and replaced with a more generic \nextra_kwargs\n.\n\n\nclass MySerializer(serializer.ModelSerializer):\n    class Meta:\n        model = MyModel\n        fields = ('id', 'email', 'notes', 'is_admin')\n        extra_kwargs = {\n                'is_admin': {'write_only': True}\n        }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.ModelSerializer):\n    is_admin = serializers.BooleanField(write_only=True)\n\n    class Meta:\n        model = MyModel\n        fields = ('id', 'email', 'notes', 'is_admin')\n\n\n\nThe \nread_only_fields\n option remains as a convenient shortcut for the more common case.\n\n\nChanges to \nHyperlinkedModelSerializer\n.\n\n\nThe \nview_name\n and \nlookup_field\n options have been moved to \nPendingDeprecation\n. They are no longer required, as you can use the \nextra_kwargs\n argument instead:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n    class Meta:\n        model = MyModel\n        fields = ('url', 'email', 'notes', 'is_admin')\n        extra_kwargs = {\n            'url': {'lookup_field': 'uuid'}\n        }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n    url = serializers.HyperlinkedIdentityField(\n        view_name='mymodel-detail',\n        lookup_field='uuid'\n    )\n\n    class Meta:\n        model = MyModel\n        fields = ('url', 'email', 'notes', 'is_admin')\n\n\n\nFields for model methods and properties.\n\n\nWith \nModelSerializer\n you can now specify field names in the \nfields\n option that refer to model methods or properties. For example, suppose you have the following model:\n\n\nclass Invitation(models.Model):\n    created = models.DateTimeField()\n    to_email = models.EmailField()\n    message = models.CharField(max_length=1000)\n\n    def expiry_date(self):\n        return self.created + datetime.timedelta(days=30)\n\n\n\nYou can include \nexpiry_date\n as a field option on a \nModelSerializer\n class.\n\n\nclass InvitationSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Invitation\n        fields = ('to_email', 'message', 'expiry_date')\n\n\n\nThese fields will be mapped to \nserializers.ReadOnlyField()\n instances.\n\n\n serializer = InvitationSerializer()\n\n print repr(serializer)\nInvitationSerializer():\n    to_email = EmailField(max_length=75)\n    message = CharField(max_length=1000)\n    expiry_date = ReadOnlyField()\n\n\n\nThe \nListSerializer\n class.\n\n\nThe \nListSerializer\n class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.\n\n\nclass MultipleUserSerializer(ListSerializer):\n    child = UserSerializer()\n\n\n\nYou can also still use the \nmany=True\n argument to serializer classes. It's worth noting that \nmany=True\n argument transparently creates a \nListSerializer\n instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.\n\n\nYou will typically want to \ncontinue to use the existing \nmany=True\n flag\n rather than declaring \nListSerializer\n classes explicitly, but declaring the classes explicitly can be useful if you need to write custom \ncreate\n or \nupdate\n methods for bulk updates, or provide for other custom behavior.\n\n\nSee also the new \nListField\n class, which validates input in the same way, but does not include the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nBaseSerializer\n class.\n\n\nREST framework now includes a simple \nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns an errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class-based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes.\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n    created = models.DateTimeField(auto_now_add=True)\n    player_name = models.CharField(max_length=10)\n    score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n    instance = HighScore.objects.get(pk=pk)\n    serializer = HighScoreSerializer(instance)\n    return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n    queryset = HighScore.objects.order_by('-score')\n    serializer = HighScoreSerializer(queryset, many=True)\n    return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes.\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n    def to_internal_value(self, data):\n        score = data.get('score')\n        player_name = data.get('player_name')\n\n        # Perform the data validation.\n        if not score:\n            raise ValidationError({\n                'score': 'This field is required.'\n            })\n        if not player_name:\n            raise ValidationError({\n                'player_name': 'This field is required.'\n            })\n        if len(player_name) \n 10:\n            raise ValidationError({\n                'player_name': 'May not be more than 10 characters.'\n            })\n\n        # Return the validated values. This will be available as\n        # the `.validated_data` property.\n        return {\n            'score': int(score),\n            'player_name': player_name\n        }\n\n    def to_representation(self, obj):\n        return {\n            'score': obj.score,\n            'player_name': obj.player_name\n        }\n\n    def create(self, validated_data):\n        return HighScore.objects.create(**validated_data)\n\n\n\nCreating new generic serializers with \nBaseSerializer\n.\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n    \"\"\"\n    A read-only serializer that coerces arbitrary complex objects\n    into primitive representations.\n    \"\"\"\n    def to_representation(self, obj):\n        for attribute_name in dir(obj):\n            attribute = getattr(obj, attribute_name)\n            if attribute_name('_'):\n                # Ignore private attributes.\n                pass\n            elif hasattr(attribute, '__call__'):\n                # Ignore methods and other callables.\n                pass\n            elif isinstance(attribute, (str, int, bool, float, type(None))):\n                # Primitive types can be passed through unmodified.\n                output[attribute_name] = attribute\n            elif isinstance(attribute, list):\n                # Recursively deal with items in lists.\n                output[attribute_name] = [\n                    self.to_representation(item) for item in attribute\n                ]\n            elif isinstance(attribute, dict):\n                # Recursively deal with items in dictionaries.\n                output[attribute_name] = {\n                    str(key): self.to_representation(value)\n                    for key, value in attribute.items()\n                }\n            else:\n                # Force anything else to its string representation.\n                output[attribute_name] = str(attribute)\n\n\n\n\n\nSerializer fields\n\n\nThe \nField\n and \nReadOnly\n field classes.\n\n\nThere are some minor tweaks to the field base classes.\n\n\nPreviously we had these two base classes:\n\n\n\n\nField\n as the base class for read-only fields. A default implementation was included for serializing data.\n\n\nWritableField\n as the base class for read-write fields.\n\n\n\n\nWe now use the following:\n\n\n\n\nField\n is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.\n\n\nReadOnlyField\n is a concrete implementation for read-only fields that simply returns the attribute value without modification.\n\n\n\n\nThe \nrequired\n, \nallow_null\n, \nallow_blank\n and \ndefault\n arguments.\n\n\nREST framework now has more explicit and clear control over validating empty values for fields.\n\n\nPreviously the meaning of the \nrequired=False\n 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 \nNone\n or the empty string.\n\n\nWe now have a better separation, with separate \nrequired\n, \nallow_null\n and \nallow_blank\n arguments.\n\n\nThe following set of arguments are used to control validation of empty values:\n\n\n\n\nrequired=False\n: The value does not need to be present in the input, and will not be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\ndefault=\nvalue\n: The value does not need to be present in the input, and a default value will be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\nallow_null=True\n: \nNone\n is a valid input.\n\n\nallow_blank=True\n: \n''\n is valid input. For \nCharField\n and subclasses only.\n\n\n\n\nTypically you'll want to use \nrequired=False\n if the corresponding model field has a default value, and additionally set either \nallow_null=True\n or \nallow_blank=True\n if required.\n\n\nThe \ndefault\n argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the \nrequired\n argument when a default is specified, and doing so will result in an error.\n\n\nCoercing output types.\n\n\nThe previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an \nIntegerField\n 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.\n\n\nRemoval of \n.validate()\n.\n\n\nThe \n.validate()\n method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override \nto_internal_value()\n.\n\n\nclass UppercaseCharField(serializers.CharField):\n    def to_internal_value(self, data):\n        value = super(UppercaseCharField, self).to_internal_value(data)\n        if value != value.upper():\n            raise serializers.ValidationError('The input should be uppercase only.')\n        return value\n\n\n\nPreviously validation errors could be raised in either \n.to_native()\n or \n.validate()\n, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.\n\n\nThe \nListField\n class.\n\n\nThe \nListField\n class has now been added. This field validates list input. It takes a \nchild\n keyword argument which is used to specify the field used to validate each item in the list. For example:\n\n\nscores = ListField(child=IntegerField(min_value=0, max_value=100))\n\n\n\nYou can also use a declarative style to create new subclasses of \nListField\n, like this:\n\n\nclass ScoresField(ListField):\n    child = IntegerField(min_value=0, max_value=100)\n\n\n\nWe can now use the \nScoresField\n class inside another serializer:\n\n\nscores = ScoresField()\n\n\n\nSee also the new \nListSerializer\n class, which validates input in the same way, but also includes the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nChoiceField\n class may now accept a flat list.\n\n\nThe \nChoiceField\n class may now accept a list of choices in addition to the existing style of using a list of pairs of \n(name, display_value)\n. The following is now valid:\n\n\ncolor = ChoiceField(choices=['red', 'green', 'blue'])\n\n\n\nThe \nMultipleChoiceField\n class.\n\n\nThe \nMultipleChoiceField\n class has been added. This field acts like \nChoiceField\n, but returns a set, which may include none, one or many of the valid choices.\n\n\nChanges to the custom field API.\n\n\nThe \nfrom_native(self, value)\n and \nto_native(self, data)\n method names have been replaced with the more obviously named \nto_internal_value(self, data)\n and \nto_representation(self, value)\n.\n\n\nThe \nfield_from_native()\n and \nfield_to_native()\n 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...\n\n\ndef field_to_native(self, obj, field_name):\n    \"\"\"A custom read-only field that returns the class name.\"\"\"\n    return obj.__class__.__name__\n\n\n\nNow if you need to access the entire object you'll instead need to override one or both of the following:\n\n\n\n\nUse \nget_attribute\n to modify the attribute value passed to \nto_representation()\n.\n\n\nUse \nget_value\n to modify the data value passed \nto_internal_value()\n.\n\n\n\n\nFor example:\n\n\ndef get_attribute(self, obj):\n    # Pass the entire object through to `to_representation()`,\n    # instead of the standard attribute lookup.\n    return obj\n\ndef to_representation(self, value):\n    return value.__class__.__name__\n\n\n\nExplicit \nqueryset\n required on relational fields.\n\n\nPreviously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a \nModelSerializer\n.\n\n\nThis code \nwould be valid\n in \n2.4.3\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    organizations = serializers.SlugRelatedField(slug_field='name')\n\n    class Meta:\n        model = Account\n\n\n\nHowever this code \nwould not be valid\n in \n3.0\n:\n\n\n# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n    organizations = serializers.SlugRelatedField(slug_field='name')\n\n    def restore_object(self, attrs, instance=None):\n        # ...\n\n\n\nThe queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit \nModelSerializer\n classes and explicit \nSerializer\n classes.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n    organizations = serializers.SlugRelatedField(\n        slug_field='name',\n        queryset=Organization.objects.all()\n    )\n\n    class Meta:\n        model = Account\n\n\n\nThe \nqueryset\n argument is only ever required for writable fields, and is not required or valid for fields with \nread_only=True\n.\n\n\nOptional argument to \nSerializerMethodField\n.\n\n\nThe argument to \nSerializerMethodField\n is now optional, and defaults to \nget_\nfield_name\n. For example the following is valid:\n\n\nclass AccountSerializer(serializers.Serializer):\n    # `method_name='get_billing_details'` by default.\n    billing_details = serializers.SerializerMethodField()\n\n    def get_billing_details(self, account):\n        return calculate_billing(account)\n\n\n\nIn 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 \nwill raise an error\n:\n\n\nbilling_details = serializers.SerializerMethodField('get_billing_details')\n\n\n\nEnforcing consistent \nsource\n usage.\n\n\nI've see several codebases that unnecessarily include the \nsource\n argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that \nsource\n is usually not required.\n\n\nThe following usage will \nnow raise an error\n:\n\n\nemail = serializers.EmailField(source='email')\n\n\n\nThe \nUniqueValidator\n and \nUniqueTogetherValidator\n classes.\n\n\nREST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit \nSerializer\n class instead of using \nModelSerializer\n.\n\n\nThe \nUniqueValidator\n should be applied to a serializer field, and takes a single \nqueryset\n argument.\n\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n    url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n    created = serializers.DateTimeField(read_only=True)\n    name = serializers.CharField(\n        max_length=100,\n        validators=UniqueValidator(queryset=Organization.objects.all())\n    )\n\n\n\nThe \nUniqueTogetherValidator\n should be applied to a serializer, and takes a \nqueryset\n argument and a \nfields\n argument which should be a list or tuple of field names.\n\n\nclass RaceResultSerializer(serializers.Serializer):\n    category = serializers.ChoiceField(['5k', '10k'])\n    position = serializers.IntegerField()\n    name = serializers.CharField(max_length=100)\n\n    class Meta:\n        validators = [UniqueTogetherValidator(\n            queryset=RaceResult.objects.all(),\n            fields=('category', 'position')\n        )]\n\n\n\nThe \nUniqueForDateValidator\n classes.\n\n\nREST framework also now includes explicit validator classes for validating the \nunique_for_date\n, \nunique_for_month\n, and \nunique_for_year\n model field constraints. These are used internally instead of calling into \nModel.full_clean()\n.\n\n\nThese classes are documented in the \nValidators\n section of the documentation.\n\n\n\n\nGeneric views\n\n\nSimplification of view logic.\n\n\nThe view logic for the default method handlers has been significantly simplified, due to the new serializers API.\n\n\nChanges to pre/post save hooks.\n\n\nThe \npre_save\n and \npost_save\n hooks no longer exist, but are replaced with \nperform_create(self, serializer)\n and \nperform_update(self, serializer)\n.\n\n\nThese methods should save the object instance by calling \nserializer.save()\n, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.\n\n\nFor example:\n\n\ndef perform_create(self, serializer):\n    # Include the owner attribute directly, rather than from request data.\n    instance = serializer.save(owner=self.request.user)\n    # Perform a custom post-save action.\n    send_email(instance.to_email, instance.message)\n\n\n\nThe \npre_delete\n and \npost_delete\n hooks no longer exist, and are replaced with \n.perform_destroy(self, instance)\n, which should delete the instance and perform any custom actions.\n\n\ndef perform_destroy(self, instance):\n    # Perform a custom pre-delete action.\n    send_deletion_alert(user=instance.created_by, deleted=instance)\n    # Delete the object instance.\n    instance.delete()\n\n\n\nRemoval of view attributes.\n\n\nThe \n.object\n and \n.object_list\n 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.\n\n\nI would personally recommend that developers treat view instances as immutable objects in their application code.\n\n\nPUT as create.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to restore the previous behavior you may want to include \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\nCustomizing error responses.\n\n\nThe generic views now raise \nValidationFailed\n exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a \n400 Bad Request\n response directly.\n\n\nThis 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.\n\n\n\n\nThe metadata API\n\n\nBehavior for dealing with \nOPTIONS\n 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.\n\n\nThis makes it far easier to use a different style for \nOPTIONS\n responses throughout your API, and makes it possible to create third-party metadata policies.\n\n\n\n\nSerializers as HTML forms\n\n\nREST framework 3.0 includes templated HTML form rendering for serializers.\n\n\nThis API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.\n\n\nSignificant changes that you do need to be aware of include:\n\n\n\n\nNested HTML forms are now supported, for example, a \nUserSerializer\n with a nested \nProfileSerializer\n will now render a nested \nfieldset\n when used in the browsable API.\n\n\nNested lists of HTML forms are not yet supported, but are planned for 3.1.\n\n\nBecause we now use templated HTML form generation, \nthe \nwidget\n option is no longer available for serializer fields\n. You can instead control the template that is used for a given field, by using the \nstyle\n dictionary.\n\n\n\n\nThe \nstyle\n keyword argument for serializer fields.\n\n\nThe \nstyle\n keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the \nHTMLFormRenderer\n uses the \nbase_template\n key to determine which template to render the field with.\n\n\nFor example, to use a \ntextarea\n control instead of the default \ninput\n control, you would use the following\u2026\n\n\nadditional_notes = serializers.CharField(\n    style={'base_template': 'textarea.html'}\n)\n\n\n\nSimilarly, to use a radio button control instead of the default \nselect\n control, you would use the following\u2026\n\n\ncolor_channel = serializers.ChoiceField(\n    choices=['red', 'blue', 'green'],\n    style={'base_template': 'radio.html'}\n)\n\n\n\nThis API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.\n\n\n\n\nAPI style\n\n\nThere are some improvements in the default style we use in our API responses.\n\n\nUnicode JSON by default.\n\n\nUnicode JSON is now the default. The \nUnicodeJSONRenderer\n class no longer exists, and the \nUNICODE_JSON\n setting has been added. To revert this behavior use the new setting:\n\n\nREST_FRAMEWORK = {\n    'UNICODE_JSON': False\n}\n\n\n\nCompact JSON by default.\n\n\nWe now output compact JSON in responses by default. For example, we return:\n\n\n{\"email\":\"amy@example.com\",\"is_admin\":true}\n\n\n\nInstead of the following:\n\n\n{\"email\": \"amy@example.com\", \"is_admin\": true}\n\n\n\nThe \nCOMPACT_JSON\n setting has been added, and can be used to revert this behavior if needed:\n\n\nREST_FRAMEWORK = {\n    'COMPACT_JSON': False\n}\n\n\n\nFile fields as URLs\n\n\nThe \nFileField\n and \nImageField\n classes are now represented as URLs by default. You should ensure you set Django's \nstandard \nMEDIA_URL\n setting\n appropriately, and ensure your application \nserves the uploaded files\n.\n\n\nYou can revert this behavior, and display filenames in the representation by using the \nUPLOADED_FILES_USE_URL\n settings key:\n\n\nREST_FRAMEWORK = {\n    'UPLOADED_FILES_USE_URL': False\n}\n\n\n\nYou can also modify serializer fields individually, using the \nuse_url\n argument:\n\n\nuploaded_file = serializers.FileField(use_url=False)\n\n\n\nAlso note that you should pass the \nrequest\n object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form \nhttps://example.com/url_path/filename.txt\n. For example:\n\n\ncontext = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n\n\n\nIf the request is omitted from the context, the returned URLs will be of the form \n/url_path/filename.txt\n.\n\n\nThrottle headers using \nRetry-After\n.\n\n\nThe custom \nX-Throttle-Wait-Second\n header has now been dropped in favor of the standard \nRetry-After\n header. You can revert this behavior if needed by writing a custom exception handler for your application.\n\n\nDate and time objects as ISO-8859-1 strings in serializer data.\n\n\nDate and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as \nDate\n, \nTime\n and \nDateTime\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by settings the existing \nDATE_FORMAT\n, \nDATETIME_FORMAT\n and \nTIME_FORMAT\n settings keys. Setting these values to \nNone\n instead of their default value of \n'iso-8859-1'\n will result in native objects being returned in serializer data.\n\n\nREST_FRAMEWORK = {\n    # Return native `Date` and `Time` objects in `serializer.data`\n    'DATETIME_FORMAT': None\n    'DATE_FORMAT': None\n    'TIME_FORMAT': None\n}\n\n\n\nYou can also modify serializer fields individually, using the \ndate_format\n, \ntime_format\n and \ndatetime_format\n arguments:\n\n\n# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n\n\n\nDecimals as strings in serializer data.\n\n\nDecimals are now coerced to strings by default in the serializer output. Previously they were returned as \nDecimal\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by using the \nCOERCE_DECIMAL_TO_STRING\n settings key.\n\n\nREST_FRAMEWORK = {\n    'COERCE_DECIMAL_TO_STRING': False\n}\n\n\n\nOr modify it on an individual serializer field, using the \ncoerce_to_string\n keyword argument.\n\n\n# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n    max_digits=10,\n    decimal_places=2,\n    coerce_to_string=False\n)\n\n\n\nThe default JSON renderer will return float objects for un-coerced \nDecimal\n instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.\n\n\n\n\nMiscellaneous notes\n\n\n\n\nThe serializer \nChoiceField\n does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.\n\n\nDue 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.\n\n\nSome of the default validation error messages were rewritten and might no longer be pre-translated. You can still \ncreate language files with Django\n if you wish to localize them.\n\n\nAPIException\n subclasses could previously take any arbitrary type in the \ndetail\n argument. These exceptions now use translatable text strings, and as a result call \nforce_text\n on the \ndetail\n argument, which \nmust be a string\n. If you need complex arguments to an \nAPIException\n class, you should subclass it and override the \n__init__()\n method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.\n\n\n\n\n\n\nWhat's coming next\n\n\n3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.\n\n\nThe 3.1 release is planned to address improvements in the following components:\n\n\n\n\nPublic API for using serializers as HTML forms.\n\n\nRequest parsing, mediatypes \n the implementation of the browsable API.\n\n\nIntroduction of a new pagination API.\n\n\nBetter support for API versioning.\n\n\n\n\nThe 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.\n\n\nYou can follow development on the GitHub site, where we use \nmilestones to indicate planning timescales\n.", 
                 "title": "3.0 Announcement"
             }, 
             {
    @@ -4852,7 +4947,7 @@
             }, 
             {
                 "location": "/topics/3.4-announcement/", 
    -            "text": ".promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px;\n    padding: 150px 0 0 0;\n    background-position: 0 50%;\n    background-size: 130px auto;\n    background-repeat: no-repeat;\n    font-size: 120%;\n    color: black;\n}\n.promo li {\n    list-style: none;\n}\n\n\n\n\nDjango REST framework 3.4\n\n\nThe 3.4 release is the first in a planned series that will be addressing schema\ngeneration, hypermedia support, API clients, and finally realtime support.\n\n\n\n\nFunding\n\n\nThe 3.4 release has been made possible a recent \nMozilla grant\n, and by our\n\ncollaborative funding model\n. If you use REST framework commercially, and would\nlike to see this work continue, we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nThe initial aim is to provide a single full-time position on REST framework.\nRight now we're over 60% of the way towards achieving that.\n\nEvery single sign-up makes a significant impact.\n\n\n\n    \nRover.com\n\n    \nSentry\n\n    \nStream\n\n\n\n\n\n\n\n\nMany thanks to all our \nawesome sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, and \nStream\n.\n\n\n\n\nSchemas \n client libraries\n\n\nREST framework 3.4 brings built-in support for generating API schemas.\n\n\nWe provide this support by using \nCore API\n, a Document Object Model\nfor describing APIs.\n\n\nBecause Core API represents the API schema in an format-independent\nmanner, we're able to render the Core API \nDocument\n object into many different\nschema formats, by allowing the renderer class to determine how the internal\nrepresentation maps onto the external schema format.\n\n\nThis approach should also open the door to a range of auto-generated API\ndocumentation options in the future, by rendering the \nDocument\n object into\nHTML documentation pages.\n\n\nAlongside the built-in schema support, we're also now providing the following:\n\n\n\n\nA \ncommand line tool\n for interacting with APIs.\n\n\nA \nPython client library\n for interacting with APIs.\n\n\n\n\nThese API clients are dynamically driven, and able to interact with any API\nthat exposes a supported schema format.\n\n\nDynamically driven clients allow you to interact with an API at an application\nlayer interface, rather than a network layer interface, while still providing\nthe benefits of RESTful Web API design.\n\n\nWe're expecting to expand the range of languages that we provide client libraries\nfor over the coming months.\n\n\nFurther work on maturing the API schema support is also planned, including\ndocumentation on supporting file upload and download, and improved support for\ndocumentation generation and parameter annotation.\n\n\n\n\nCurrent support for schema formats is as follows:\n\n\n\n\n\n\n\n\nName\n\n\nSupport\n\n\nPyPI package\n\n\n\n\n\n\n\n\n\n\nCore JSON\n\n\nSchema generation \n client support.\n\n\nBuilt-in support in \ncoreapi\n\n\n\n\n\n\nSwagger / OpenAPI\n\n\nSchema generation \n client support.\n\n\nThe \nopenapi-codec\npackage.\n\n\n\n\n\n\nJSON Hyper-Schema\n\n\nCurrrently client support only.\n\n\nThe \nhyperschema-codec\npackage.\n\n\n\n\n\n\nAPI Blueprint\n\n\nNot yet available.\n\n\nNot yet available.\n\n\n\n\n\n\n\n\n\n\nYou can read more about any of this new functionality in the following:\n\n\n\n\nNew tutorial section on \nschemas \n client libraries\n.\n\n\nDocumentation page on \nschema generation\n.\n\n\nTopic page on \nAPI clients\n.\n\n\n\n\nIt is also worth noting that Marc Gibbons is currently working towards a 2.0 release of\nthe popular Django REST Swagger package, which will tie in with our new built-in support.\n\n\n\n\nSupported versions\n\n\nThe 3.4.0 release adds support for Django 1.10.\n\n\nThe following versions of Python and Django are now supported:\n\n\n\n\nDjango versions 1.8, 1.9, and 1.10.\n\n\nPython versions 2.7, 3.2(*), 3.3(*), 3.4, 3.5.\n\n\n\n\n(*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.\n\n\n\n\nDeprecations and changes\n\n\nThe 3.4 release includes very limited deprecation or behavioral changes, and\nshould present a straightforward upgrade.\n\n\nUse fields or exclude on serializer classes.\n\n\nThe following change in 3.3.0 is now escalated from \"pending deprecation\" to\n\"deprecated\". Its usage will continue to function but will raise warnings:\n\n\nModelSerializer\n and \nHyperlinkedModelSerializer\n should include either a \nfields\n\noption, or an \nexclude\n option. The \nfields = '__all__'\n shortcut may be used\nto explicitly include all fields.\n\n\nMicrosecond precision when returning time or datetime.\n\n\nUsing the default JSON renderer and directly returning a \ndatetime\n or \ntime\n\ninstance will now render with microsecond precision (6 digits), rather than\nmillisecond precision (3 digits). This makes the output format consistent with the\ndefault string output of \nserializers.DateTimeField\n and \nserializers.TimeField\n.\n\n\nThis change \ndoes not affect the default behavior when using serializers\n,\nwhich is to serialize \ndatetime\n and \ntime\n instances into strings with\nmicrosecond precision.\n\n\nThe serializer behavior can be modified if needed, using the \nDATETIME_FORMAT\n\nand \nTIME_FORMAT\n settings.\n\n\nThe renderer behavior can be modified by setting a custom \nencoder_class\n\nattribute on a \nJSONRenderer\n subclass.\n\n\nRelational choices no longer displayed in OPTIONS requests.\n\n\nMaking an \nOPTIONS\n request to views that have a serializer choice field\nwill result in a list of the available choices being returned in the response.\n\n\nIn cases where there is a relational field, the previous behavior would be\nto return a list of available instances to choose from for that relational field.\n\n\nIn order to minimise exposed information the behavior now is to \nnot\n return\nchoices information for relational fields.\n\n\nIf you want to override this new behavior you'll need to \nimplement a custom\nmetadata class\n.\n\n\nSee \nissue #3751\n for more information on this behavioral change.\n\n\n\n\nOther improvements\n\n\nThis release includes further work from a huge number of \npull requests and issues\n.\n\n\nMany thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.\n\n\nThe full set of itemized release notes \nare available here\n.", 
    +            "text": ".promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px;\n    padding: 150px 0 0 0;\n    background-position: 0 50%;\n    background-size: 130px auto;\n    background-repeat: no-repeat;\n    font-size: 120%;\n    color: black;\n}\n.promo li {\n    list-style: none;\n}\n\n\n\n\nDjango REST framework 3.4\n\n\nThe 3.4 release is the first in a planned series that will be addressing schema\ngeneration, hypermedia support, API clients, and finally realtime support.\n\n\n\n\nFunding\n\n\nThe 3.4 release has been made possible a recent \nMozilla grant\n, and by our\n\ncollaborative funding model\n. If you use REST framework commercially, and would\nlike to see this work continue, we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nThe initial aim is to provide a single full-time position on REST framework.\nRight now we're over 60% of the way towards achieving that.\n\nEvery single sign-up makes a significant impact.\n\n\n\n    \nRover.com\n\n    \nSentry\n\n    \nStream\n\n\n\n\n\n\n\n\nMany thanks to all our \nawesome sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, and \nStream\n.\n\n\n\n\nSchemas \n client libraries\n\n\nREST framework 3.4 brings built-in support for generating API schemas.\n\n\nWe provide this support by using \nCore API\n, a Document Object Model\nfor describing APIs.\n\n\nBecause Core API represents the API schema in an format-independent\nmanner, we're able to render the Core API \nDocument\n object into many different\nschema formats, by allowing the renderer class to determine how the internal\nrepresentation maps onto the external schema format.\n\n\nThis approach should also open the door to a range of auto-generated API\ndocumentation options in the future, by rendering the \nDocument\n object into\nHTML documentation pages.\n\n\nAlongside the built-in schema support, we're also now providing the following:\n\n\n\n\nA \ncommand line tool\n for interacting with APIs.\n\n\nA \nPython client library\n for interacting with APIs.\n\n\n\n\nThese API clients are dynamically driven, and able to interact with any API\nthat exposes a supported schema format.\n\n\nDynamically driven clients allow you to interact with an API at an application\nlayer interface, rather than a network layer interface, while still providing\nthe benefits of RESTful Web API design.\n\n\nWe're expecting to expand the range of languages that we provide client libraries\nfor over the coming months.\n\n\nFurther work on maturing the API schema support is also planned, including\ndocumentation on supporting file upload and download, and improved support for\ndocumentation generation and parameter annotation.\n\n\n\n\nCurrent support for schema formats is as follows:\n\n\n\n\n\n\n\n\nName\n\n\nSupport\n\n\nPyPI package\n\n\n\n\n\n\n\n\n\n\nCore JSON\n\n\nSchema generation \n client support.\n\n\nBuilt-in support in \ncoreapi\n.\n\n\n\n\n\n\nSwagger / OpenAPI\n\n\nSchema generation \n client support.\n\n\nThe \nopenapi-codec\n package.\n\n\n\n\n\n\nJSON Hyper-Schema\n\n\nCurrrently client support only.\n\n\nThe \nhyperschema-codec\n package.\n\n\n\n\n\n\nAPI Blueprint\n\n\nNot yet available.\n\n\nNot yet available.\n\n\n\n\n\n\n\n\n\n\nYou can read more about any of this new functionality in the following:\n\n\n\n\nNew tutorial section on \nschemas \n client libraries\n.\n\n\nDocumentation page on \nschema generation\n.\n\n\nTopic page on \nAPI clients\n.\n\n\n\n\nIt is also worth noting that Marc Gibbons is currently working towards a 2.0 release of\nthe popular Django REST Swagger package, which will tie in with our new built-in support.\n\n\n\n\nSupported versions\n\n\nThe 3.4.0 release adds support for Django 1.10.\n\n\nThe following versions of Python and Django are now supported:\n\n\n\n\nDjango versions 1.8, 1.9, and 1.10.\n\n\nPython versions 2.7, 3.2(*), 3.3(*), 3.4, 3.5.\n\n\n\n\n(*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.\n\n\n\n\nDeprecations and changes\n\n\nThe 3.4 release includes very limited deprecation or behavioral changes, and\nshould present a straightforward upgrade.\n\n\nUse fields or exclude on serializer classes.\n\n\nThe following change in 3.3.0 is now escalated from \"pending deprecation\" to\n\"deprecated\". Its usage will continue to function but will raise warnings:\n\n\nModelSerializer\n and \nHyperlinkedModelSerializer\n should include either a \nfields\n\noption, or an \nexclude\n option. The \nfields = '__all__'\n shortcut may be used\nto explicitly include all fields.\n\n\nMicrosecond precision when returning time or datetime.\n\n\nUsing the default JSON renderer and directly returning a \ndatetime\n or \ntime\n\ninstance will now render with microsecond precision (6 digits), rather than\nmillisecond precision (3 digits). This makes the output format consistent with the\ndefault string output of \nserializers.DateTimeField\n and \nserializers.TimeField\n.\n\n\nThis change \ndoes not affect the default behavior when using serializers\n,\nwhich is to serialize \ndatetime\n and \ntime\n instances into strings with\nmicrosecond precision.\n\n\nThe serializer behavior can be modified if needed, using the \nDATETIME_FORMAT\n\nand \nTIME_FORMAT\n settings.\n\n\nThe renderer behavior can be modified by setting a custom \nencoder_class\n\nattribute on a \nJSONRenderer\n subclass.\n\n\nRelational choices no longer displayed in OPTIONS requests.\n\n\nMaking an \nOPTIONS\n request to views that have a serializer choice field\nwill result in a list of the available choices being returned in the response.\n\n\nIn cases where there is a relational field, the previous behavior would be\nto return a list of available instances to choose from for that relational field.\n\n\nIn order to minimise exposed information the behavior now is to \nnot\n return\nchoices information for relational fields.\n\n\nIf you want to override this new behavior you'll need to \nimplement a custom\nmetadata class\n.\n\n\nSee \nissue #3751\n for more information on this behavioral change.\n\n\n\n\nOther improvements\n\n\nThis release includes further work from a huge number of \npull requests and issues\n.\n\n\nMany thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.\n\n\nThe full set of itemized release notes \nare available here\n.", 
                 "title": "3.4 Announcement"
             }, 
             {
    @@ -4867,7 +4962,7 @@
             }, 
             {
                 "location": "/topics/3.4-announcement/#schemas-client-libraries", 
    -            "text": "REST framework 3.4 brings built-in support for generating API schemas.  We provide this support by using  Core API , a Document Object Model\nfor describing APIs.  Because Core API represents the API schema in an format-independent\nmanner, we're able to render the Core API  Document  object into many different\nschema formats, by allowing the renderer class to determine how the internal\nrepresentation maps onto the external schema format.  This approach should also open the door to a range of auto-generated API\ndocumentation options in the future, by rendering the  Document  object into\nHTML documentation pages.  Alongside the built-in schema support, we're also now providing the following:   A  command line tool  for interacting with APIs.  A  Python client library  for interacting with APIs.   These API clients are dynamically driven, and able to interact with any API\nthat exposes a supported schema format.  Dynamically driven clients allow you to interact with an API at an application\nlayer interface, rather than a network layer interface, while still providing\nthe benefits of RESTful Web API design.  We're expecting to expand the range of languages that we provide client libraries\nfor over the coming months.  Further work on maturing the API schema support is also planned, including\ndocumentation on supporting file upload and download, and improved support for\ndocumentation generation and parameter annotation.   Current support for schema formats is as follows:     Name  Support  PyPI package      Core JSON  Schema generation   client support.  Built-in support in  coreapi    Swagger / OpenAPI  Schema generation   client support.  The  openapi-codec package.    JSON Hyper-Schema  Currrently client support only.  The  hyperschema-codec package.    API Blueprint  Not yet available.  Not yet available.      You can read more about any of this new functionality in the following:   New tutorial section on  schemas   client libraries .  Documentation page on  schema generation .  Topic page on  API clients .   It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of\nthe popular Django REST Swagger package, which will tie in with our new built-in support.", 
    +            "text": "REST framework 3.4 brings built-in support for generating API schemas.  We provide this support by using  Core API , a Document Object Model\nfor describing APIs.  Because Core API represents the API schema in an format-independent\nmanner, we're able to render the Core API  Document  object into many different\nschema formats, by allowing the renderer class to determine how the internal\nrepresentation maps onto the external schema format.  This approach should also open the door to a range of auto-generated API\ndocumentation options in the future, by rendering the  Document  object into\nHTML documentation pages.  Alongside the built-in schema support, we're also now providing the following:   A  command line tool  for interacting with APIs.  A  Python client library  for interacting with APIs.   These API clients are dynamically driven, and able to interact with any API\nthat exposes a supported schema format.  Dynamically driven clients allow you to interact with an API at an application\nlayer interface, rather than a network layer interface, while still providing\nthe benefits of RESTful Web API design.  We're expecting to expand the range of languages that we provide client libraries\nfor over the coming months.  Further work on maturing the API schema support is also planned, including\ndocumentation on supporting file upload and download, and improved support for\ndocumentation generation and parameter annotation.   Current support for schema formats is as follows:     Name  Support  PyPI package      Core JSON  Schema generation   client support.  Built-in support in  coreapi .    Swagger / OpenAPI  Schema generation   client support.  The  openapi-codec  package.    JSON Hyper-Schema  Currrently client support only.  The  hyperschema-codec  package.    API Blueprint  Not yet available.  Not yet available.      You can read more about any of this new functionality in the following:   New tutorial section on  schemas   client libraries .  Documentation page on  schema generation .  Topic page on  API clients .   It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of\nthe popular Django REST Swagger package, which will tie in with our new built-in support.", 
                 "title": "Schemas & client libraries"
             }, 
             {
    diff --git a/sitemap.xml b/sitemap.xml
    index f2ac234fe..29000312b 100644
    --- a/sitemap.xml
    +++ b/sitemap.xml
    @@ -4,7 +4,7 @@
         
         
          http://www.django-rest-framework.org//
    -     2016-09-29
    +     2016-10-14
          daily
         
         
    @@ -13,49 +13,49 @@
             
         
          http://www.django-rest-framework.org//tutorial/quickstart/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/1-serialization/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/2-requests-and-responses/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/3-class-based-views/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//tutorial/7-schemas-and-client-libraries/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
    @@ -65,163 +65,163 @@
             
         
          http://www.django-rest-framework.org//api-guide/requests/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/responses/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/views/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/generic-views/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/viewsets/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/routers/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/parsers/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/renderers/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/serializers/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/fields/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/relations/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/validators/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/authentication/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/permissions/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/throttling/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/filtering/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/pagination/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/versioning/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/content-negotiation/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/metadata/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/schemas/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/format-suffixes/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/reverse/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/exceptions/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/status-codes/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/testing/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//api-guide/settings/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
    @@ -231,121 +231,121 @@
             
         
          http://www.django-rest-framework.org//topics/documenting-your-api/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/api-clients/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/internationalization/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/ajax-csrf-cors/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/html-and-forms/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/browser-enhancements/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/browsable-api/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/third-party-resources/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/contributing/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/project-management/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/3.0-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/3.1-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/3.2-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/3.3-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/3.4-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/kickstarter-announcement/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/mozilla-grant/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/funding/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
         
          http://www.django-rest-framework.org//topics/release-notes/
    -     2016-09-29
    +     2016-10-14
          daily
         
             
    diff --git a/topics/3.0-announcement/index.html b/topics/3.0-announcement/index.html
    index 20fb40735..33b84e41f 100644
    --- a/topics/3.0-announcement/index.html
    +++ b/topics/3.0-announcement/index.html
    @@ -450,7 +450,7 @@
     

    Below is an in-depth guide to the API changes and migration notes for 3.0.

    Request objects

    -

    .query_params properties.The .data and

    +

    The .data and .query_params properties.

    The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data.

    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.

    You may now pass all the request data to a serializer class in a single argument:

    @@ -482,7 +482,7 @@ ExampleSerializer(data=request.DATA, files=request.FILES)
  • Calling serializer.save() then saves and returns the new object instance.
  • The resulting API changes are further detailed below.

    -

    .update() methods.The .create() and

    +

    The .create() and .update() methods.

    The .restore_object() method is now removed, and we instead have two separate methods, .create() and .update(). These methods work slightly different to the previous .restore_object().

    When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it.

    These methods also replace the optional .save_object() method, which no longer exists.

    @@ -514,7 +514,7 @@ def create(self, validated_data): return Snippet.objects.create(**validated_data)

    Note that these methods should return the newly created object instance.

    -

    .object.Use .validated_data instead of

    +

    Use .validated_data instead of .object.

    You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists.

    For example the following code is no longer valid:

    if serializer.is_valid():
    @@ -862,7 +862,7 @@ def all_high_scores(request):
     

    Serializer fields

    -

    ReadOnly field classes.The Field and

    +

    The Field and ReadOnly field classes.

    There are some minor tweaks to the field base classes.

    Previously we had these two base classes:

      @@ -874,7 +874,7 @@ def all_high_scores(request):
    • Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
    • ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification.
    -

    allow_null, default arguments.The required, allow_blank and

    +

    The required, allow_null, allow_blank and default arguments.

    REST framework now has more explicit and clear control over validating empty values for fields.

    Previously the meaning of the required=False 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 None or the empty string.

    We now have a better separation, with separate required, allow_null and allow_blank arguments.

    @@ -984,7 +984,7 @@ This removes some magic and makes it easier and more obvious to move between imp

    The following usage will now raise an error:

    email = serializers.EmailField(source='email')
     
    -

    UniqueTogetherValidator classes.The UniqueValidator and

    +

    The UniqueValidator and UniqueTogetherValidator classes.

    REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer.

    The UniqueValidator should be applied to a serializer field, and takes a single queryset argument.

    from rest_framework import serializers
    diff --git a/topics/3.4-announcement/index.html b/topics/3.4-announcement/index.html
    index 3c44f34d0..ec590cecf 100644
    --- a/topics/3.4-announcement/index.html
    +++ b/topics/3.4-announcement/index.html
    @@ -482,17 +482,17 @@ documentation generation and parameter annotation.

    Core JSON Schema generation & client support. -Built-in support in coreapi +Built-in support in coreapi. Swagger / OpenAPI Schema generation & client support. -The openapi-codecpackage. +The openapi-codec package. JSON Hyper-Schema Currrently client support only. -The hyperschema-codecpackage. +The hyperschema-codec package. API Blueprint diff --git a/topics/contributing/index.html b/topics/contributing/index.html index d095a2f6e..153abbd8f 100644 --- a/topics/contributing/index.html +++ b/topics/contributing/index.html @@ -479,6 +479,7 @@
    # Setup the virtual environment
     virtualenv env
     source env/bin/activate
    +pip install django
     pip install -r requirements.txt
     
     # Run the tests
    diff --git a/topics/html-and-forms/index.html b/topics/html-and-forms/index.html
    index 9a330fbad..7b65e46bd 100644
    --- a/topics/html-and-forms/index.html
    +++ b/topics/html-and-forms/index.html
    @@ -581,22 +581,22 @@ class ProfileDetail(APIView):
     
     
     select.html
    -ChoiceFieldor relational field types
    +ChoiceField or relational field types
     hide_label
     
     
     radio.html
    -ChoiceFieldor relational field types
    +ChoiceField or relational field types
     inline, hide_label
     
     
     select_multiple.html
    -MultipleChoiceFieldor relational fields with many=True
    +MultipleChoiceField or relational fields with many=True
     hide_label
     
     
     checkbox_multiple.html
    -MultipleChoiceFieldor relational fields with many=True
    +MultipleChoiceField or relational fields with many=True
     inline, hide_label
     
     
    @@ -611,7 +611,7 @@ class ProfileDetail(APIView):
     
     
     list_fieldset.html
    -ListFieldor nested serializer with many=True
    +ListField or nested serializer with many=True
     hide_label
     
     
    diff --git a/topics/project-management/index.html b/topics/project-management/index.html
    index 6c62a2831..60a6ee089 100644
    --- a/topics/project-management/index.html
    +++ b/topics/project-management/index.html
    @@ -407,7 +407,7 @@
     

    — Halford E. Luccock

    This document outlines our project management processes for REST framework.

    -

    The aim is to ensure that the project has a high +

    The aim is to ensure that the project has a high "bus factor", and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.


    Maintenance team

    @@ -540,7 +540,7 @@ tx push -s

    Download translations

    When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:

    # 3. Pull the translated django.po files from Transifex.
    -tx pull -a
    +tx pull -a --minimum-perc 10
     cd rest_framework
     # 4. Compile the binary .mo files for all supported languages.
     django-admin.py compilemessages
    diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html
    index 8c3d6632b..95f4e189a 100644
    --- a/topics/third-party-resources/index.html
    +++ b/topics/third-party-resources/index.html
    @@ -573,6 +573,7 @@ You probably want to also tag the version now:
     
    • djangorestframework-chain - Allows arbitrary chaining of both relations and lookup filters.
    • django-url-filter - 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.
    • +
    • drf-url-filter is a simple Django app to apply filters on drf ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values.

    Misc

      diff --git a/tutorial/1-serialization/index.html b/tutorial/1-serialization/index.html index 2d882feb3..1ec6ed137 100644 --- a/tutorial/1-serialization/index.html +++ b/tutorial/1-serialization/index.html @@ -490,7 +490,7 @@ from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): - pk = serializers.IntegerField(read_only=True) + id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) @@ -538,12 +538,12 @@ snippet.save()

      We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.

      serializer = SnippetSerializer(snippet)
       serializer.data
      -# {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
      +# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
       

      At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.

      content = JSONRenderer().render(serializer.data)
       content
      -# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
      +# '{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
       

      Deserialization is similar. First we parse a stream into Python native datatypes...

      from django.utils.six import BytesIO
      @@ -564,7 +564,7 @@ serializer.save()
       

      We can also serialize querysets instead of model instances. To do so we simply add a many=True flag to the serializer arguments.

      serializer = SnippetSerializer(Snippet.objects.all(), many=True)
       serializer.data
      -# [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')])]
      +# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
       

      Using ModelSerializers

      Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It would be nice if we could keep our code a bit more concise.

      @@ -636,12 +636,12 @@ def snippet_list(request):

      Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.

      We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.

      @csrf_exempt
      -def snippet_detail(request, pk):
      +def snippet_detail(request, id):
           """
           Retrieve, update or delete a code snippet.
           """
           try:
      -        snippet = Snippet.objects.get(pk=pk)
      +        snippet = Snippet.objects.get(id=id)
           except Snippet.DoesNotExist:
               return HttpResponse(status=404)
       
      @@ -667,7 +667,7 @@ from snippets import views
       
       urlpatterns = [
           url(r'^snippets/$', views.snippet_list),
      -    url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
      +    url(r'^snippets/(?P<id>[0-9]+)/$', views.snippet_detail),
       ]
       

      We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs.

      diff --git a/tutorial/2-requests-and-responses/index.html b/tutorial/2-requests-and-responses/index.html index 54a2a44f7..b25375079 100644 --- a/tutorial/2-requests-and-responses/index.html +++ b/tutorial/2-requests-and-responses/index.html @@ -465,12 +465,12 @@ def snippet_list(request):

      Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.

      Here is the view for an individual snippet, in the views.py module.

      @api_view(['GET', 'PUT', 'DELETE'])
      -def snippet_detail(request, pk):
      +def snippet_detail(request, id):
           """
           Retrieve, update or delete a snippet instance.
           """
           try:
      -        snippet = Snippet.objects.get(pk=pk)
      +        snippet = Snippet.objects.get(id=id)
           except Snippet.DoesNotExist:
               return Response(status=status.HTTP_404_NOT_FOUND)
       
      @@ -497,7 +497,7 @@ def snippet_detail(request, pk):
       
      def snippet_list(request, format=None):
       

      and

      -
      def snippet_detail(request, pk, format=None):
      +
      def snippet_detail(request, id, format=None):
       

      Now update the urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs.

      from django.conf.urls import url
      @@ -506,7 +506,7 @@ from snippets import views
       
       urlpatterns = [
           url(r'^snippets/$', views.snippet_list),
      -    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
      +    url(r'^snippets/(?P<id>[0-9]+)$', views.snippet_detail),
       ]
       
       urlpatterns = format_suffix_patterns(urlpatterns)
      diff --git a/tutorial/3-class-based-views/index.html b/tutorial/3-class-based-views/index.html
      index 2c089024f..df2232ddb 100644
      --- a/tutorial/3-class-based-views/index.html
      +++ b/tutorial/3-class-based-views/index.html
      @@ -426,27 +426,27 @@ class SnippetList(APIView):
           """
           Retrieve, update or delete a snippet instance.
           """
      -    def get_object(self, pk):
      +    def get_object(self, id):
               try:
      -            return Snippet.objects.get(pk=pk)
      +            return Snippet.objects.get(id=id)
               except Snippet.DoesNotExist:
                   raise Http404
       
      -    def get(self, request, pk, format=None):
      -        snippet = self.get_object(pk)
      +    def get(self, request, id, format=None):
      +        snippet = self.get_object(id)
               serializer = SnippetSerializer(snippet)
               return Response(serializer.data)
       
      -    def put(self, request, pk, format=None):
      -        snippet = self.get_object(pk)
      +    def put(self, request, id, format=None):
      +        snippet = self.get_object(id)
               serializer = SnippetSerializer(snippet, data=request.data)
               if serializer.is_valid():
                   serializer.save()
                   return Response(serializer.data)
               return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
       
      -    def delete(self, request, pk, format=None):
      -        snippet = self.get_object(pk)
      +    def delete(self, request, id, format=None):
      +        snippet = self.get_object(id)
               snippet.delete()
               return Response(status=status.HTTP_204_NO_CONTENT)
       
      @@ -458,7 +458,7 @@ from snippets import views urlpatterns = [ url(r'^snippets/$', views.SnippetList.as_view()), - url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), + url(r'^snippets/(?P<id>[0-9]+)/$', views.SnippetDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html index 343a941ec..95352402d 100644 --- a/tutorial/4-authentication-and-permissions/index.html +++ b/tutorial/4-authentication-and-permissions/index.html @@ -492,7 +492,7 @@ class UserDetail(generics.RetrieveAPIView):

      Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in urls.py.

      url(r'^users/$', views.UserList.as_view()),
      -url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
      +url(r'^users/(?P<id>[0-9]+)/$', views.UserDetail.as_view()),
       

      Associating Snippets with Users

      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.

      @@ -532,7 +532,7 @@ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),

      The r'^api-auth/' part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework' namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.

      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.

      -

      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.

      +

      Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.

      Object level permissions

      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.

      To do that we're going to need to create a custom permission.

      diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html index 150264868..d72e2e9ab 100644 --- a/tutorial/5-relationships-and-hyperlinked-apis/index.html +++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html @@ -443,7 +443,7 @@ We'll add a url pattern for our new API root in snippets/urls.py:url(r'^$', views.api_root),

      And then add a url pattern for the snippet highlights:

      -
      url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
      +
      url(r'^snippets/(?P<id>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
       

      Hyperlinking our API

      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:

      @@ -459,7 +459,7 @@ We'll add a url pattern for our new API root in snippets/urls.py:In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer instead of the existing ModelSerializer.

      The HyperlinkedModelSerializer has the following differences from ModelSerializer:

        -
      • It does not include the pk field by default.
      • +
      • It does not include the id field by default.
      • It includes a url field, using HyperlinkedIdentityField.
      • Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.
      • @@ -471,7 +471,7 @@ We'll add a url pattern for our new API root in snippets/urls.py:

      Notice that we've also added a new 'highlight' field. This field is of the same type as the url field, except that it points to the 'snippet-highlight' url pattern, instead of the 'snippet-detail' url pattern.

      Because we've included format suffixed URLs such as '.json', we also need to indicate on the highlight field that any format suffixed hyperlinks it returns should use the '.html' suffix.

      @@ -503,16 +503,16 @@ urlpatterns = format_suffix_patterns([ url(r'^snippets/$', views.SnippetList.as_view(), name='snippet-list'), - url(r'^snippets/(?P<pk>[0-9]+)/$', + url(r'^snippets/(?P<id>[0-9]+)/$', views.SnippetDetail.as_view(), name='snippet-detail'), - url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', + url(r'^snippets/(?P<id>[0-9]+)/highlight/$', views.SnippetHighlight.as_view(), name='snippet-highlight'), url(r'^users/$', views.UserList.as_view(), name='user-list'), - url(r'^users/(?P<pk>[0-9]+)/$', + url(r'^users/(?P<id>[0-9]+)/$', views.UserDetail.as_view(), name='user-detail') ]) diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html index 613e9a951..c2c7ac48f 100644 --- a/tutorial/6-viewsets-and-routers/index.html +++ b/tutorial/6-viewsets-and-routers/index.html @@ -473,10 +473,10 @@ user_detail = UserViewSet.as_view({
      urlpatterns = format_suffix_patterns([
           url(r'^$', api_root),
           url(r'^snippets/$', snippet_list, name='snippet-list'),
      -    url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
      -    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
      +    url(r'^snippets/(?P<id>[0-9]+)/$', snippet_detail, name='snippet-detail'),
      +    url(r'^snippets/(?P<id>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
           url(r'^users/$', user_list, name='user-list'),
      -    url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
      +    url(r'^users/(?P<id>[0-9]+)/$', user_detail, name='user-detail')
       ])
       

      Using Routers

      diff --git a/tutorial/7-schemas-and-client-libraries/index.html b/tutorial/7-schemas-and-client-libraries/index.html index 25029d717..09be19862 100644 --- a/tutorial/7-schemas-and-client-libraries/index.html +++ b/tutorial/7-schemas-and-client-libraries/index.html @@ -429,16 +429,23 @@ we can simply use the automatic schema generation.

      API schema.

      $ pip install coreapi
       
      -

      We can now include a schema for our API, by adding a schema_title argument to -the router instantiation.

      -
      router = DefaultRouter(schema_title='Pastebin API')
      +

      We can now include a schema for our API, by including an autogenerated schema +view in our URL configuration.

      +
      from rest_framework.schemas import get_schema_view
      +
      +schema_view = get_schema_view(title='Pastebin API')
      +
      +urlpatterns = [
      +    url('^schema/$', schema_view),
      +    ...
      +]
       

      If you visit the API root endpoint in a browser you should now see corejson representation become available as an option.

      Schema format

      We can also request the schema from the command line, by specifying the desired content type in the Accept header.

      -
      $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json
      +
      $ http http://127.0.0.1:8000/schema/ Accept:application/vnd.coreapi+json
       HTTP/1.0 200 OK
       Allow: GET, HEAD, OPTIONS
       Content-Type: application/vnd.coreapi+json
      @@ -476,16 +483,16 @@ Commands:
       ...
       

      First we'll load the API schema using the command line client.

      -
      $ coreapi get http://127.0.0.1:8000/
      -<Pastebin API "http://127.0.0.1:8000/">
      +
      $ coreapi get http://127.0.0.1:8000/schema/
      +<Pastebin API "http://127.0.0.1:8000/schema/">
           snippets: {
      -        highlight(pk)
      +        highlight(id)
               list()
      -        retrieve(pk)
      +        read(id)
           }
           users: {
               list()
      -        retrieve(pk)
      +        read(id)
           }
       

      We haven't authenticated yet, so right now we're only able to see the read only @@ -495,7 +502,7 @@ endpoints, in line with how we've set up the permissions on the API.

      [ { "url": "http://127.0.0.1:8000/snippets/1/", - "pk": 1, + "id": 1, "highlight": "http://127.0.0.1:8000/snippets/1/highlight/", "owner": "lucy", "title": "Example", @@ -508,7 +515,7 @@ endpoints, in line with how we've set up the permissions on the API.

      Some of the API endpoints require named parameters. For example, to get back the highlight HTML for a particular snippet we need to provide an id.

      -
      $ coreapi action snippets highlight --param pk=1
      +
      $ coreapi action snippets highlight --param id=1
       <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
       
       <html>
      @@ -528,19 +535,19 @@ Added credentials
       

      Now if we fetch the schema again, we should be able to see the full set of available interactions.

      $ coreapi reload
      -Pastebin API "http://127.0.0.1:8000/">
      +Pastebin API "http://127.0.0.1:8000/schema/">
           snippets: {
               create(code, [title], [linenos], [language], [style])
      -        destroy(pk)
      -        highlight(pk)
      +        delete(id)
      +        highlight(id)
               list()
      -        partial_update(pk, [title], [code], [linenos], [language], [style])
      -        retrieve(pk)
      -        update(pk, code, [title], [linenos], [language], [style])
      +        partial_update(id, [title], [code], [linenos], [language], [style])
      +        read(id)
      +        update(id, code, [title], [linenos], [language], [style])
           }
           users: {
               list()
      -        retrieve(pk)
      +        read(id)
           }
       

      We're now able to interact with these endpoints. For example, to create a new @@ -548,7 +555,7 @@ snippet:

      $ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
       {
           "url": "http://127.0.0.1:8000/snippets/7/",
      -    "pk": 7,
      +    "id": 7,
           "highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
           "owner": "lucy",
           "title": "Example",
      @@ -559,7 +566,7 @@ snippet:

      }

      And to delete a snippet:

      -
      $ coreapi action snippets destroy --param pk=7
      +
      $ coreapi action snippets delete --param id=7
       

      As well as the command line client, developers can also interact with your API using client libraries. The Python client library is the first of these