diff --git a/404.html b/404.html index 3d6640212..b5ff70705 100644 --- a/404.html +++ b/404.html @@ -179,10 +179,6 @@ Permissions -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - +
  • + Django OAuth2 Consumer +
  • +
  • JSON Web Token Authentication
  • @@ -808,12 +801,14 @@ REST_FRAMEWORK = {

    For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions.

    Digest Authentication

    HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. Juan Riaza maintains the djangorestframework-digestauth package which provides HTTP digest authentication support for REST framework.

    +

    Django OAuth2 Consumer

    +

    The Django OAuth2 Consumer library from Rediker Software is another package that provides OAuth 2.0 support for REST framework. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.

    JSON Web Token Authentication

    JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. Blimp maintains the djangorestframework-jwt package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is djangorestframework-simplejwt which provides different features as well as a pluggable token blacklist app.

    Hawk HTTP Authentication

    The HawkREST library builds on the Mohawk library to let you work with Hawk signed requests and responses in your API. Hawk lets two parties securely communicate with each other using messages signed by a shared key. It is based on HTTP MAC access authentication (which was based on parts of OAuth 1.0).

    HTTP Signature Authentication

    -

    HTTP Signature (currently a IETF draft) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme, used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature, which is drf-httpsig.

    +

    HTTP Signature (currently a IETF draft) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme, used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature package which provides an easy to use HTTP Signature Authentication mechanism.

    Djoser

    Djoser library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.

    django-rest-auth

    diff --git a/api-guide/caching/index.html b/api-guide/caching/index.html deleted file mode 100644 index 79120cd94..000000000 --- a/api-guide/caching/index.html +++ /dev/null @@ -1,514 +0,0 @@ - - - - - - - Caching - Django REST framework - - - - - - - - - - - - - - - - - - - - - -
    - - -
    -
    - - - -
    -
    -
    - - -
    -
    - -
    - - - -

    Caching

    -
    -

    A certain woman had a very sharp conciousness but almost no -memory ... She remembered enough to work, and she worked hard. -- Lydia Davis

    -
    -

    Caching in REST Framework works well with the cache utilities -provided in Django.

    -
    -

    Using cache with apiview and viewsets

    -

    Django provides a method_decorator to use -decorators with class based views. This can be used with -with other cache decorators such as cache_page and -vary_on_cookie.

    -
    from rest_framework.response import Response
    -from rest_framework.views import APIView
    -from rest_framework import viewsets
    -
    -class UserViewSet(viewsets.Viewset):
    -
    -    # Cache requested url for each user for 2 hours
    -    @method_decorator(cache_page(60*60*2))
    -    @method_decorator(vary_on_cookie)
    -    def list(self, request, format=None):
    -        content = {
    -            'user_feed': request.user.get_user_feed()
    -        }
    -        return Response(content)
    -
    -class PostView(APIView):
    -
    -    # Cache page for the requested url
    -    @method_decorator(cache_page(60*60*2))
    -    def get(self, request, format=None):
    -        content = {
    -            'title': 'Post title',
    -            'body': 'Post content'
    -        }
    -        return Response(content)
    -
    - -

    NOTE: The cache_page decorator only caches the -GET and HEAD responses with status 200.

    - - -
    -
    -
    -
    -
    -
    - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html index bc817c591..9733b3ac5 100644 --- a/api-guide/content-negotiation/index.html +++ b/api-guide/content-negotiation/index.html @@ -179,10 +179,6 @@ Permissions -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -
  • - rest_framework.exceptions.bad_request + rest_framework.exceptions.server_error
  • @@ -665,7 +654,7 @@ API-only application.)

    Set as handler500:

    handler500 = 'rest_framework.exceptions.server_error'
     
    -

    rest_framework.exceptions.bad_request

    +

    rest_framework.exceptions.server_error

    Returns a response with status code 400 and application/json content type.

    Set as handler400:

    handler400 = 'rest_framework.exceptions.bad_request'
    diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html
    index 2e7f2bde2..4fd35988c 100644
    --- a/api-guide/fields/index.html
    +++ b/api-guide/fields/index.html
    @@ -179,10 +179,6 @@
                         Permissions
                       
                       
    -                  
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -
  • The field should have a database index.
  • Using 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.

    -

    For more technical details on the implementation we use for cursor pagination, the "Building cursors for the Disqus API" blog post gives a good overview of the basic approach.

    +

    For more technical details on the implementation we use for cursor pagination, the "Building cursors for the Disqus API" blog post gives a good overview of the basic approach.

    Setup

    To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired:

    REST_FRAMEWORK = {
    diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html
    index 89a6e2aa5..639d25997 100644
    --- a/api-guide/parsers/index.html
    +++ b/api-guide/parsers/index.html
    @@ -179,10 +179,6 @@
                         Permissions
                       
                       
    -                  
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - XLSX (Binary Spreadsheet Endpoints) -
  • -
  • CSV
  • @@ -881,37 +866,6 @@ In this case you can underspecify the media types it should respond to, by using

    MessagePack

    MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.

    -

    XLSX (Binary Spreadsheet Endpoints)

    -

    XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-renderer-xlsx, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.

    -

    Installation & configuration

    -

    Install using pip.

    -
    $ pip install drf-renderer-xlsx
    -
    -

    Modify your REST framework settings.

    -
    REST_FRAMEWORK = {
    -    ...
    -
    -    'DEFAULT_RENDERER_CLASSES': (
    -        'rest_framework.renderers.JSONRenderer',
    -        'rest_framework.renderers.BrowsableAPIRenderer',
    -        'drf_renderer_xlsx.renderers.XLSXRenderer',
    -    ),
    -}
    -
    -

    To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the Content-Disposition header. If no filename is provided, it will default to export.xlsx. For example:

    -
    from rest_framework.viewsets import ReadOnlyModelViewSet
    -from drf_renderer_xlsx.mixins import XLSXFileMixin
    -from drf_renderer_xlsx.renderers import XLSXRenderer
    -
    -from .models import MyExampleModel
    -from .serializers import MyExampleSerializer
    -
    -class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    -    queryset = MyExampleModel.objects.all()
    -    serializer_class = MyExampleSerializer
    -    renderer_classes = (XLSXRenderer,)
    -    filename = 'my_export.xlsx'
    -

    CSV

    Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the djangorestframework-csv package which provides CSV renderer support for REST framework.

    UltraJSON

    diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html index 600fd64fe..84927fcef 100644 --- a/api-guide/requests/index.html +++ b/api-guide/requests/index.html @@ -179,10 +179,6 @@ Permissions -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -
    -

    This also applies to extra actions for ViewSets:

    -
        class CustomViewSet(viewsets.ModelViewSet):
    -
    -        @action(detail=True, schema=None)
    -        def extra_action(self, request, pk=None):
    -            ...
    -

    Note: For full details on SchemaGenerator plus the AutoSchema and ManualSchema descriptors see the API Reference below.

    @@ -1017,13 +999,13 @@ view docstring as described in the "Schemas as Documentation" section above.

    with the given view. Eg. 'application/json'. May return a blank string for views that do not expect a request body.

    get_path_fields(self, path, method):

    -

    Return a list of coreapi.Field() instances. One for each path parameter in the URL.

    +

    Return a list of coreapi.Link() instances. One for each path parameter in the URL.

    get_serializer_fields(self, path, method)

    -

    Return a list of coreapi.Field() instances. One for each field in the serializer class used by the view.

    +

    Return a list of coreapi.Link() instances. One for each field in the serializer class used by the view.

    get_pagination_fields(self, path, method)

    -

    Return a list of coreapi.Field() instances, as returned by the get_schema_fields() method on any pagination class used by the view.

    +

    Return a list of coreapi.Link() instances, as returned by the get_schema_fields() method on any pagination class used by the view.

    get_filter_fields(self, path, method)

    -

    Return a list of coreapi.Field() instances, as returned by the get_schema_fields() method of any filter classes used by the view.

    +

    Return a list of coreapi.Link() instances, as returned by the get_schema_fields() method of any filter classes used by the view.

    get_manual_fields(self, path, method)

    Return a list of coreapi.Field() instances to be added to or replace generated fields. Defaults to (optional) manual_fields passed to AutoSchema constructor.

    May be overridden to customise manual fields by path or method. For example, a per-method adjustment may look like this:

    diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html index 28cc8e8ff..d6e4e6059 100644 --- a/api-guide/serializers/index.html +++ b/api-guide/serializers/index.html @@ -179,10 +179,6 @@ Permissions -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -
    -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -

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

    -
    from rest_framework.test import RequestsClient
    -
    -client = RequestsClient()
    +
    client = RequestsClient()
     response = client.get('http://testserver/users/')
     assert response.status_code == 200
     
    @@ -711,12 +698,12 @@ token in the following request.

    client = RequestsClient()
     
     # Obtain a CSRF token.
    -response = client.get('http://testserver/homepage/')
    +response = client.get('/homepage/')
     assert response.status_code == 200
     csrftoken = response.cookies['csrftoken']
     
     # Interact with the API.
    -response = client.post('http://testserver/organisations/', json={
    +response = client.post('/organisations/', json={
         'name': 'MegaCorp',
         'status': 'active'
     }, headers={'X-CSRFToken': csrftoken})
    diff --git a/api-guide/throttling/index.html b/api-guide/throttling/index.html
    index 9e91dc074..a9d82654f 100644
    --- a/api-guide/throttling/index.html
    +++ b/api-guide/throttling/index.html
    @@ -61,7 +61,7 @@
               
    -          
                Search
    @@ -179,10 +179,6 @@
                         Permissions
                       
                       
    -                  
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - - -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -

    Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:

    @@ -568,8 +557,6 @@ urlpatterns = router.urls
  • action - the name of the current action (e.g., list, create).
  • detail - boolean indicating if the current action is configured for a list or detail view.
  • suffix - the display suffix for the viewset type - mirrors the detail attribute.
  • -
  • name - the display name for the viewset. This argument is mutually exclusive to suffix.
  • -
  • description - the display description for the individual view of a viewset.
  • You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this:

    def get_permissions(self):
    @@ -598,7 +585,7 @@ class UserViewSet(viewsets.ModelViewSet):
         queryset = User.objects.all()
         serializer_class = UserSerializer
     
    -    @action(detail=True, methods=['post'])
    +    @action(methods=['post'], detail=True)
         def set_password(self, request, pk=None):
             user = self.get_object()
             serializer = PasswordSerializer(data=request.data)
    @@ -623,30 +610,17 @@ class UserViewSet(viewsets.ModelViewSet):
             return Response(serializer.data)
     

    The decorator can additionally take extra arguments that will be set for the routed view only. For example:

    -
        @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
    +
        @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
         def set_password(self, request, pk=None):
            ...
     

    These decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example:

    -
        @action(detail=True, methods=['post', 'delete'])
    +
        @action(methods=['post', 'delete'], detail=True)
         def unset_password(self, request, pk=None):
            ...
     

    The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$

    To view all extra actions, call the .get_extra_actions() method.

    -

    Routing additional HTTP methods for extra actions

    -

    Extra actions can be mapped to different ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.

    -
        @action(detail=True, methods=['put'], name='Change Password')
    -    def password(self, request, pk=None):
    -        """Update the user's password."""
    -        ...
    -
    -    @password.mapping.delete
    -    def delete_password(self, request, pk=None):
    -        """Delete the user's password."""
    -        ...
    -
    -

    Reversing action URLs

    If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute.

    Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method.

    @@ -694,7 +668,7 @@ class UserViewSet(viewsets.ModelViewSet): def get_queryset(self): return self.request.user.accounts.all()
    -

    Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration.

    +

    Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration.

    Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.

    ReadOnlyModelViewSet

    The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().

    diff --git a/img/books/bda-cover.png b/img/books/bda-cover.png deleted file mode 100644 index 741fd24db..000000000 Binary files a/img/books/bda-cover.png and /dev/null differ diff --git a/img/books/rad-cover.png b/img/books/rad-cover.png deleted file mode 100644 index 75b19df64..000000000 Binary files a/img/books/rad-cover.png and /dev/null differ diff --git a/img/premium/load-impact-readme.png b/img/premium/load-impact-readme.png index 5dc6b9069..c46d36ada 100644 Binary files a/img/premium/load-impact-readme.png and b/img/premium/load-impact-readme.png differ diff --git a/index.html b/index.html index e37e9efe8..b90159b7f 100644 --- a/index.html +++ b/index.html @@ -179,10 +179,6 @@ Permissions -
  • - Caching -
  • -
  • Throttling
  • @@ -274,83 +270,76 @@ REST, Hypermedia & HATEOAS - - - -
  • + Tutorial +
  • + + + +
  • + API Guide +
  • + + + +
  • + Topics +
  • + + +
  • Development
  • @@ -499,6 +506,8 @@

    +
    +

    Note: This is the documentation for the version 3 of REST framework. Documentation for version 2 is also available.


    Funding

    REST framework is a collaboratively funded project. If you use REST framework commercially we strongly encourage you to invest in its -continued development by signing up for a paid plan.

    +continued development by signing up for a paid plan.

    Every single sign-up helps us make REST framework long-term financially sustainable.

    • Rover.com
    • @@ -545,8 +554,8 @@ continued development by signing up for a p

      Requirements

      REST framework requires the following:

        -
      • Python (2.7, 3.4, 3.5, 3.6, 3.7)
      • -
      • Django (1.11, 2.0, 2.1)
      • +
      • Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
      • +
      • Django (1.10, 1.11, 2.0)

      The following packages are optional:

        @@ -622,8 +631,81 @@ urlpatterns = [

        You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.

        Quickstart

        Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.

        +

        Tutorial

        +

        The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.

        + +

        There is a live example API of the finished tutorial API for testing purposes, available here.

        +

        API Guide

        +

        The API guide is your complete reference manual to all the functionality provided by REST framework.

        + +

        Topics

        +

        General guides to using REST framework.

        +

        Development

        -

        See the Contribution guidelines for information on how to clone +

        See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework.

        Support

        diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json index 9d9d1f42d..94e1e4a63 100644 --- a/mkdocs/search_index.json +++ b/mkdocs/search_index.json @@ -2,7 +2,7 @@ "docs": [ { "location": "/", - "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\n\n \n\n\n \n\n \n\n \n\n\n \n\n \n\n \n\n\n\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by internationally recognised companies including \nMozilla\n, \nRed Hat\n, \nHeroku\n, and \nEventbrite\n.\n\n\n\n\n\n\nFunding\n\n\nREST framework is a \ncollaboratively funded project\n. If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nEvery single sign-up helps us make REST framework long-term financially sustainable.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nRollbar\n\n \nCadre\n\n \nLoad Impact\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nRollbar\n, \nCadre\n, and \nLoad Impact\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.4, 3.5, 3.6, 3.7)\n\n\nDjango (1.11, 2.0, 2.1)\n\n\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (1.0.1+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:encode/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls'))\n]\n\n\n\nNote that the URL path can be whatever you want.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include 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\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2017, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", + "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\n\n \n\n\n \n\n \n\n \n\n\n \n\n \n\n \n\n\n\n\n\n\n\nNote\n: This is the documentation for the \nversion 3\n of REST framework. Documentation for \nversion 2\n is also available.\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by internationally recognised companies including \nMozilla\n, \nRed Hat\n, \nHeroku\n, and \nEventbrite\n.\n\n\n\n\n\n\nFunding\n\n\nREST framework is a \ncollaboratively funded project\n. If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nEvery single sign-up helps us make REST framework long-term financially sustainable.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nRollbar\n\n \nCadre\n\n \nLoad Impact\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nRollbar\n, \nCadre\n, and \nLoad Impact\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)\n\n\nDjango (1.10, 1.11, 2.0)\n\n\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (1.0.1+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:encode/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls'))\n]\n\n\n\nNote that the URL path can be whatever you want.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include 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\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nTutorial\n\n\nThe tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.\n\n\n\n\n1 - Serialization\n\n\n2 - Requests & Responses\n\n\n3 - Class-based views\n\n\n4 - Authentication & permissions\n\n\n5 - Relationships & hyperlinked APIs\n\n\n6 - Viewsets & routers\n\n\n7 - Schemas & client libraries\n\n\n\n\nThere is a live example API of the finished tutorial API for testing purposes, \navailable here\n.\n\n\nAPI Guide\n\n\nThe API guide is your complete reference manual to all the functionality provided by REST framework.\n\n\n\n\nRequests\n\n\nResponses\n\n\nViews\n\n\nGeneric views\n\n\nViewsets\n\n\nRouters\n\n\nParsers\n\n\nRenderers\n\n\nSerializers\n\n\nSerializer fields\n\n\nSerializer relations\n\n\nValidators\n\n\nAuthentication\n\n\nPermissions\n\n\nThrottling\n\n\nFiltering\n\n\nPagination\n\n\nVersioning\n\n\nContent negotiation\n\n\nMetadata\n\n\nSchemas\n\n\nFormat suffixes\n\n\nReturning URLs\n\n\nExceptions\n\n\nStatus codes\n\n\nTesting\n\n\nSettings\n\n\n\n\nTopics\n\n\nGeneral guides to using REST framework.\n\n\n\n\nDocumenting your API\n\n\nAPI Clients\n\n\nInternationalization\n\n\nAJAX, CSRF & CORS\n\n\nHTML & Forms\n\n\nBrowser enhancements\n\n\nThe Browsable API\n\n\nREST, Hypermedia & HATEOAS\n\n\nThird Party Packages\n\n\nTutorials and Resources\n\n\nContributing to REST framework\n\n\nProject management\n\n\n3.0 Announcement\n\n\n3.1 Announcement\n\n\n3.2 Announcement\n\n\n3.3 Announcement\n\n\n3.4 Announcement\n\n\n3.5 Announcement\n\n\n3.6 Announcement\n\n\n3.7 Announcement\n\n\n3.8 Announcement\n\n\nKickstarter Announcement\n\n\nMozilla Grant\n\n\nFunding\n\n\nRelease Notes\n\n\nJobs\n\n\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2017, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "title": "Home" }, { @@ -12,7 +12,7 @@ }, { "location": "/#requirements", - "text": "REST framework requires the following: Python (2.7, 3.4, 3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1) The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (1.0.1+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", + "text": "REST framework requires the following: Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6) Django (1.10, 1.11, 2.0) The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (1.0.1+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", "title": "Requirements" }, { @@ -30,6 +30,21 @@ "text": "Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.", "title": "Quickstart" }, + { + "location": "/#tutorial", + "text": "The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading. 1 - Serialization 2 - Requests & Responses 3 - Class-based views 4 - Authentication & permissions 5 - Relationships & hyperlinked APIs 6 - Viewsets & routers 7 - Schemas & client libraries There is a live example API of the finished tutorial API for testing purposes, available here .", + "title": "Tutorial" + }, + { + "location": "/#api-guide", + "text": "The API guide is your complete reference manual to all the functionality provided by REST framework. Requests Responses Views Generic views Viewsets Routers Parsers Renderers Serializers Serializer fields Serializer relations Validators Authentication Permissions Throttling Filtering Pagination Versioning Content negotiation Metadata Schemas Format suffixes Returning URLs Exceptions Status codes Testing Settings", + "title": "API Guide" + }, + { + "location": "/#topics", + "text": "General guides to using REST framework. Documenting your API API Clients Internationalization AJAX, CSRF & CORS HTML & Forms Browser enhancements The Browsable API REST, Hypermedia & HATEOAS Third Party Packages Tutorials and Resources Contributing to REST framework Project management 3.0 Announcement 3.1 Announcement 3.2 Announcement 3.3 Announcement 3.4 Announcement 3.5 Announcement 3.6 Announcement 3.7 Announcement 3.8 Announcement Kickstarter Announcement Mozilla Grant Funding Release Notes Jobs", + "title": "Topics" + }, { "location": "/#development", "text": "See the Contribution guidelines for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.", @@ -52,7 +67,7 @@ }, { "location": "/tutorial/quickstart/", - "text": "Quickstart\n\n\nWe're going to create a simple API to allow admin users to view and edit the users and groups in the system.\n\n\nProject setup\n\n\nCreate a new Django project named \ntutorial\n, then start a new app called \nquickstart\n.\n\n\n# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd ..\n\n\n\nThe project layout should look like:\n\n\n$ pwd\n/tutorial\n$ find .\n.\n./manage.py\n./tutorial\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py\n\n\n\nIt may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external module (topic goes outside the scope of the quickstart).\n\n\nNow sync your database for the first time:\n\n\npython manage.py migrate\n\n\n\nWe'll also create an initial user named \nadmin\n with a password of \npassword123\n. We'll authenticate as that user later in our example.\n\n\npython manage.py createsuperuser --email admin@example.com --username admin\n\n\n\nOnce you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...\n\n\nSerializers\n\n\nFirst up we're going to define some serializers. Let's create a new module named \ntutorial/quickstart/serializers.py\n that we'll use for our data representations.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'groups')\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = ('url', 'name')\n\n\n\nNotice that we're using hyperlinked relations in this case, with \nHyperlinkedModelSerializer\n. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.\n\n\nViews\n\n\nRight, we'd better write some views then. Open \ntutorial/quickstart/views.py\n and get typing.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets\nfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n\n\n\nRather than write multiple views we're grouping together all the common behavior into classes called \nViewSets\n.\n\n\nWe can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.\n\n\nURLs\n\n\nOkay, now let's wire up the API URLs. On to \ntutorial/urls.py\n...\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include 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\nBecause we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.\n\n\nAgain, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.\n\n\nFinally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.\n\n\nPagination\n\n\nPagination allows you to control how many objects per page are returned. To enable it add following lines to the \ntutorial/settings.py\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n}\n\n\n\nSettings\n\n\nAdd \n'rest_framework'\n to \nINSTALLED_APPS\n. The settings module will be in \ntutorial/settings.py\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nOkay, we're done.\n\n\n\n\nTesting our API\n\n\nWe're now ready to test the API we've built. Let's fire up the server from the command line.\n\n\npython manage.py runserver\n\n\n\nWe can now access our API, both from the command-line, using tools like \ncurl\n...\n\n\nbash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr using the \nhttpie\n, command line tool...\n\n\nbash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr directly through the browser, by going to the URL \nhttp://127.0.0.1:8000/users/\n...\n\n\n\n\nIf you're working through the browser, make sure to login using the control in the top right corner.\n\n\nGreat, that was easy!\n\n\nIf you want to get a more in depth understanding of how REST framework fits together head on over to \nthe tutorial\n, or start browsing the \nAPI guide\n.", + "text": "Quickstart\n\n\nWe're going to create a simple API to allow admin users to view and edit the users and groups in the system.\n\n\nProject setup\n\n\nCreate a new Django project named \ntutorial\n, then start a new app called \nquickstart\n.\n\n\n# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd ..\n\n\n\nThe project layout should look like:\n\n\n$ pwd\n/tutorial\n$ find .\n.\n./manage.py\n./tutorial\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py\n\n\n\nIt may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external module (topic goes outside the scope of the quickstart).\n\n\nNow sync your database for the first time:\n\n\npython manage.py migrate\n\n\n\nWe'll also create an initial user named \nadmin\n with a password of \npassword123\n. We'll authenticate as that user later in our example.\n\n\npython manage.py createsuperuser --email admin@example.com --username admin\n\n\n\nOnce you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...\n\n\nSerializers\n\n\nFirst up we're going to define some serializers. Let's create a new module named \ntutorial/quickstart/serializers.py\n that we'll use for our data representations.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'groups')\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = ('url', 'name')\n\n\n\nNotice that we're using hyperlinked relations in this case, with \nHyperlinkedModelSerializer\n. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.\n\n\nViews\n\n\nRight, we'd better write some views then. Open \ntutorial/quickstart/views.py\n and get typing.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets\nfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n\n\n\nRather than write multiple views we're grouping together all the common behavior into classes called \nViewSets\n.\n\n\nWe can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.\n\n\nURLs\n\n\nOkay, now let's wire up the API URLs. On to \ntutorial/urls.py\n...\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include 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\nBecause we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.\n\n\nAgain, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.\n\n\nFinally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.\n\n\nSettings\n\n\nAdd \n'rest_framework'\n to \nINSTALLED_APPS\n. The settings module will be in \ntutorial/settings.py\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nOkay, we're done.\n\n\n\n\nTesting our API\n\n\nWe're now ready to test the API we've built. Let's fire up the server from the command line.\n\n\npython manage.py runserver\n\n\n\nWe can now access our API, both from the command-line, using tools like \ncurl\n...\n\n\nbash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr using the \nhttpie\n, command line tool...\n\n\nbash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr directly through the browser, by going to the URL \nhttp://127.0.0.1:8000/users/\n...\n\n\n\n\nIf you're working through the browser, make sure to login using the control in the top right corner.\n\n\nGreat, that was easy!\n\n\nIf you want to get a more in depth understanding of how REST framework fits together head on over to \nthe tutorial\n, or start browsing the \nAPI guide\n.", "title": "Quickstart" }, { @@ -62,7 +77,7 @@ }, { "location": "/tutorial/quickstart/#project-setup", - "text": "Create a new Django project named tutorial , then start a new app called quickstart . # Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd .. The project layout should look like: $ pwd\n/tutorial\n$ find .\n.\n./manage.py\n./tutorial\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external module (topic goes outside the scope of the quickstart). Now sync your database for the first time: python manage.py migrate We'll also create an initial user named admin with a password of password123 . We'll authenticate as that user later in our example. python manage.py createsuperuser --email admin@example.com --username admin Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...", + "text": "Create a new Django project named tutorial , then start a new app called quickstart . # Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd .. The project layout should look like: $ pwd\n/tutorial\n$ find .\n.\n./manage.py\n./tutorial\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external module (topic goes outside the scope of the quickstart). Now sync your database for the first time: python manage.py migrate We'll also create an initial user named admin with a password of password123 . We'll authenticate as that user later in our example. python manage.py createsuperuser --email admin@example.com --username admin Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...", "title": "Project setup" }, { @@ -80,11 +95,6 @@ "text": "Okay, now let's wire up the API URLs. On to tutorial/urls.py ... from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include 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] Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly. Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.", "title": "URLs" }, - { - "location": "/tutorial/quickstart/#pagination", - "text": "Pagination allows you to control how many objects per page are returned. To enable it add following lines to the tutorial/settings.py REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n}", - "title": "Pagination" - }, { "location": "/tutorial/quickstart/#settings", "text": "Add 'rest_framework' to INSTALLED_APPS . The settings module will be in tutorial/settings.py INSTALLED_APPS = (\n ...\n 'rest_framework',\n) Okay, we're done.", @@ -97,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 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\nimport io\n\nstream = io.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# \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\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse, JsonResponse\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\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, safe=False)\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.urls import path\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.snippet_list),\n path('snippets//', 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.urls import path, include\n\nurlpatterns = [\n path('', 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.11, 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# \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\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse, JsonResponse\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\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, safe=False)\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[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.11, 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" }, { @@ -132,7 +142,7 @@ }, { "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# {'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... import io\n\nstream = io.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# 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')])]", + "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# 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" }, { @@ -142,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. Edit the snippets/views.py file, and add the following. from django.http import HttpResponse, JsonResponse\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 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, safe=False)\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.urls import path\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.snippet_list),\n path('snippets//', 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.urls import path, include\n\nurlpatterns = [\n path('', 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. Edit the snippets/views.py file, and add the following. from django.http import HttpResponse, JsonResponse\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 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, safe=False)\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[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" }, { @@ -157,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 any more, 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 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 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 code snippet.\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 \nsnippets/urls.py\n file slightly, to append a set of \nformat_suffix_patterns\n in addition to the existing URLs.\n\n\nfrom django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.snippet_list),\n path('snippets/', 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 any more, 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 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 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 code snippet.\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 \nsnippets/urls.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[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" }, { @@ -192,7 +202,7 @@ }, { "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 snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs. from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.snippet_list),\n path('snippets/', 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, pk, format=None): Now update the snippets/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[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" }, { @@ -212,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 \nsnippets/urls.py\n slightly now that we're using class-based views.\n\n\nfrom django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.SnippetList.as_view()),\n path('snippets//', 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, 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 \nsnippets/urls.py\n slightly now that 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[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" }, { @@ -222,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 snippets/urls.py slightly now that we're using class-based views. from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path('snippets/', views.SnippetList.as_view()),\n path('snippets//', 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, 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 snippets/urls.py slightly now that 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[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" }, { @@ -237,7 +247,7 @@ }, { "location": "/tutorial/4-authentication-and-permissions/", - "text": "Tutorial 4: Authentication & 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', on_delete=models.CASCADE)\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 = 'table' if self.linenos else False\n options = {'title': self.title} if self.title else {}\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 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 \nsnippets/urls.py\n.\n\n\npath('users/', views.UserList.as_view()),\npath('users//', 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 path('api-auth/', include('rest_framework.urls')),\n]\n\n\n\nThe \n'api-auth/'\n part of pattern can actually be whatever URL you want to use.\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 admin:password123 POST http://127.0.0.1:8000/snippets/ code=\"print 789\"\n\n{\n \"id\": 1,\n \"owner\": \"admin\",\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 & 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', on_delete=models.CASCADE)\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 = 'table' if self.linenos else False\n options = {'title': self.title} if self.title else {}\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 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[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]\n\n\n\nThe \nr'^api-auth/'\n part of pattern can actually be whatever URL you want to use.\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 admin:password123 POST http://127.0.0.1:8000/snippets/ code=\"print 789\"\n\n{\n \"id\": 1,\n \"owner\": \"admin\",\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" }, { @@ -252,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 snippets/urls.py . path('users/', views.UserList.as_view()),\npath('users//', 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[0-9]+)/$', views.UserDetail.as_view()),", "title": "Adding endpoints for our User models" }, { @@ -272,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 path('api-auth/', include('rest_framework.urls')),\n] The 'api-auth/' part of pattern can actually be whatever URL you want to use. 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.", + "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] The r'^api-auth/' part of pattern can actually be whatever URL you want to use. 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" }, { @@ -292,7 +302,7 @@ }, { "location": "/tutorial/5-relationships-and-hyperlinked-apis/", - "text": "Tutorial 5: Relationships & 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\npath('', views.api_root),\n\n\n\nAnd then add a url pattern for the snippet highlights:\n\n\npath('snippets//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 path('', views.api_root),\n path('snippets/',\n views.SnippetList.as_view(),\n name='snippet-list'),\n path('snippets//',\n views.SnippetDetail.as_view(),\n name='snippet-detail'),\n path('snippets//highlight/',\n views.SnippetHighlight.as_view(),\n name='snippet-highlight'),\n path('users/',\n views.UserList.as_view(),\n name='user-list'),\n path('users//',\n views.UserDetail.as_view(),\n name='user-detail')\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 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n}\n\n\n\nNote that settings in REST framework are all namespaced into a single dictionary setting, named \nREST_FRAMEWORK\n, 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 & 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[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[0-9]+)/$',\n views.SnippetDetail.as_view(),\n name='snippet-detail'),\n url(r'^snippets/(?P[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[0-9]+)/$',\n views.UserDetail.as_view(),\n name='user-detail')\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 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n}\n\n\n\nNote that settings in REST framework are all namespaced into a single dictionary setting, named \nREST_FRAMEWORK\n, 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" }, { @@ -307,7 +317,7 @@ }, { "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 : path('', views.api_root), And then add a url pattern for the snippet highlights: path('snippets//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[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),", "title": "Creating an endpoint for the highlighted snippets" }, { @@ -317,7 +327,7 @@ }, { "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 path('', views.api_root),\n path('snippets/',\n views.SnippetList.as_view(),\n name='snippet-list'),\n path('snippets//',\n views.SnippetDetail.as_view(),\n name='snippet-detail'),\n path('snippets//highlight/',\n views.SnippetHighlight.as_view(),\n name='snippet-highlight'),\n path('users/',\n views.UserList.as_view(),\n name='user-list'),\n path('users//',\n views.UserDetail.as_view(),\n name='user-detail')\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[0-9]+)/$',\n views.SnippetDetail.as_view(),\n name='snippet-detail'),\n url(r'^snippets/(?P[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[0-9]+)/$',\n views.UserDetail.as_view(),\n name='user-detail')\n])", "title": "Making sure our URL patterns are named" }, { @@ -332,7 +342,7 @@ }, { "location": "/tutorial/6-viewsets-and-routers/", - "text": "Tutorial 6: ViewSets & 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 action\nfrom rest_framework.response import Response\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 @action(detail=True, 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@action\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@action\n decorator will respond to \nGET\n requests by default. 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 \nurl_path\n 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 \nsnippets/urls.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 path('', api_root),\n path('snippets/', snippet_list, name='snippet-list'),\n path('snippets//', snippet_detail, name='snippet-detail'),\n path('snippets//highlight/', snippet_highlight, name='snippet-highlight'),\n path('users/', user_list, name='user-list'),\n path('users//', 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 \nsnippets/urls.py\n file.\n\n\nfrom django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom snippets import views\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.\nurlpatterns = [\n path('', include(router.urls)),\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 & 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 action\nfrom rest_framework.response import Response\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 @action(detail=True, 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@action\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@action\n decorator will respond to \nGET\n requests by default. 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 \nurl_path\n 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 \nsnippets/urls.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[0-9]+)/$', snippet_detail, name='snippet-detail'),\n url(r'^snippets/(?P[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n url(r'^users/$', user_list, name='user-list'),\n url(r'^users/(?P[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 \nsnippets/urls.py\n file.\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework.routers import DefaultRouter\nfrom snippets import views\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.\nurlpatterns = [\n url(r'^', include(router.urls))\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" }, { @@ -347,12 +357,12 @@ }, { "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 snippets/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 path('', api_root),\n path('snippets/', snippet_list, name='snippet-list'),\n path('snippets//', snippet_detail, name='snippet-detail'),\n path('snippets//highlight/', snippet_highlight, name='snippet-highlight'),\n path('users/', user_list, name='user-list'),\n path('users//', 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 snippets/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[0-9]+)/$', snippet_detail, name='snippet-detail'),\n url(r'^snippets/(?P[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),\n url(r'^users/$', user_list, name='user-list'),\n url(r'^users/(?P[0-9]+)/$', user_detail, name='user-detail')\n])", "title": "Binding ViewSets to URLs explicitly" }, { "location": "/tutorial/6-viewsets-and-routers/#using-routers", - "text": "Because we're using ViewSet classes rather than View 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 Router class. All we need to do is register the appropriate view sets with a router, and let it do the rest. Here's our re-wired snippets/urls.py file. from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom snippets import views\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.\nurlpatterns = [\n path('', include(router.urls)),\n] Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself. The DefaultRouter class we're using also automatically creates the API root view for us, so we can now delete the api_root method from our views module.", + "text": "Because we're using ViewSet classes rather than View 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 Router class. All we need to do is register the appropriate view sets with a router, and let it do the rest. Here's our re-wired snippets/urls.py file. from django.conf.urls import url, include\nfrom rest_framework.routers import DefaultRouter\nfrom snippets import views\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.\nurlpatterns = [\n url(r'^', include(router.urls))\n] Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself. The DefaultRouter class we're using also automatically creates the API root view for us, so we can now delete the api_root method from our views module.", "title": "Using Routers" }, { @@ -362,7 +372,7 @@ }, { "location": "/tutorial/7-schemas-and-client-libraries/", - "text": "Tutorial 7: Schemas & 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 \u00a0 \u00a0path('schema/', schema_view),\n ...\n]\n\n\n\n\nIf you visit the \n/schema/\n 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/coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/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\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\n\n\n Example\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 \n\n and \n\n below with your\nactual username and password.\n\n\n$ coreapi credentials add 127.0.0.1 : --auth basic\nAdded credentials\n127.0.0.1 \"Basic <...>\"\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 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.", + "text": "Tutorial 7: Schemas & 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 \u00a0 \u00a0url(r'^schema/$', schema_view),\n ...\n]\n\n\n\n\nIf you visit the \n/schema/\n 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/coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/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\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\n\n\n Example\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 \n\n and \n\n below with your\nactual username and password.\n\n\n$ coreapi credentials add 127.0.0.1 : --auth basic\nAdded credentials\n127.0.0.1 \"Basic <...>\"\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 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" }, { @@ -377,7 +387,7 @@ }, { "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 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 \u00a0 \u00a0path('schema/', schema_view),\n ...\n] If you visit the /schema/ 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/coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/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 \u00a0 \u00a0url(r'^schema/$', schema_view),\n ...\n] If you visit the /schema/ 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/coreapi+json\nHTTP/1.0 200 OK\nAllow: GET, HEAD, OPTIONS\nContent-Type: application/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" }, { @@ -882,7 +892,7 @@ }, { "location": "/api-guide/viewsets/", - "text": "ViewSets\n\n\n\n\nAfter routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.\n\n\n\u2014 \nRuby on Rails Documentation\n\n\n\n\nDjango REST framework allows you to combine the logic for a set of related views in a single class, called a \nViewSet\n. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.\n\n\nA \nViewSet\n class is simply \na type of class-based View, that does not provide any method handlers\n such as \n.get()\n or \n.post()\n, and instead provides actions such as \n.list()\n and \n.create()\n.\n\n\nThe method handlers for a \nViewSet\n are only bound to the corresponding actions at the point of finalizing the view, using the \n.as_view()\n method.\n\n\nTypically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.\n\n\nExample\n\n\nLet's define a simple viewset that can be used to list or retrieve all the users in the system.\n\n\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data)\n\n\n\nIf we need to, we can bind this viewset into two separate views, like so:\n\n\nuser_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'})\n\n\n\nTypically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.\n\n\nfrom myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, basename='user')\nurlpatterns = router.urls\n\n\n\nRather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all()\n\n\n\nThere are two main advantages of using a \nViewSet\n class over using a \nView\n class.\n\n\n\n\nRepeated logic can be combined into a single class. In the above example, we only need to specify the \nqueryset\n once, and it'll be used across multiple views.\n\n\nBy using routers, we no longer need to deal with wiring up the URL conf ourselves.\n\n\n\n\nBoth of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.\n\n\nViewSet actions\n\n\nThe default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:\n\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n Example empty viewset demonstrating the standard\n actions that will be handled by a router class.\n\n If you're using format suffixes, make sure to also include\n the `format=None` keyword argument for each action.\n \"\"\"\n\n def list(self, request):\n pass\n\n def create(self, request):\n pass\n\n def retrieve(self, request, pk=None):\n pass\n\n def update(self, request, pk=None):\n pass\n\n def partial_update(self, request, pk=None):\n pass\n\n def destroy(self, request, pk=None):\n pass\n\n\n\nIntrospecting ViewSet actions\n\n\nDuring dispatch, the following attributes are available on the \nViewSet\n.\n\n\n\n\nbasename\n - the base to use for the URL names that are created.\n\n\naction\n - the name of the current action (e.g., \nlist\n, \ncreate\n).\n\n\ndetail\n - boolean indicating if the current action is configured for a list or detail view.\n\n\nsuffix\n - the display suffix for the viewset type - mirrors the \ndetail\n attribute.\n\n\nname\n - the display name for the viewset. This argument is mutually exclusive to \nsuffix\n.\n\n\ndescription\n - the display description for the individual view of a viewset.\n\n\n\n\nYou may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the \nlist\n action similar to this:\n\n\ndef get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]\n\n\n\nMarking extra actions for routing\n\n\nIf you have ad-hoc methods that should be routable, you can mark them as such with the \n@action\n decorator. Like regular actions, extra actions may be intended for either a list of objects, or a single instance. To indicate this, set the \ndetail\n argument to \nTrue\n or \nFalse\n. The router will configure its URL patterns accordingly. e.g., the \nDefaultRouter\n will configure detail actions to contain \npk\n in their URL patterns.\n\n\nA more complete example of extra actions:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(detail=True, methods=['post'])\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data)\n\n\n\nThe decorator can additionally take extra arguments that will be set for the routed view only. For example:\n\n\n @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n\n\n\nThese decorator will route \nGET\n requests by default, but may also accept other HTTP methods by setting the \nmethods\n argument. For example:\n\n\n @action(detail=True, methods=['post', 'delete'])\n def unset_password(self, request, pk=None):\n ...\n\n\n\nThe two new actions will then be available at the urls \n^users/{pk}/set_password/$\n and \n^users/{pk}/unset_password/$\n\n\nTo view all extra actions, call the \n.get_extra_actions()\n method.\n\n\nRouting additional HTTP methods for extra actions\n\n\nExtra actions can be mapped to different \nViewSet\n methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.\n\n\n @action(detail=True, methods=['put'], name='Change Password')\n def password(self, request, pk=None):\n \"\"\"Update the user's password.\"\"\"\n ...\n\n @password.mapping.delete\n def delete_password(self, request, pk=None):\n \"\"\"Delete the user's password.\"\"\"\n ...\n\n\n\n\nReversing action URLs\n\n\nIf you need to get the URL of an action, use the \n.reverse_action()\n method. This is a convenience wrapper for \nreverse()\n, automatically passing the view's \nrequest\n object and prepending the \nurl_name\n with the \n.basename\n attribute.\n\n\nNote that the \nbasename\n is provided by the router during \nViewSet\n registration. If you are not using a router, then you must provide the \nbasename\n argument to the \n.as_view()\n method.\n\n\nUsing the example from the previous section:\n\n\n>>> view.reverse_action('set-password', args=['1'])\n'http://localhost:8000/api/users/1/set_password'\n\n\n\n\nAlternatively, you can use the \nurl_name\n attribute set by the \n@action\n decorator.\n\n\n>>> view.reverse_action(view.set_password.url_name, args=['1'])\n'http://localhost:8000/api/users/1/set_password'\n\n\n\n\nThe \nurl_name\n argument for \n.reverse_action()\n should match the same argument to the \n@action\n decorator. Additionally, this method can be used to reverse the default actions, such as \nlist\n and \ncreate\n.\n\n\n\n\nAPI Reference\n\n\nViewSet\n\n\nThe \nViewSet\n class inherits from \nAPIView\n. You can use any of the standard attributes such as \npermission_classes\n, \nauthentication_classes\n in order to control the API policy on the viewset.\n\n\nThe \nViewSet\n class does not provide any implementations of actions. In order to use a \nViewSet\n class you'll override the class and define the action implementations explicitly.\n\n\nGenericViewSet\n\n\nThe \nGenericViewSet\n class inherits from \nGenericAPIView\n, and provides the default set of \nget_object\n, \nget_queryset\n methods and other generic view base behavior, but does not include any actions by default.\n\n\nIn order to use a \nGenericViewSet\n class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.\n\n\nModelViewSet\n\n\nThe \nModelViewSet\n class inherits from \nGenericAPIView\n and includes implementations for various actions, by mixing in the behavior of the various mixin classes.\n\n\nThe actions provided by the \nModelViewSet\n class are \n.list()\n, \n.retrieve()\n, \n.create()\n, \n.update()\n, \n.partial_update()\n, and \n.destroy()\n.\n\n\nExample\n\n\nBecause \nModelViewSet\n extends \nGenericAPIView\n, you'll normally need to provide at least the \nqueryset\n and \nserializer_class\n attributes. For example:\n\n\nclass AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n\n\nNote that you can use any of the standard attributes or method overrides provided by \nGenericAPIView\n. For example, to use a \nViewSet\n that dynamically determines the queryset it should operate on, you might do something like this:\n\n\nclass AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all()\n\n\n\nNote however that upon removal of the \nqueryset\n property from your \nViewSet\n, any associated \nrouter\n will be unable to derive the basename of your Model automatically, and so you will have to specify the \nbasename\n kwarg as part of your \nrouter registration\n.\n\n\nAlso note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.\n\n\nReadOnlyModelViewSet\n\n\nThe \nReadOnlyModelViewSet\n class also inherits from \nGenericAPIView\n. As with \nModelViewSet\n it also includes implementations for various actions, but unlike \nModelViewSet\n only provides the 'read-only' actions, \n.list()\n and \n.retrieve()\n.\n\n\nExample\n\n\nAs with \nModelViewSet\n, you'll normally need to provide at least the \nqueryset\n and \nserializer_class\n attributes. For example:\n\n\nclass AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n\n\n\nAgain, as with \nModelViewSet\n, you can use any of the standard attributes and method overrides available to \nGenericAPIView\n.\n\n\nCustom ViewSet base classes\n\n\nYou may need to provide custom \nViewSet\n classes that do not have the full set of \nModelViewSet\n actions, or that customize the behavior in some other way.\n\n\nExample\n\n\nTo create a base viewset class that provides \ncreate\n, \nlist\n and \nretrieve\n operations, inherit from \nGenericViewSet\n, and mixin the required actions:\n\n\nfrom rest_framework import mixins\n\nclass CreateListRetrieveViewSet(mixins.CreateModelMixin,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n A viewset that provides `retrieve`, `create`, and `list` actions.\n\n To use it, override the class and set the `.queryset` and\n `.serializer_class` attributes.\n \"\"\"\n pass\n\n\n\nBy creating your own base \nViewSet\n classes, you can provide common behavior that can be reused in multiple viewsets across your API.", + "text": "ViewSets\n\n\n\n\nAfter routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.\n\n\n\u2014 \nRuby on Rails Documentation\n\n\n\n\nDjango REST framework allows you to combine the logic for a set of related views in a single class, called a \nViewSet\n. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.\n\n\nA \nViewSet\n class is simply \na type of class-based View, that does not provide any method handlers\n such as \n.get()\n or \n.post()\n, and instead provides actions such as \n.list()\n and \n.create()\n.\n\n\nThe method handlers for a \nViewSet\n are only bound to the corresponding actions at the point of finalizing the view, using the \n.as_view()\n method.\n\n\nTypically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.\n\n\nExample\n\n\nLet's define a simple viewset that can be used to list or retrieve all the users in the system.\n\n\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data)\n\n\n\nIf we need to, we can bind this viewset into two separate views, like so:\n\n\nuser_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'})\n\n\n\nTypically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.\n\n\nfrom myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, base_name='user')\nurlpatterns = router.urls\n\n\n\nRather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all()\n\n\n\nThere are two main advantages of using a \nViewSet\n class over using a \nView\n class.\n\n\n\n\nRepeated logic can be combined into a single class. In the above example, we only need to specify the \nqueryset\n once, and it'll be used across multiple views.\n\n\nBy using routers, we no longer need to deal with wiring up the URL conf ourselves.\n\n\n\n\nBoth of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.\n\n\nViewSet actions\n\n\nThe default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:\n\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n Example empty viewset demonstrating the standard\n actions that will be handled by a router class.\n\n If you're using format suffixes, make sure to also include\n the `format=None` keyword argument for each action.\n \"\"\"\n\n def list(self, request):\n pass\n\n def create(self, request):\n pass\n\n def retrieve(self, request, pk=None):\n pass\n\n def update(self, request, pk=None):\n pass\n\n def partial_update(self, request, pk=None):\n pass\n\n def destroy(self, request, pk=None):\n pass\n\n\n\nIntrospecting ViewSet actions\n\n\nDuring dispatch, the following attributes are available on the \nViewSet\n.\n\n\n\n\nbasename\n - the base to use for the URL names that are created.\n\n\naction\n - the name of the current action (e.g., \nlist\n, \ncreate\n).\n\n\ndetail\n - boolean indicating if the current action is configured for a list or detail view.\n\n\nsuffix\n - the display suffix for the viewset type - mirrors the \ndetail\n attribute.\n\n\n\n\nYou may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the \nlist\n action similar to this:\n\n\ndef get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]\n\n\n\nMarking extra actions for routing\n\n\nIf you have ad-hoc methods that should be routable, you can mark them as such with the \n@action\n decorator. Like regular actions, extra actions may be intended for either a list of objects, or a single instance. To indicate this, set the \ndetail\n argument to \nTrue\n or \nFalse\n. The router will configure its URL patterns accordingly. e.g., the \nDefaultRouter\n will configure detail actions to contain \npk\n in their URL patterns.\n\n\nA more complete example of extra actions:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(methods=['post'], detail=True)\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data)\n\n\n\nThe decorator can additionally take extra arguments that will be set for the routed view only. For example:\n\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n\n\n\nThese decorator will route \nGET\n requests by default, but may also accept other HTTP methods by setting the \nmethods\n argument. For example:\n\n\n @action(methods=['post', 'delete'], detail=True)\n def unset_password(self, request, pk=None):\n ...\n\n\n\nThe two new actions will then be available at the urls \n^users/{pk}/set_password/$\n and \n^users/{pk}/unset_password/$\n\n\nTo view all extra actions, call the \n.get_extra_actions()\n method.\n\n\nReversing action URLs\n\n\nIf you need to get the URL of an action, use the \n.reverse_action()\n method. This is a convenience wrapper for \nreverse()\n, automatically passing the view's \nrequest\n object and prepending the \nurl_name\n with the \n.basename\n attribute.\n\n\nNote that the \nbasename\n is provided by the router during \nViewSet\n registration. If you are not using a router, then you must provide the \nbasename\n argument to the \n.as_view()\n method.\n\n\nUsing the example from the previous section:\n\n\n>>> view.reverse_action('set-password', args=['1'])\n'http://localhost:8000/api/users/1/set_password'\n\n\n\n\nAlternatively, you can use the \nurl_name\n attribute set by the \n@action\n decorator.\n\n\n>>> view.reverse_action(view.set_password.url_name, args=['1'])\n'http://localhost:8000/api/users/1/set_password'\n\n\n\n\nThe \nurl_name\n argument for \n.reverse_action()\n should match the same argument to the \n@action\n decorator. Additionally, this method can be used to reverse the default actions, such as \nlist\n and \ncreate\n.\n\n\n\n\nAPI Reference\n\n\nViewSet\n\n\nThe \nViewSet\n class inherits from \nAPIView\n. You can use any of the standard attributes such as \npermission_classes\n, \nauthentication_classes\n in order to control the API policy on the viewset.\n\n\nThe \nViewSet\n class does not provide any implementations of actions. In order to use a \nViewSet\n class you'll override the class and define the action implementations explicitly.\n\n\nGenericViewSet\n\n\nThe \nGenericViewSet\n class inherits from \nGenericAPIView\n, and provides the default set of \nget_object\n, \nget_queryset\n methods and other generic view base behavior, but does not include any actions by default.\n\n\nIn order to use a \nGenericViewSet\n class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.\n\n\nModelViewSet\n\n\nThe \nModelViewSet\n class inherits from \nGenericAPIView\n and includes implementations for various actions, by mixing in the behavior of the various mixin classes.\n\n\nThe actions provided by the \nModelViewSet\n class are \n.list()\n, \n.retrieve()\n, \n.create()\n, \n.update()\n, \n.partial_update()\n, and \n.destroy()\n.\n\n\nExample\n\n\nBecause \nModelViewSet\n extends \nGenericAPIView\n, you'll normally need to provide at least the \nqueryset\n and \nserializer_class\n attributes. For example:\n\n\nclass AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n\n\nNote that you can use any of the standard attributes or method overrides provided by \nGenericAPIView\n. For example, to use a \nViewSet\n that dynamically determines the queryset it should operate on, you might do something like this:\n\n\nclass AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all()\n\n\n\nNote however that upon removal of the \nqueryset\n property from your \nViewSet\n, any associated \nrouter\n will be unable to derive the base_name of your Model automatically, and so you will have to specify the \nbase_name\n kwarg as part of your \nrouter registration\n.\n\n\nAlso note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.\n\n\nReadOnlyModelViewSet\n\n\nThe \nReadOnlyModelViewSet\n class also inherits from \nGenericAPIView\n. As with \nModelViewSet\n it also includes implementations for various actions, but unlike \nModelViewSet\n only provides the 'read-only' actions, \n.list()\n and \n.retrieve()\n.\n\n\nExample\n\n\nAs with \nModelViewSet\n, you'll normally need to provide at least the \nqueryset\n and \nserializer_class\n attributes. For example:\n\n\nclass AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n\n\n\nAgain, as with \nModelViewSet\n, you can use any of the standard attributes and method overrides available to \nGenericAPIView\n.\n\n\nCustom ViewSet base classes\n\n\nYou may need to provide custom \nViewSet\n classes that do not have the full set of \nModelViewSet\n actions, or that customize the behavior in some other way.\n\n\nExample\n\n\nTo create a base viewset class that provides \ncreate\n, \nlist\n and \nretrieve\n operations, inherit from \nGenericViewSet\n, and mixin the required actions:\n\n\nfrom rest_framework import mixins\n\nclass CreateListRetrieveViewSet(mixins.CreateModelMixin,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n A viewset that provides `retrieve`, `create`, and `list` actions.\n\n To use it, override the class and set the `.queryset` and\n `.serializer_class` attributes.\n \"\"\"\n pass\n\n\n\nBy creating your own base \nViewSet\n classes, you can provide common behavior that can be reused in multiple viewsets across your API.", "title": "Viewsets" }, { @@ -892,7 +902,7 @@ }, { "location": "/api-guide/viewsets/#example", - "text": "Let's define a simple viewset that can be used to list or retrieve all the users in the system. from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data) If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'}) Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, basename='user')\nurlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all() There are two main advantages of using a ViewSet class over using a View class. Repeated logic can be combined into a single class. In the above example, we only need to specify the queryset once, and it'll be used across multiple views. By using routers, we no longer need to deal with wiring up the URL conf ourselves. Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.", + "text": "Let's define a simple viewset that can be used to list or retrieve all the users in the system. from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data) If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'}) Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, base_name='user')\nurlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all() There are two main advantages of using a ViewSet class over using a View class. Repeated logic can be combined into a single class. In the above example, we only need to specify the queryset once, and it'll be used across multiple views. By using routers, we no longer need to deal with wiring up the URL conf ourselves. Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.", "title": "Example" }, { @@ -902,19 +912,14 @@ }, { "location": "/api-guide/viewsets/#introspecting-viewset-actions", - "text": "During dispatch, the following attributes are available on the ViewSet . basename - the base to use for the URL names that are created. action - the name of the current action (e.g., list , create ). detail - boolean indicating if the current action is configured for a list or detail view. suffix - the display suffix for the viewset type - mirrors the detail attribute. name - the display name for the viewset. This argument is mutually exclusive to suffix . description - the display description for the individual view of a viewset. You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this: def get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]", + "text": "During dispatch, the following attributes are available on the ViewSet . basename - the base to use for the URL names that are created. action - the name of the current action (e.g., list , create ). detail - boolean indicating if the current action is configured for a list or detail view. suffix - the display suffix for the viewset type - mirrors the detail attribute. You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this: def get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]", "title": "Introspecting ViewSet actions" }, { "location": "/api-guide/viewsets/#marking-extra-actions-for-routing", - "text": "If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a list of objects, or a single instance. To indicate this, set the detail argument to True or False . The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns. A more complete example of extra actions: from django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(detail=True, methods=['post'])\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data) The decorator can additionally take extra arguments that will be set for the routed view only. For example: @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ... These decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example: @action(detail=True, methods=['post', 'delete'])\n def unset_password(self, request, pk=None):\n ... The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$ To view all extra actions, call the .get_extra_actions() method.", + "text": "If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a list of objects, or a single instance. To indicate this, set the detail argument to True or False . The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns. A more complete example of extra actions: from django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(methods=['post'], detail=True)\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data) The decorator can additionally take extra arguments that will be set for the routed view only. For example: @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ... These decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example: @action(methods=['post', 'delete'], detail=True)\n def unset_password(self, request, pk=None):\n ... The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$ To view all extra actions, call the .get_extra_actions() method.", "title": "Marking extra actions for routing" }, - { - "location": "/api-guide/viewsets/#routing-additional-http-methods-for-extra-actions", - "text": "Extra actions can be mapped to different ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. @action(detail=True, methods=['put'], name='Change Password')\n def password(self, request, pk=None):\n \"\"\"Update the user's password.\"\"\"\n ...\n\n @password.mapping.delete\n def delete_password(self, request, pk=None):\n \"\"\"Delete the user's password.\"\"\"\n ...", - "title": "Routing additional HTTP methods for extra actions" - }, { "location": "/api-guide/viewsets/#reversing-action-urls", "text": "If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse() , automatically passing the view's request object and prepending the url_name with the .basename attribute. Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method. Using the example from the previous section: >>> view.reverse_action('set-password', args=['1'])\n'http://localhost:8000/api/users/1/set_password' Alternatively, you can use the url_name attribute set by the @action decorator. >>> view.reverse_action(view.set_password.url_name, args=['1'])\n'http://localhost:8000/api/users/1/set_password' The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create .", @@ -942,7 +947,7 @@ }, { "location": "/api-guide/viewsets/#example_1", - "text": "Because ModelViewSet extends GenericAPIView , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView . For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet , any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration . Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.", + "text": "Because ModelViewSet extends GenericAPIView , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView . For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet , any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration . Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.", "title": "Example" }, { @@ -967,7 +972,7 @@ }, { "location": "/api-guide/routers/", - "text": "Routers\n\n\n\n\nResource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.\n\n\n\u2014 \nRuby on Rails Documentation\n\n\n\n\nSome Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.\n\n\nREST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.\n\n\nUsage\n\n\nHere's an example of a simple URL conf, that uses \nSimpleRouter\n.\n\n\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls\n\n\n\nThere are two mandatory arguments to the \nregister()\n method:\n\n\n\n\nprefix\n - The URL prefix to use for this set of routes.\n\n\nviewset\n - The viewset class.\n\n\n\n\nOptionally, you may also specify an additional argument:\n\n\n\n\nbasename\n - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the \nqueryset\n attribute of the viewset, if it has one. Note that if the viewset does not include a \nqueryset\n attribute then you must set \nbasename\n when registering the viewset.\n\n\n\n\nThe example above would generate the following URL patterns:\n\n\n\n\nURL pattern: \n^users/$\n Name: \n'user-list'\n\n\nURL pattern: \n^users/{pk}/$\n Name: \n'user-detail'\n\n\nURL pattern: \n^accounts/$\n Name: \n'account-list'\n\n\nURL pattern: \n^accounts/{pk}/$\n Name: \n'account-detail'\n\n\n\n\n\n\nNote\n: The \nbasename\n argument is used to specify the initial part of the view name pattern. In the example above, that's the \nuser\n or \naccount\n part.\n\n\nTypically you won't \nneed\n to specify the \nbasename\n argument, but if you have a viewset where you've defined a custom \nget_queryset\n method, then the viewset may not have a \n.queryset\n attribute set. If you try to register that viewset you'll see an error like this:\n\n\n'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.\n\n\n\nThis means you'll need to explicitly set the \nbasename\n argument when registering the viewset, as it could not be automatically determined from the model name.\n\n\n\n\nUsing \ninclude\n with routers\n\n\nThe \n.urls\n attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.\n\n\nFor example, you can append \nrouter.urls\n to a list of existing views...\n\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls\n\n\n\nAlternatively you can use Django's \ninclude\n function, like so...\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n]\n\n\n\nYou may use \ninclude\n with an application namespace:\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'))),\n]\n\n\n\nOr both an application and instance namespace:\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),\n]\n\n\n\nSee Django's \nURL namespaces docs\n and the \ninclude\n API reference\n for more details.\n\n\n\n\nNote\n: If using namespacing with hyperlinked serializers you'll also need to ensure that any \nview_name\n parameters\non the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as\n\nview_name='app_name:user-detail'\n for serializer fields hyperlinked to the user detail view.\n\n\nThe automatic \nview_name\n generation uses a pattern like \n%(model_name)-detail\n. Unless your models names actually clash\nyou may be better off \nnot\n namespacing your Django REST Framework views when using hyperlinked serializers.\n\n\n\n\nRouting for extra actions\n\n\nA viewset may \nmark extra actions for routing\n by decorating a method with the \n@action\n decorator. These extra actions will be included in the generated routes. For example, given the \nset_password\n method on the \nUserViewSet\n class:\n\n\nfrom myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n\n\n\nThe following route would be generated:\n\n\n\n\nURL pattern: \n^users/{pk}/set_password/$\n\n\nURL name: \n'user-set-password'\n\n\n\n\nBy default, the URL pattern is based on the method name, and the URL name is the combination of the \nViewSet.basename\n and the hyphenated method name.\nIf you don't want to use the defaults for either of these values, you can instead provide the \nurl_path\n and \nurl_name\n arguments to the \n@action\n decorator.\n\n\nFor example, if you want to change the URL for our custom action to \n^users/{pk}/change-password/$\n, you could write:\n\n\nfrom myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],\n url_path='change-password', url_name='change_password')\n def set_password(self, request, pk=None):\n ...\n\n\n\nThe above example would now generate the following URL pattern:\n\n\n\n\nURL path: \n^users/{pk}/change-password/$\n\n\nURL name: \n'user-change_password'\n\n\n\n\nAPI Guide\n\n\nSimpleRouter\n\n\nThis router includes routes for the standard set of \nlist\n, \ncreate\n, \nretrieve\n, \nupdate\n, \npartial_update\n and \ndestroy\n actions. The viewset can also mark additional methods to be routed, using the \n@action\n decorator.\n\n\n\n \nURL Style\nHTTP Method\nAction\nURL Name\n\n \n{prefix}/\nGET\nlist\n{basename}-list\n\n \nPOST\ncreate\n\n \n{prefix}/{url_path}/\nGET, or as specified by `methods` argument\n`@action(detail=False)` decorated method\n{basename}-{url_name}\n\n \n{prefix}/{lookup}/\nGET\nretrieve\n{basename}-detail\n\n \nPUT\nupdate\n\n \nPATCH\npartial_update\n\n \nDELETE\ndestroy\n\n \n{prefix}/{lookup}/{url_path}/\nGET, or as specified by `methods` argument\n`@action(detail=True)` decorated method\n{basename}-{url_name}\n\n\n\n\n\nBy default the URLs created by \nSimpleRouter\n are appended with a trailing slash.\nThis behavior can be modified by setting the \ntrailing_slash\n argument to \nFalse\n when instantiating the router. For example:\n\n\nrouter = SimpleRouter(trailing_slash=False)\n\n\n\nTrailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.\n\n\nThe router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the \nlookup_value_regex\n attribute on the viewset. For example, you can limit the lookup to valid UUIDs:\n\n\nclass MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_id'\n lookup_value_regex = '[0-9a-f]{32}'\n\n\n\nDefaultRouter\n\n\nThis router is similar to \nSimpleRouter\n as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional \n.json\n style format suffixes.\n\n\n\n \nURL Style\nHTTP Method\nAction\nURL Name\n\n \n[.format]\nGET\nautomatically generated root view\napi-root\n\n \n{prefix}/[.format]\nGET\nlist\n{basename}-list\n\n \nPOST\ncreate\n\n \n{prefix}/{url_path}/[.format]\nGET, or as specified by `methods` argument\n`@action(detail=False)` decorated method\n{basename}-{url_name}\n\n \n{prefix}/{lookup}/[.format]\nGET\nretrieve\n{basename}-detail\n\n \nPUT\nupdate\n\n \nPATCH\npartial_update\n\n \nDELETE\ndestroy\n\n \n{prefix}/{lookup}/{url_path}/[.format]\nGET, or as specified by `methods` argument\n`@action(detail=True)` decorated method\n{basename}-{url_name}\n\n\n\n\n\nAs with \nSimpleRouter\n the trailing slashes on the URL routes can be removed by setting the \ntrailing_slash\n argument to \nFalse\n when instantiating the router.\n\n\nrouter = DefaultRouter(trailing_slash=False)\n\n\n\nCustom Routers\n\n\nImplementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.\n\n\nThe simplest way to implement a custom router is to subclass one of the existing router classes. The \n.routes\n attribute is used to template the URL patterns that will be mapped to each viewset. The \n.routes\n attribute is a list of \nRoute\n named tuples.\n\n\nThe arguments to the \nRoute\n named tuple are:\n\n\nurl\n: A string representing the URL to be routed. May include the following format strings:\n\n\n\n\n{prefix}\n - The URL prefix to use for this set of routes.\n\n\n{lookup}\n - The lookup field used to match against a single instance.\n\n\n{trailing_slash}\n - Either a '/' or an empty string, depending on the \ntrailing_slash\n argument.\n\n\n\n\nmapping\n: A mapping of HTTP method names to the view methods\n\n\nname\n: The name of the URL as used in \nreverse\n calls. May include the following format string:\n\n\n\n\n{basename}\n - The base to use for the URL names that are created.\n\n\n\n\ninitkwargs\n: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the \ndetail\n, \nbasename\n, and \nsuffix\n arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.\n\n\nCustomizing dynamic routes\n\n\nYou can also customize how the \n@action\n decorator is routed. Include the \nDynamicRoute\n named tuple in the \n.routes\n list, setting the \ndetail\n argument as appropriate for the list-based and detail-based routes. In addition to \ndetail\n, the arguments to \nDynamicRoute\n are:\n\n\nurl\n: A string representing the URL to be routed. May include the same format strings as \nRoute\n, and additionally accepts the \n{url_path}\n format string.\n\n\nname\n: The name of the URL as used in \nreverse\n calls. May include the following format strings:\n\n\n\n\n{basename}\n - The base to use for the URL names that are created.\n\n\n{url_name}\n - The \nurl_name\n provided to the \n@action\n.\n\n\n\n\ninitkwargs\n: A dictionary of any additional arguments that should be passed when instantiating the view.\n\n\nExample\n\n\nThe following example will only route to the \nlist\n and \nretrieve\n actions, and does not use the trailing slash convention.\n\n\nfrom rest_framework.routers import Route, DynamicRoute, SimpleRouter\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ]\n\n\n\nLet's take a look at the routes our \nCustomReadOnlyRouter\n would generate for a simple viewset.\n\n\nviews.py\n:\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups])\n\n\n\nurls.py\n:\n\n\nrouter = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls\n\n\n\nThe following mappings would be generated...\n\n\n\n \nURL\nHTTP Method\nAction\nURL Name\n\n \n/users\nGET\nlist\nuser-list\n\n \n/users/{username}\nGET\nretrieve\nuser-detail\n\n \n/users/{username}/group_names\nGET\ngroup_names\nuser-group-names\n\n\n\n\n\nFor another example of setting the \n.routes\n attribute, see the source code for the \nSimpleRouter\n class.\n\n\nAdvanced custom routers\n\n\nIf you want to provide totally custom behavior, you can override \nBaseRouter\n and override the \nget_urls(self)\n method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the \nself.registry\n attribute.\n\n\nYou may also want to override the \nget_default_basename(self, viewset)\n method, or else always explicitly set the \nbasename\n argument when registering your viewsets with the router.\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\nModelRouter (wq.db.rest)\n\n\nThe \nwq.db package\n provides an advanced \nModelRouter\n class (and singleton instance) that extends \nDefaultRouter\n with a \nregister_model()\n API. Much like Django's \nadmin.site.register\n, the only required argument to \nrest.router.register_model\n is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.\n\n\nfrom wq.db import rest\nfrom myapp.models import MyModel\n\nrest.router.register_model(MyModel)\n\n\n\nDRF-extensions\n\n\nThe \nDRF-extensions\n package\n provides \nrouters\n for creating \nnested viewsets\n, \ncollection level controllers\n with \ncustomizable endpoint names\n.", + "text": "Routers\n\n\n\n\nResource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.\n\n\n\u2014 \nRuby on Rails Documentation\n\n\n\n\nSome Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.\n\n\nREST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.\n\n\nUsage\n\n\nHere's an example of a simple URL conf, that uses \nSimpleRouter\n.\n\n\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls\n\n\n\nThere are two mandatory arguments to the \nregister()\n method:\n\n\n\n\nprefix\n - The URL prefix to use for this set of routes.\n\n\nviewset\n - The viewset class.\n\n\n\n\nOptionally, you may also specify an additional argument:\n\n\n\n\nbase_name\n - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the \nqueryset\n attribute of the viewset, if it has one. Note that if the viewset does not include a \nqueryset\n attribute then you must set \nbase_name\n when registering the viewset.\n\n\n\n\nThe example above would generate the following URL patterns:\n\n\n\n\nURL pattern: \n^users/$\n Name: \n'user-list'\n\n\nURL pattern: \n^users/{pk}/$\n Name: \n'user-detail'\n\n\nURL pattern: \n^accounts/$\n Name: \n'account-list'\n\n\nURL pattern: \n^accounts/{pk}/$\n Name: \n'account-detail'\n\n\n\n\n\n\nNote\n: The \nbase_name\n argument is used to specify the initial part of the view name pattern. In the example above, that's the \nuser\n or \naccount\n part.\n\n\nTypically you won't \nneed\n to specify the \nbase_name\n argument, but if you have a viewset where you've defined a custom \nget_queryset\n method, then the viewset may not have a \n.queryset\n attribute set. If you try to register that viewset you'll see an error like this:\n\n\n'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.\n\n\n\nThis means you'll need to explicitly set the \nbase_name\n argument when registering the viewset, as it could not be automatically determined from the model name.\n\n\n\n\nUsing \ninclude\n with routers\n\n\nThe \n.urls\n attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.\n\n\nFor example, you can append \nrouter.urls\n to a list of existing views\u2026\n\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls\n\n\n\nAlternatively you can use Django's \ninclude\n function, like so\u2026\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n]\n\n\n\nYou may use \ninclude\n with an application namespace:\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'))),\n]\n\n\n\nOr both an application and instance namespace:\n\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),\n]\n\n\n\nSee Django's \nURL namespaces docs\n and the \ninclude\n API reference\n for more details.\n\n\n\n\nNote\n: If using namespacing with hyperlinked serializers you'll also need to ensure that any \nview_name\n parameters\non the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as\n\nview_name='app_name:user-detail'\n for serializer fields hyperlinked to the user detail view.\n\n\nThe automatic \nview_name\n generation uses a pattern like \n%(model_name)-detail\n. Unless your models names actually clash\nyou may be better off \nnot\n namespacing your Django REST Framework views when using hyperlinked serializers.\n\n\n\n\nRouting for extra actions\n\n\nA viewset may \nmark extra actions for routing\n by decorating a method with the \n@action\n decorator. These extra actions will be included in the generated routes. For example, given the \nset_password\n method on the \nUserViewSet\n class:\n\n\nfrom myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n\n\n\nThe following route would be generated:\n\n\n\n\nURL pattern: \n^users/{pk}/set_password/$\n\n\nURL name: \n'user-set-password'\n\n\n\n\nBy default, the URL pattern is based on the method name, and the URL name is the combination of the \nViewSet.basename\n and the hyphenated method name.\nIf you don't want to use the defaults for either of these values, you can instead provide the \nurl_path\n and \nurl_name\n arguments to the \n@action\n decorator.\n\n\nFor example, if you want to change the URL for our custom action to \n^users/{pk}/change-password/$\n, you could write:\n\n\nfrom myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],\n url_path='change-password', url_name='change_password')\n def set_password(self, request, pk=None):\n ...\n\n\n\nThe above example would now generate the following URL pattern:\n\n\n\n\nURL path: \n^users/{pk}/change-password/$\n\n\nURL name: \n'user-change_password'\n\n\n\n\nAPI Guide\n\n\nSimpleRouter\n\n\nThis router includes routes for the standard set of \nlist\n, \ncreate\n, \nretrieve\n, \nupdate\n, \npartial_update\n and \ndestroy\n actions. The viewset can also mark additional methods to be routed, using the \n@action\n decorator.\n\n\n\n \nURL Style\nHTTP Method\nAction\nURL Name\n\n \n{prefix}/\nGET\nlist\n{basename}-list\n\n \nPOST\ncreate\n\n \n{prefix}/{url_path}/\nGET, or as specified by `methods` argument\n`@action(detail=False)` decorated method\n{basename}-{url_name}\n\n \n{prefix}/{lookup}/\nGET\nretrieve\n{basename}-detail\n\n \nPUT\nupdate\n\n \nPATCH\npartial_update\n\n \nDELETE\ndestroy\n\n \n{prefix}/{lookup}/{url_path}/\nGET, or as specified by `methods` argument\n`@action(detail=True)` decorated method\n{basename}-{url_name}\n\n\n\n\n\nBy default the URLs created by \nSimpleRouter\n are appended with a trailing slash.\nThis behavior can be modified by setting the \ntrailing_slash\n argument to \nFalse\n when instantiating the router. For example:\n\n\nrouter = SimpleRouter(trailing_slash=False)\n\n\n\nTrailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.\n\n\nThe router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the \nlookup_value_regex\n attribute on the viewset. For example, you can limit the lookup to valid UUIDs:\n\n\nclass MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_id'\n lookup_value_regex = '[0-9a-f]{32}'\n\n\n\nDefaultRouter\n\n\nThis router is similar to \nSimpleRouter\n as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional \n.json\n style format suffixes.\n\n\n\n \nURL Style\nHTTP Method\nAction\nURL Name\n\n \n[.format]\nGET\nautomatically generated root view\napi-root\n\n \n{prefix}/[.format]\nGET\nlist\n{basename}-list\n\n \nPOST\ncreate\n\n \n{prefix}/{url_path}/[.format]\nGET, or as specified by `methods` argument\n`@action(detail=False)` decorated method\n{basename}-{url_name}\n\n \n{prefix}/{lookup}/[.format]\nGET\nretrieve\n{basename}-detail\n\n \nPUT\nupdate\n\n \nPATCH\npartial_update\n\n \nDELETE\ndestroy\n\n \n{prefix}/{lookup}/{url_path}/[.format]\nGET, or as specified by `methods` argument\n`@action(detail=True)` decorated method\n{basename}-{url_name}\n\n\n\n\n\nAs with \nSimpleRouter\n the trailing slashes on the URL routes can be removed by setting the \ntrailing_slash\n argument to \nFalse\n when instantiating the router.\n\n\nrouter = DefaultRouter(trailing_slash=False)\n\n\n\nCustom Routers\n\n\nImplementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.\n\n\nThe simplest way to implement a custom router is to subclass one of the existing router classes. The \n.routes\n attribute is used to template the URL patterns that will be mapped to each viewset. The \n.routes\n attribute is a list of \nRoute\n named tuples.\n\n\nThe arguments to the \nRoute\n named tuple are:\n\n\nurl\n: A string representing the URL to be routed. May include the following format strings:\n\n\n\n\n{prefix}\n - The URL prefix to use for this set of routes.\n\n\n{lookup}\n - The lookup field used to match against a single instance.\n\n\n{trailing_slash}\n - Either a '/' or an empty string, depending on the \ntrailing_slash\n argument.\n\n\n\n\nmapping\n: A mapping of HTTP method names to the view methods\n\n\nname\n: The name of the URL as used in \nreverse\n calls. May include the following format string:\n\n\n\n\n{basename}\n - The base to use for the URL names that are created.\n\n\n\n\ninitkwargs\n: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the \ndetail\n, \nbasename\n, and \nsuffix\n arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.\n\n\nCustomizing dynamic routes\n\n\nYou can also customize how the \n@action\n decorator is routed. Include the \nDynamicRoute\n named tuple in the \n.routes\n list, setting the \ndetail\n argument as appropriate for the list-based and detail-based routes. In addition to \ndetail\n, the arguments to \nDynamicRoute\n are:\n\n\nurl\n: A string representing the URL to be routed. May include the same format strings as \nRoute\n, and additionally accepts the \n{url_path}\n format string.\n\n\nname\n: The name of the URL as used in \nreverse\n calls. May include the following format strings:\n\n\n\n\n{basename}\n - The base to use for the URL names that are created.\n\n\n{url_name}\n - The \nurl_name\n provided to the \n@action\n.\n\n\n\n\ninitkwargs\n: A dictionary of any additional arguments that should be passed when instantiating the view.\n\n\nExample\n\n\nThe following example will only route to the \nlist\n and \nretrieve\n actions, and does not use the trailing slash convention.\n\n\nfrom rest_framework.routers import Route, DynamicRoute, SimpleRouter\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ]\n\n\n\nLet's take a look at the routes our \nCustomReadOnlyRouter\n would generate for a simple viewset.\n\n\nviews.py\n:\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups])\n\n\n\nurls.py\n:\n\n\nrouter = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls\n\n\n\nThe following mappings would be generated...\n\n\n\n \nURL\nHTTP Method\nAction\nURL Name\n\n \n/users\nGET\nlist\nuser-list\n\n \n/users/{username}\nGET\nretrieve\nuser-detail\n\n \n/users/{username}/group-names\nGET\ngroup_names\nuser-group-names\n\n\n\n\n\nFor another example of setting the \n.routes\n attribute, see the source code for the \nSimpleRouter\n class.\n\n\nAdvanced custom routers\n\n\nIf you want to provide totally custom behavior, you can override \nBaseRouter\n and override the \nget_urls(self)\n method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the \nself.registry\n attribute.\n\n\nYou may also want to override the \nget_default_base_name(self, viewset)\n method, or else always explicitly set the \nbase_name\n argument when registering your viewsets with the router.\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\nModelRouter (wq.db.rest)\n\n\nThe \nwq.db package\n provides an advanced \nModelRouter\n class (and singleton instance) that extends \nDefaultRouter\n with a \nregister_model()\n API. Much like Django's \nadmin.site.register\n, the only required argument to \nrest.router.register_model\n is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.\n\n\nfrom wq.db import rest\nfrom myapp.models import MyModel\n\nrest.router.register_model(MyModel)\n\n\n\nDRF-extensions\n\n\nThe \nDRF-extensions\n package\n provides \nrouters\n for creating \nnested viewsets\n, \ncollection level controllers\n with \ncustomizable endpoint names\n.", "title": "Routers" }, { @@ -977,12 +982,12 @@ }, { "location": "/api-guide/routers/#usage", - "text": "Here's an example of a simple URL conf, that uses SimpleRouter . from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls There are two mandatory arguments to the register() method: prefix - The URL prefix to use for this set of routes. viewset - The viewset class. Optionally, you may also specify an additional argument: basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset. The example above would generate the following URL patterns: URL pattern: ^users/$ Name: 'user-list' URL pattern: ^users/{pk}/$ Name: 'user-detail' URL pattern: ^accounts/$ Name: 'account-list' URL pattern: ^accounts/{pk}/$ Name: 'account-detail' Note : The basename argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part. Typically you won't need to specify the basename argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this: 'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the basename argument when registering the viewset, as it could not be automatically determined from the model name.", + "text": "Here's an example of a simple URL conf, that uses SimpleRouter . from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls There are two mandatory arguments to the register() method: prefix - The URL prefix to use for this set of routes. viewset - The viewset class. Optionally, you may also specify an additional argument: base_name - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set base_name when registering the viewset. The example above would generate the following URL patterns: URL pattern: ^users/$ Name: 'user-list' URL pattern: ^users/{pk}/$ Name: 'user-detail' URL pattern: ^accounts/$ Name: 'account-list' URL pattern: ^accounts/{pk}/$ Name: 'account-detail' Note : The base_name argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part. Typically you won't need to specify the base_name argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this: 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the base_name argument when registering the viewset, as it could not be automatically determined from the model name.", "title": "Usage" }, { "location": "/api-guide/routers/#using-include-with-routers", - "text": "The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. For example, you can append router.urls to a list of existing views... router = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls Alternatively you can use Django's include function, like so... urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n] You may use include with an application namespace: urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'))),\n] Or both an application and instance namespace: urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),\n] See Django's URL namespaces docs and the include API reference for more details. Note : If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters\non the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view. The automatic view_name generation uses a pattern like %(model_name)-detail . Unless your models names actually clash\nyou may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.", + "text": "The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. For example, you can append router.urls to a list of existing views\u2026 router = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls Alternatively you can use Django's include function, like so\u2026 urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n] You may use include with an application namespace: urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'))),\n] Or both an application and instance namespace: urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),\n] See Django's URL namespaces docs and the include API reference for more details. Note : If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters\non the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view. The automatic view_name generation uses a pattern like %(model_name)-detail . Unless your models names actually clash\nyou may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.", "title": "Using include with routers" }, { @@ -1017,12 +1022,12 @@ }, { "location": "/api-guide/routers/#example", - "text": "The following example will only route to the list and retrieve actions, and does not use the trailing slash convention. from rest_framework.routers import Route, DynamicRoute, SimpleRouter\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ] Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset. views.py : class UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups]) urls.py : router = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls The following mappings would be generated... \n URL HTTP Method Action URL Name \n /users GET list user-list \n /users/{username} GET retrieve user-detail \n /users/{username}/group_names GET group_names user-group-names For another example of setting the .routes attribute, see the source code for the SimpleRouter class.", + "text": "The following example will only route to the list and retrieve actions, and does not use the trailing slash convention. from rest_framework.routers import Route, DynamicRoute, SimpleRouter\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ] Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset. views.py : class UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups]) urls.py : router = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls The following mappings would be generated... \n URL HTTP Method Action URL Name \n /users GET list user-list \n /users/{username} GET retrieve user-detail \n /users/{username}/group-names GET group_names user-group-names For another example of setting the .routes attribute, see the source code for the SimpleRouter class.", "title": "Example" }, { "location": "/api-guide/routers/#advanced-custom-routers", - "text": "If you want to provide totally custom behavior, you can override BaseRouter and override the get_urls(self) method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the self.registry attribute. You may also want to override the get_default_basename(self, viewset) method, or else always explicitly set the basename argument when registering your viewsets with the router.", + "text": "If you want to provide totally custom behavior, you can override BaseRouter and override the get_urls(self) method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the self.registry attribute. You may also want to override the get_default_base_name(self, viewset) method, or else always explicitly set the base_name argument when registering your viewsets with the router.", "title": "Advanced custom routers" }, { @@ -1162,7 +1167,7 @@ }, { "location": "/api-guide/renderers/", - "text": "Renderers\n\n\n\n\nBefore a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.\n\n\n\u2014 \nDjango documentation\n\n\n\n\nREST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.\n\n\nHow the renderer is determined\n\n\nThe set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.\n\n\nThe basic process of content negotiation involves examining the request's \nAccept\n header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL \nhttp://example.com/api/users_count.json\n might be an endpoint that always returns JSON data.\n\n\nFor more information see the documentation on \ncontent negotiation\n.\n\n\nSetting the renderers\n\n\nThe default set of renderers may be set globally, using the \nDEFAULT_RENDERER_CLASSES\n setting. For example, the following settings would use \nJSON\n as the main media type and also include the self describing API.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n )\n}\n\n\n\nYou can also set the renderers used for an individual view, or viewset,\nusing the \nAPIView\n class-based views.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass UserCountView(APIView):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n renderer_classes = (JSONRenderer, )\n\n def get(self, request, format=None):\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@renderer_classes((JSONRenderer,))\ndef user_count_view(request, format=None):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n\n\n\nOrdering of renderer classes\n\n\nIt's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an \nAccept: */*\n header, or not including an \nAccept\n header at all, then REST framework will select the first renderer in the list to use for the response.\n\n\nFor example if your API serves JSON responses and the HTML browsable API, you might want to make \nJSONRenderer\n your default renderer, in order to send \nJSON\n responses to clients that do not specify an \nAccept\n header.\n\n\nIf your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making \nTemplateHTMLRenderer\n your default renderer, in order to play nicely with older browsers that send \nbroken accept headers\n.\n\n\n\n\nAPI Reference\n\n\nJSONRenderer\n\n\nRenders the request data into \nJSON\n, using utf-8 encoding.\n\n\nNote that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:\n\n\n{\"unicode black star\":\"\u2605\",\"value\":999}\n\n\n\nThe client may additionally include an \n'indent'\n media type parameter, in which case the returned \nJSON\n will be indented. For example \nAccept: application/json; indent=4\n.\n\n\n{\n \"unicode black star\": \"\u2605\",\n \"value\": 999\n}\n\n\n\nThe default JSON encoding style can be altered using the \nUNICODE_JSON\n and \nCOMPACT_JSON\n settings keys.\n\n\n.media_type\n: \napplication/json\n\n\n.format\n: \n'.json'\n\n\n.charset\n: \nNone\n\n\nTemplateHTMLRenderer\n\n\nRenders data to HTML, using Django's standard template rendering.\nUnlike other renderers, the data passed to the \nResponse\n does not need to be serialized. Also, unlike other renderers, you may want to include a \ntemplate_name\n argument when creating the \nResponse\n.\n\n\nThe TemplateHTMLRenderer will create a \nRequestContext\n, using the \nresponse.data\n as the context dict, and determine a template name to use to render the context.\n\n\nThe template name is determined by (in order of preference):\n\n\n\n\nAn explicit \ntemplate_name\n argument passed to the response.\n\n\nAn explicit \n.template_name\n attribute set on this class.\n\n\nThe return result of calling \nview.get_template_names()\n.\n\n\n\n\nAn example of a view that uses \nTemplateHTMLRenderer\n:\n\n\nclass UserDetail(generics.RetrieveAPIView):\n \"\"\"\n A view that returns a templated HTML representation of a given user.\n \"\"\"\n queryset = User.objects.all()\n renderer_classes = (TemplateHTMLRenderer,)\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return Response({'user': self.object}, template_name='user_detail.html')\n\n\n\nYou can use \nTemplateHTMLRenderer\n either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.\n\n\nIf you're building websites that use \nTemplateHTMLRenderer\n along with other renderer classes, you should consider listing \nTemplateHTMLRenderer\n as the first class in the \nrenderer_classes\n list, so that it will be prioritised first even for browsers that send poorly formed \nACCEPT:\n headers.\n\n\nSee the \nHTML & Forms\n Topic Page\n for further examples of \nTemplateHTMLRenderer\n usage.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.html'\n\n\n.charset\n: \nutf-8\n\n\nSee also: \nStaticHTMLRenderer\n\n\nStaticHTMLRenderer\n\n\nA simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.\n\n\nAn example of a view that uses \nStaticHTMLRenderer\n:\n\n\n@api_view(('GET',))\n@renderer_classes((StaticHTMLRenderer,))\ndef simple_html_view(request):\n data = '

        Hello, world

        '\n return Response(data)\n\n\n\nYou can use \nStaticHTMLRenderer\n either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.html'\n\n\n.charset\n: \nutf-8\n\n\nSee also: \nTemplateHTMLRenderer\n\n\nBrowsableAPIRenderer\n\n\nRenders data into HTML for the Browsable API:\n\n\n\n\nThis renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.api'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/api.html'\n\n\nCustomizing BrowsableAPIRenderer\n\n\nBy default the response content will be rendered with the highest priority renderer apart from \nBrowsableAPIRenderer\n. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the \nget_default_renderer()\n method. For example:\n\n\nclass CustomBrowsableAPIRenderer(BrowsableAPIRenderer):\n def get_default_renderer(self, view):\n return JSONRenderer()\n\n\n\nAdminRenderer\n\n\nRenders data into HTML for an admin-like display:\n\n\n\n\nThis renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.\n\n\nNote that views that have nested or list serializers for their input won't work well with the \nAdminRenderer\n, as the HTML forms are unable to properly support them.\n\n\nNote\n: The \nAdminRenderer\n is only able to include links to detail pages when a properly configured \nURL_FIELD_NAME\n (\nurl\n by default) attribute is present in the data. For \nHyperlinkedModelSerializer\n this will be the case, but for \nModelSerializer\n or plain \nSerializer\n classes you'll need to make sure to include the field explicitly. For example here we use models \nget_absolute_url\n method:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n\n class Meta:\n model = Account\n\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.admin'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/admin.html'\n\n\nHTMLFormRenderer\n\n\nRenders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing \n
        \n tags, a hidden CSRF input or any submit buttons.\n\n\nThis renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the \nrender_form\n template tag.\n\n\n{% load rest_framework %}\n\n\n {% csrf_token %}\n {% render_form serializer %}\n \n
        \n\n\n\nFor more information see the \nHTML & Forms\n documentation.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.form'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/horizontal/form.html'\n\n\nMultiPartRenderer\n\n\nThis renderer is used for rendering HTML multipart form data. \nIt is not suitable as a response renderer\n, but is instead used for creating test requests, using REST framework's \ntest client and test request factory\n.\n\n\n.media_type\n: \nmultipart/form-data; boundary=BoUnDaRyStRiNg\n\n\n.format\n: \n'.multipart'\n\n\n.charset\n: \nutf-8\n\n\n\n\nCustom renderers\n\n\nTo implement a custom renderer, you should override \nBaseRenderer\n, set the \n.media_type\n and \n.format\n properties, and implement the \n.render(self, data, media_type=None, renderer_context=None)\n method.\n\n\nThe method should return a bytestring, which will be used as the body of the HTTP response.\n\n\nThe arguments passed to the \n.render()\n method are:\n\n\ndata\n\n\nThe request data, as set by the \nResponse()\n instantiation.\n\n\nmedia_type=None\n\n\nOptional. If provided, this is the accepted media type, as determined by the content negotiation stage.\n\n\nDepending on the client's \nAccept:\n header, this may be more specific than the renderer's \nmedia_type\n attribute, and may include media type parameters. For example \n\"application/json; nested=true\"\n.\n\n\nrenderer_context=None\n\n\nOptional. If provided, this is a dictionary of contextual information provided by the view.\n\n\nBy default this will include the following keys: \nview\n, \nrequest\n, \nresponse\n, \nargs\n, \nkwargs\n.\n\n\nExample\n\n\nThe following is an example plaintext renderer that will return a response with the \ndata\n parameter as the content of the response.\n\n\nfrom django.utils.encoding import smart_unicode\nfrom rest_framework import renderers\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data.encode(self.charset)\n\n\n\nSetting the character set\n\n\nBy default renderer classes are assumed to be using the \nUTF-8\n encoding. To use a different encoding, set the \ncharset\n attribute on the renderer.\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n charset = 'iso-8859-1'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data.encode(self.charset)\n\n\n\nNote that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the \nResponse\n class, with the \ncharset\n attribute set on the renderer used to determine the encoding.\n\n\nIf the renderer returns a bytestring representing raw binary content, you should set a charset value of \nNone\n, which will ensure the \nContent-Type\n header of the response will not have a \ncharset\n value set.\n\n\nIn some cases you may also want to set the \nrender_style\n attribute to \n'binary'\n. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.\n\n\nclass JPEGRenderer(renderers.BaseRenderer):\n media_type = 'image/jpeg'\n format = 'jpg'\n charset = None\n render_style = 'binary'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data\n\n\n\n\n\nAdvanced renderer usage\n\n\nYou can do some pretty flexible things using REST framework's renderers. Some examples...\n\n\n\n\nProvide either flat or nested representations from the same endpoint, depending on the requested media type.\n\n\nServe both regular HTML webpages, and JSON based API responses from the same endpoints.\n\n\nSpecify multiple types of HTML representation for API clients to use.\n\n\nUnderspecify a renderer's media type, such as using \nmedia_type = 'image/*'\n, and use the \nAccept\n header to vary the encoding of the response.\n\n\n\n\nVarying behaviour by media type\n\n\nIn some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access \nrequest.accepted_renderer\n to determine the negotiated renderer that will be used for the response.\n\n\nFor example:\n\n\n@api_view(('GET',))\n@renderer_classes((TemplateHTMLRenderer, JSONRenderer))\ndef list_users(request):\n \"\"\"\n A view that can return JSON or HTML representations\n of the users in the system.\n \"\"\"\n queryset = Users.objects.filter(active=True)\n\n if request.accepted_renderer.format == 'html':\n # TemplateHTMLRenderer takes a context dict,\n # and additionally requires a 'template_name'.\n # It does not require serialization.\n data = {'users': queryset}\n return Response(data, template_name='list_users.html')\n\n # JSONRenderer requires serialized data as normal.\n serializer = UserSerializer(instance=queryset)\n data = serializer.data\n return Response(data)\n\n\n\nUnderspecifying the media type\n\n\nIn some cases you might want a renderer to serve a range of media types.\nIn this case you can underspecify the media types it should respond to, by using a \nmedia_type\n value such as \nimage/*\n, or \n*/*\n.\n\n\nIf you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the \ncontent_type\n attribute. For example:\n\n\nreturn Response(data, content_type='image/png')\n\n\n\nDesigning your media types\n\n\nFor the purposes of many Web APIs, simple \nJSON\n responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and \nHATEOAS\n you'll need to consider the design and usage of your media types in more detail.\n\n\nIn \nthe words of Roy Fielding\n, \"A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.\".\n\n\nFor good examples of custom media types, see GitHub's use of a custom \napplication/vnd.github+json\n media type, and Mike Amundsen's IANA approved \napplication/vnd.collection+json\n JSON-based hypermedia.\n\n\nHTML error views\n\n\nTypically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an \nHttp404\n or \nPermissionDenied\n exception, or a subclass of \nAPIException\n.\n\n\nIf you're using either the \nTemplateHTMLRenderer\n or the \nStaticHTMLRenderer\n and an exception is raised, the behavior is slightly different, and mirrors \nDjango's default handling of error views\n.\n\n\nExceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.\n\n\n\n\nLoad and render a template named \n{status_code}.html\n.\n\n\nLoad and render a template named \napi_exception.html\n.\n\n\nRender the HTTP status code and text, for example \"404 Not Found\".\n\n\n\n\nTemplates will render with a \nRequestContext\n which includes the \nstatus_code\n and \ndetails\n keys.\n\n\nNote\n: If \nDEBUG=True\n, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nYAML\n\n\nREST framework YAML\n provides \nYAML\n parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-yaml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}\n\n\n\nXML\n\n\nREST Framework XML\n provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-xml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}\n\n\n\nJSONP\n\n\nREST framework JSONP\n provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\n\n\nWarning\n: If you require cross-domain AJAX requests, you should generally be using the more modern approach of \nCORS\n as an alternative to \nJSONP\n. See the \nCORS documentation\n for more details.\n\n\nThe \njsonp\n approach is essentially a browser hack, and is \nonly appropriate for globally readable API endpoints\n, where \nGET\n requests are unauthenticated and do not require any user permissions.\n\n\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-jsonp\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ),\n}\n\n\n\nMessagePack\n\n\nMessagePack\n is a fast, efficient binary serialization format. \nJuan Riaza\n maintains the \ndjangorestframework-msgpack\n package which provides MessagePack renderer and parser support for REST framework.\n\n\nXLSX (Binary Spreadsheet Endpoints)\n\n\nXLSX is the world's most popular binary spreadsheet format. \nTim Allen\n of \nThe Wharton School\n maintains \ndrf-renderer-xlsx\n, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install drf-renderer-xlsx\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n ...\n\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'drf_renderer_xlsx.renderers.XLSXRenderer',\n ),\n}\n\n\n\nTo avoid having a file streamed without a filename (which the browser will often default to the filename \"download\", with no extension), we need to use a mixin to override the \nContent-Disposition\n header. If no filename is provided, it will default to \nexport.xlsx\n. For example:\n\n\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\nfrom drf_renderer_xlsx.mixins import XLSXFileMixin\nfrom drf_renderer_xlsx.renderers import XLSXRenderer\n\nfrom .models import MyExampleModel\nfrom .serializers import MyExampleSerializer\n\nclass MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):\n queryset = MyExampleModel.objects.all()\n serializer_class = MyExampleSerializer\n renderer_classes = (XLSXRenderer,)\n filename = 'my_export.xlsx'\n\n\n\nCSV\n\n\nComma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. \nMjumbe Poe\n maintains the \ndjangorestframework-csv\n package which provides CSV renderer support for REST framework.\n\n\nUltraJSON\n\n\nUltraJSON\n is an optimized C JSON encoder which can give significantly faster JSON rendering. \nJacob Haslehurst\n maintains the \ndrf-ujson-renderer\n package which implements JSON rendering using the UJSON package.\n\n\nCamelCase JSON\n\n\ndjangorestframework-camel-case\n provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by \nVitaly Babiy\n.\n\n\nPandas (CSV, Excel, PNG)\n\n\nDjango REST Pandas\n provides a serializer and renderers that support additional data processing and output via the \nPandas\n DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both \n.xls\n and \n.xlsx\n), and a number of \nother formats\n. It is maintained by \nS. Andrew Sheppard\n as part of the \nwq Project\n.\n\n\nLaTeX\n\n\nRest Framework Latex\n provides a renderer that outputs PDFs using Laulatex. It is maintained by \nPebble (S/F Software)\n.", + "text": "Renderers\n\n\n\n\nBefore a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.\n\n\n\u2014 \nDjango documentation\n\n\n\n\nREST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.\n\n\nHow the renderer is determined\n\n\nThe set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.\n\n\nThe basic process of content negotiation involves examining the request's \nAccept\n header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL \nhttp://example.com/api/users_count.json\n might be an endpoint that always returns JSON data.\n\n\nFor more information see the documentation on \ncontent negotiation\n.\n\n\nSetting the renderers\n\n\nThe default set of renderers may be set globally, using the \nDEFAULT_RENDERER_CLASSES\n setting. For example, the following settings would use \nJSON\n as the main media type and also include the self describing API.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n )\n}\n\n\n\nYou can also set the renderers used for an individual view, or viewset,\nusing the \nAPIView\n class-based views.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass UserCountView(APIView):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n renderer_classes = (JSONRenderer, )\n\n def get(self, request, format=None):\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@renderer_classes((JSONRenderer,))\ndef user_count_view(request, format=None):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n\n\n\nOrdering of renderer classes\n\n\nIt's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an \nAccept: */*\n header, or not including an \nAccept\n header at all, then REST framework will select the first renderer in the list to use for the response.\n\n\nFor example if your API serves JSON responses and the HTML browsable API, you might want to make \nJSONRenderer\n your default renderer, in order to send \nJSON\n responses to clients that do not specify an \nAccept\n header.\n\n\nIf your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making \nTemplateHTMLRenderer\n your default renderer, in order to play nicely with older browsers that send \nbroken accept headers\n.\n\n\n\n\nAPI Reference\n\n\nJSONRenderer\n\n\nRenders the request data into \nJSON\n, using utf-8 encoding.\n\n\nNote that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:\n\n\n{\"unicode black star\":\"\u2605\",\"value\":999}\n\n\n\nThe client may additionally include an \n'indent'\n media type parameter, in which case the returned \nJSON\n will be indented. For example \nAccept: application/json; indent=4\n.\n\n\n{\n \"unicode black star\": \"\u2605\",\n \"value\": 999\n}\n\n\n\nThe default JSON encoding style can be altered using the \nUNICODE_JSON\n and \nCOMPACT_JSON\n settings keys.\n\n\n.media_type\n: \napplication/json\n\n\n.format\n: \n'.json'\n\n\n.charset\n: \nNone\n\n\nTemplateHTMLRenderer\n\n\nRenders data to HTML, using Django's standard template rendering.\nUnlike other renderers, the data passed to the \nResponse\n does not need to be serialized. Also, unlike other renderers, you may want to include a \ntemplate_name\n argument when creating the \nResponse\n.\n\n\nThe TemplateHTMLRenderer will create a \nRequestContext\n, using the \nresponse.data\n as the context dict, and determine a template name to use to render the context.\n\n\nThe template name is determined by (in order of preference):\n\n\n\n\nAn explicit \ntemplate_name\n argument passed to the response.\n\n\nAn explicit \n.template_name\n attribute set on this class.\n\n\nThe return result of calling \nview.get_template_names()\n.\n\n\n\n\nAn example of a view that uses \nTemplateHTMLRenderer\n:\n\n\nclass UserDetail(generics.RetrieveAPIView):\n \"\"\"\n A view that returns a templated HTML representation of a given user.\n \"\"\"\n queryset = User.objects.all()\n renderer_classes = (TemplateHTMLRenderer,)\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return Response({'user': self.object}, template_name='user_detail.html')\n\n\n\nYou can use \nTemplateHTMLRenderer\n either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.\n\n\nIf you're building websites that use \nTemplateHTMLRenderer\n along with other renderer classes, you should consider listing \nTemplateHTMLRenderer\n as the first class in the \nrenderer_classes\n list, so that it will be prioritised first even for browsers that send poorly formed \nACCEPT:\n headers.\n\n\nSee the \nHTML & Forms\n Topic Page\n for further examples of \nTemplateHTMLRenderer\n usage.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.html'\n\n\n.charset\n: \nutf-8\n\n\nSee also: \nStaticHTMLRenderer\n\n\nStaticHTMLRenderer\n\n\nA simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.\n\n\nAn example of a view that uses \nStaticHTMLRenderer\n:\n\n\n@api_view(('GET',))\n@renderer_classes((StaticHTMLRenderer,))\ndef simple_html_view(request):\n data = '

        Hello, world

        '\n return Response(data)\n\n\n\nYou can use \nStaticHTMLRenderer\n either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.html'\n\n\n.charset\n: \nutf-8\n\n\nSee also: \nTemplateHTMLRenderer\n\n\nBrowsableAPIRenderer\n\n\nRenders data into HTML for the Browsable API:\n\n\n\n\nThis renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.api'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/api.html'\n\n\nCustomizing BrowsableAPIRenderer\n\n\nBy default the response content will be rendered with the highest priority renderer apart from \nBrowsableAPIRenderer\n. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the \nget_default_renderer()\n method. For example:\n\n\nclass CustomBrowsableAPIRenderer(BrowsableAPIRenderer):\n def get_default_renderer(self, view):\n return JSONRenderer()\n\n\n\nAdminRenderer\n\n\nRenders data into HTML for an admin-like display:\n\n\n\n\nThis renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.\n\n\nNote that views that have nested or list serializers for their input won't work well with the \nAdminRenderer\n, as the HTML forms are unable to properly support them.\n\n\nNote\n: The \nAdminRenderer\n is only able to include links to detail pages when a properly configured \nURL_FIELD_NAME\n (\nurl\n by default) attribute is present in the data. For \nHyperlinkedModelSerializer\n this will be the case, but for \nModelSerializer\n or plain \nSerializer\n classes you'll need to make sure to include the field explicitly. For example here we use models \nget_absolute_url\n method:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n\n class Meta:\n model = Account\n\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.admin'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/admin.html'\n\n\nHTMLFormRenderer\n\n\nRenders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing \n
        \n tags, a hidden CSRF input or any submit buttons.\n\n\nThis renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the \nrender_form\n template tag.\n\n\n{% load rest_framework %}\n\n\n {% csrf_token %}\n {% render_form serializer %}\n \n
        \n\n\n\nFor more information see the \nHTML & Forms\n documentation.\n\n\n.media_type\n: \ntext/html\n\n\n.format\n: \n'.form'\n\n\n.charset\n: \nutf-8\n\n\n.template\n: \n'rest_framework/horizontal/form.html'\n\n\nMultiPartRenderer\n\n\nThis renderer is used for rendering HTML multipart form data. \nIt is not suitable as a response renderer\n, but is instead used for creating test requests, using REST framework's \ntest client and test request factory\n.\n\n\n.media_type\n: \nmultipart/form-data; boundary=BoUnDaRyStRiNg\n\n\n.format\n: \n'.multipart'\n\n\n.charset\n: \nutf-8\n\n\n\n\nCustom renderers\n\n\nTo implement a custom renderer, you should override \nBaseRenderer\n, set the \n.media_type\n and \n.format\n properties, and implement the \n.render(self, data, media_type=None, renderer_context=None)\n method.\n\n\nThe method should return a bytestring, which will be used as the body of the HTTP response.\n\n\nThe arguments passed to the \n.render()\n method are:\n\n\ndata\n\n\nThe request data, as set by the \nResponse()\n instantiation.\n\n\nmedia_type=None\n\n\nOptional. If provided, this is the accepted media type, as determined by the content negotiation stage.\n\n\nDepending on the client's \nAccept:\n header, this may be more specific than the renderer's \nmedia_type\n attribute, and may include media type parameters. For example \n\"application/json; nested=true\"\n.\n\n\nrenderer_context=None\n\n\nOptional. If provided, this is a dictionary of contextual information provided by the view.\n\n\nBy default this will include the following keys: \nview\n, \nrequest\n, \nresponse\n, \nargs\n, \nkwargs\n.\n\n\nExample\n\n\nThe following is an example plaintext renderer that will return a response with the \ndata\n parameter as the content of the response.\n\n\nfrom django.utils.encoding import smart_unicode\nfrom rest_framework import renderers\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data.encode(self.charset)\n\n\n\nSetting the character set\n\n\nBy default renderer classes are assumed to be using the \nUTF-8\n encoding. To use a different encoding, set the \ncharset\n attribute on the renderer.\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n charset = 'iso-8859-1'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data.encode(self.charset)\n\n\n\nNote that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the \nResponse\n class, with the \ncharset\n attribute set on the renderer used to determine the encoding.\n\n\nIf the renderer returns a bytestring representing raw binary content, you should set a charset value of \nNone\n, which will ensure the \nContent-Type\n header of the response will not have a \ncharset\n value set.\n\n\nIn some cases you may also want to set the \nrender_style\n attribute to \n'binary'\n. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.\n\n\nclass JPEGRenderer(renderers.BaseRenderer):\n media_type = 'image/jpeg'\n format = 'jpg'\n charset = None\n render_style = 'binary'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data\n\n\n\n\n\nAdvanced renderer usage\n\n\nYou can do some pretty flexible things using REST framework's renderers. Some examples...\n\n\n\n\nProvide either flat or nested representations from the same endpoint, depending on the requested media type.\n\n\nServe both regular HTML webpages, and JSON based API responses from the same endpoints.\n\n\nSpecify multiple types of HTML representation for API clients to use.\n\n\nUnderspecify a renderer's media type, such as using \nmedia_type = 'image/*'\n, and use the \nAccept\n header to vary the encoding of the response.\n\n\n\n\nVarying behaviour by media type\n\n\nIn some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access \nrequest.accepted_renderer\n to determine the negotiated renderer that will be used for the response.\n\n\nFor example:\n\n\n@api_view(('GET',))\n@renderer_classes((TemplateHTMLRenderer, JSONRenderer))\ndef list_users(request):\n \"\"\"\n A view that can return JSON or HTML representations\n of the users in the system.\n \"\"\"\n queryset = Users.objects.filter(active=True)\n\n if request.accepted_renderer.format == 'html':\n # TemplateHTMLRenderer takes a context dict,\n # and additionally requires a 'template_name'.\n # It does not require serialization.\n data = {'users': queryset}\n return Response(data, template_name='list_users.html')\n\n # JSONRenderer requires serialized data as normal.\n serializer = UserSerializer(instance=queryset)\n data = serializer.data\n return Response(data)\n\n\n\nUnderspecifying the media type\n\n\nIn some cases you might want a renderer to serve a range of media types.\nIn this case you can underspecify the media types it should respond to, by using a \nmedia_type\n value such as \nimage/*\n, or \n*/*\n.\n\n\nIf you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the \ncontent_type\n attribute. For example:\n\n\nreturn Response(data, content_type='image/png')\n\n\n\nDesigning your media types\n\n\nFor the purposes of many Web APIs, simple \nJSON\n responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and \nHATEOAS\n you'll need to consider the design and usage of your media types in more detail.\n\n\nIn \nthe words of Roy Fielding\n, \"A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.\".\n\n\nFor good examples of custom media types, see GitHub's use of a custom \napplication/vnd.github+json\n media type, and Mike Amundsen's IANA approved \napplication/vnd.collection+json\n JSON-based hypermedia.\n\n\nHTML error views\n\n\nTypically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an \nHttp404\n or \nPermissionDenied\n exception, or a subclass of \nAPIException\n.\n\n\nIf you're using either the \nTemplateHTMLRenderer\n or the \nStaticHTMLRenderer\n and an exception is raised, the behavior is slightly different, and mirrors \nDjango's default handling of error views\n.\n\n\nExceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.\n\n\n\n\nLoad and render a template named \n{status_code}.html\n.\n\n\nLoad and render a template named \napi_exception.html\n.\n\n\nRender the HTTP status code and text, for example \"404 Not Found\".\n\n\n\n\nTemplates will render with a \nRequestContext\n which includes the \nstatus_code\n and \ndetails\n keys.\n\n\nNote\n: If \nDEBUG=True\n, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nYAML\n\n\nREST framework YAML\n provides \nYAML\n parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-yaml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}\n\n\n\nXML\n\n\nREST Framework XML\n provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-xml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}\n\n\n\nJSONP\n\n\nREST framework JSONP\n provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\n\n\nWarning\n: If you require cross-domain AJAX requests, you should generally be using the more modern approach of \nCORS\n as an alternative to \nJSONP\n. See the \nCORS documentation\n for more details.\n\n\nThe \njsonp\n approach is essentially a browser hack, and is \nonly appropriate for globally readable API endpoints\n, where \nGET\n requests are unauthenticated and do not require any user permissions.\n\n\n\n\nInstallation & configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-jsonp\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ),\n}\n\n\n\nMessagePack\n\n\nMessagePack\n is a fast, efficient binary serialization format. \nJuan Riaza\n maintains the \ndjangorestframework-msgpack\n package which provides MessagePack renderer and parser support for REST framework.\n\n\nCSV\n\n\nComma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. \nMjumbe Poe\n maintains the \ndjangorestframework-csv\n package which provides CSV renderer support for REST framework.\n\n\nUltraJSON\n\n\nUltraJSON\n is an optimized C JSON encoder which can give significantly faster JSON rendering. \nJacob Haslehurst\n maintains the \ndrf-ujson-renderer\n package which implements JSON rendering using the UJSON package.\n\n\nCamelCase JSON\n\n\ndjangorestframework-camel-case\n provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by \nVitaly Babiy\n.\n\n\nPandas (CSV, Excel, PNG)\n\n\nDjango REST Pandas\n provides a serializer and renderers that support additional data processing and output via the \nPandas\n DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both \n.xls\n and \n.xlsx\n), and a number of \nother formats\n. It is maintained by \nS. Andrew Sheppard\n as part of the \nwq Project\n.\n\n\nLaTeX\n\n\nRest Framework Latex\n provides a renderer that outputs PDFs using Laulatex. It is maintained by \nPebble (S/F Software)\n.", "title": "Renderers" }, { @@ -1325,16 +1330,6 @@ "text": "MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.", "title": "MessagePack" }, - { - "location": "/api-guide/renderers/#xlsx-binary-spreadsheet-endpoints", - "text": "XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-renderer-xlsx , which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.", - "title": "XLSX (Binary Spreadsheet Endpoints)" - }, - { - "location": "/api-guide/renderers/#installation-configuration_3", - "text": "Install using pip. $ pip install drf-renderer-xlsx Modify your REST framework settings. REST_FRAMEWORK = {\n ...\n\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'drf_renderer_xlsx.renderers.XLSXRenderer',\n ),\n} To avoid having a file streamed without a filename (which the browser will often default to the filename \"download\", with no extension), we need to use a mixin to override the Content-Disposition header. If no filename is provided, it will default to export.xlsx . For example: from rest_framework.viewsets import ReadOnlyModelViewSet\nfrom drf_renderer_xlsx.mixins import XLSXFileMixin\nfrom drf_renderer_xlsx.renderers import XLSXRenderer\n\nfrom .models import MyExampleModel\nfrom .serializers import MyExampleSerializer\n\nclass MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):\n queryset = MyExampleModel.objects.all()\n serializer_class = MyExampleSerializer\n renderer_classes = (XLSXRenderer,)\n filename = 'my_export.xlsx'", - "title": "Installation & configuration" - }, { "location": "/api-guide/renderers/#csv", "text": "Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the djangorestframework-csv package which provides CSV renderer support for REST framework.", @@ -1362,7 +1357,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\u2014 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\nimport io\nfrom rest_framework.parsers import JSONParser\n\nstream = io.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 \n.update()\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_\n methods to your \nSerializer\n subclass. These are similar to the \n.clean_\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_\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 \n\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 \nserializers.ValidationError\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'] > 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 \n.update()\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\nThere are however, third-party packages available such as \nDRF Writable Nested\n that support automatic writable nested representations.\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>>> serializer = AccountSerializer()\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\nSince version 3.3.0, it is \nmandatory\n to provide one of the attributes \nfields\n or \nexclude\n.\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\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->instance and id->data 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 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 \nserializers.ValidationError\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 serializers.ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise serializers.ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise serializers.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 or deserialization behavior 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\nMay be overridden in order modify the representation style. For example:\n\n\ndef to_representation(self, instance):\n \"\"\"Convert `username` to lowercase.\"\"\"\n ret = super().to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n\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. The \nerrors\n argument should be a dictionary mapping field names (or \nsettings.NON_FIELD_ERRORS_KEY\n) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the \n.validate()\n method.\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\nSerializer Inheritance\n\n\nSimilar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,\n\n\nclass MyBaseSerializer(Serializer):\n my_field = serializers.CharField()\n\n def validate_my_field(self, value):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ...\n\n\n\nLike Django's \nModel\n and \nModelForm\n classes, the inner \nMeta\n class on serializers does not implicitly inherit from it's parents' inner \nMeta\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\nAdditionally, the following caveats apply to serializer inheritance:\n\n\n\n\nNormal Python name resolution rules apply. If you have multiple base classes that declare a \nMeta\n inner class, only the first one will be used. This means the child\u2019s \nMeta\n, if it exists, otherwise the \nMeta\n of the first parent, etc.\n\n\n\n\nIt\u2019s possible to declaratively remove a \nField\n inherited from a parent class by setting the name to be \nNone\n on the subclass.\n\n\nclass MyBaseSerializer(ModelSerializer):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None\n\n\n\nHowever, you can only use this technique to opt out from a field defined declaratively by a parent class; it won\u2019t prevent the \nModelSerializer\n from generating a default field. To opt-out from default fields, see \nSpecifying which fields to include\n.\n\n\n\n\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)\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>>> class Meta:\n>>> model = User\n>>> fields = ('id', 'username', 'email')\n>>>\n>>> print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\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\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\nDRF FlexFields\n\n\nThe \ndrf-flex-fields\n package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.\n\n\nSerializer Extensions\n\n\nThe \ndjango-rest-framework-serializer-extensions\n\npackage provides a collection of tools to DRY up your serializers, by allowing\nfields to be defined on a per-view/request basis. Fields can be whitelisted,\nblacklisted and child serializers can be optionally expanded.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \n
        \n submissions per the (inactive) \nHTML JSON Form specification\n. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, \n\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.\n\n\nDRF-Base64\n\n\nDRF-Base64\n provides a set of field and model serializers that handles the upload of base64-encoded files.\n\n\nQueryFields\n\n\ndjangorestframework-queryfields\n allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.\n\n\nDRF Writable Nested\n\n\nThe \ndrf-writable-nested\n package provides writable nested model serializer which allows to create/update models with nested related data.", + "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\u2014 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 \n.update()\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_\n methods to your \nSerializer\n subclass. These are similar to the \n.clean_\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_\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 \n\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 \nserializers.ValidationError\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'] > 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 \n.update()\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\nThere are however, third-party packages available such as \nDRF Writable Nested\n that support automatic writable nested representations.\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>>> serializer = AccountSerializer()\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\nSince version 3.3.0, it is \nmandatory\n to provide one of the attributes \nfields\n or \nexclude\n.\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\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->instance and id->data 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 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 \nserializers.ValidationError\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 serializers.ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise serializers.ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise serializers.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 or deserialization behavior 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\nMay be overridden in order modify the representation style. For example:\n\n\ndef to_representation(self, instance):\n \"\"\"Convert `username` to lowercase.\"\"\"\n ret = super().to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n\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. The \nerrors\n argument should be a dictionary mapping field names (or \nsettings.NON_FIELD_ERRORS_KEY\n) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the \n.validate()\n method.\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\nSerializer Inheritance\n\n\nSimilar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,\n\n\nclass MyBaseSerializer(Serializer):\n my_field = serializers.CharField()\n\n def validate_my_field(self):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ...\n\n\n\nLike Django's \nModel\n and \nModelForm\n classes, the inner \nMeta\n class on serializers does not implicitly inherit from it's parents' inner \nMeta\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\nAdditionally, the following caveats apply to serializer inheritance:\n\n\n\n\nNormal Python name resolution rules apply. If you have multiple base classes that declare a \nMeta\n inner class, only the first one will be used. This means the child\u2019s \nMeta\n, if it exists, otherwise the \nMeta\n of the first parent, etc.\n\n\n\n\nIt\u2019s possible to declaratively remove a \nField\n inherited from a parent class by setting the name to be \nNone\n on the subclass.\n\n\nclass MyBaseSerializer(ModelSerializer):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None\n\n\n\nHowever, you can only use this technique to opt out from a field defined declaratively by a parent class; it won\u2019t prevent the \nModelSerializer\n from generating a default field. To opt-out from default fields, see \nSpecifying which fields to include\n.\n\n\n\n\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)\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>>> class Meta:\n>>> model = User\n>>> fields = ('id', 'username', 'email')\n>>>\n>>> print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\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\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\nDRF FlexFields\n\n\nThe \ndrf-flex-fields\n package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.\n\n\nSerializer Extensions\n\n\nThe \ndjango-rest-framework-serializer-extensions\n\npackage provides a collection of tools to DRY up your serializers, by allowing\nfields to be defined on a per-view/request basis. Fields can be whitelisted,\nblacklisted and child serializers can be optionally expanded.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \n\n submissions per the (inactive) \nHTML JSON Form specification\n. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, \n\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.\n\n\nDRF-Base64\n\n\nDRF-Base64\n provides a set of field and model serializers that handles the upload of base64-encoded files.\n\n\nQueryFields\n\n\ndjangorestframework-queryfields\n allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.\n\n\nDRF Writable Nested\n\n\nThe \ndrf-writable-nested\n package provides writable nested model serializer which allows to create/update models with nested related data.", "title": "Serializers" }, { @@ -1382,7 +1377,7 @@ }, { "location": "/api-guide/serializers/#deserializing-objects", - "text": "Deserialization is similar. First we parse a stream into Python native datatypes... import io\nfrom rest_framework.parsers import JSONParser\n\nstream = io.BytesIO(json)\ndata = JSONParser().parse(stream) ...then we restore those native datatypes into a dictionary of validated data. serializer = 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)}", + "text": "Deserialization is similar. First we parse a stream into Python native datatypes... from django.utils.six import BytesIO\nfrom rest_framework.parsers import JSONParser\n\nstream = BytesIO(json)\ndata = JSONParser().parse(stream) ...then we restore those native datatypes into a dictionary of validated data. serializer = 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)}", "title": "Deserializing objects" }, { @@ -1672,7 +1667,7 @@ }, { "location": "/api-guide/serializers/#serializer-inheritance", - "text": "Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example, class MyBaseSerializer(Serializer):\n my_field = serializers.CharField()\n\n def validate_my_field(self, value):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ... Like Django's Model and ModelForm classes, the inner Meta class on serializers does not implicitly inherit from it's parents' inner Meta classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example: class AccountSerializer(MyBaseSerializer):\n class Meta(MyBaseSerializer.Meta):\n model = Account Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly. Additionally, the following caveats apply to serializer inheritance: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child\u2019s Meta , if it exists, otherwise the Meta of the first parent, etc. It\u2019s possible to declaratively remove a Field inherited from a parent class by setting the name to be None on the subclass. class MyBaseSerializer(ModelSerializer):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won\u2019t prevent the ModelSerializer from generating a default field. To opt-out from default fields, see Specifying which fields to include .", + "text": "Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example, class MyBaseSerializer(Serializer):\n my_field = serializers.CharField()\n\n def validate_my_field(self):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ... Like Django's Model and ModelForm classes, the inner Meta class on serializers does not implicitly inherit from it's parents' inner Meta classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example: class AccountSerializer(MyBaseSerializer):\n class Meta(MyBaseSerializer.Meta):\n model = Account Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly. Additionally, the following caveats apply to serializer inheritance: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child\u2019s Meta , if it exists, otherwise the Meta of the first parent, etc. It\u2019s possible to declaratively remove a Field inherited from a parent class by setting the name to be None on the subclass. class MyBaseSerializer(ModelSerializer):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won\u2019t prevent the ModelSerializer from generating a default field. To opt-out from default fields, see Specifying which fields to include .", "title": "Serializer Inheritance" }, { @@ -1762,7 +1757,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 \u2014 normalizing it to a consistent format.\n\n\n\u2014 \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.\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\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\nWhen serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.\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\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\nNote that, without an explicit \ndefault\n, setting this argument to \nTrue\n will imply a \ndefault\n value of \nnull\n for serialization output, but does not imply a default for input deserialization.\n\n\nDefaults to \nFalse\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. When serializing fields with dotted notation, it may be necessary to provide a \ndefault\n value if any object is not present or is empty during attribute traversal.\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 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 & 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\nNote that default \nBooleanField\n instances will be generated with a \nrequired=False\n option (since Django \nmodels.BooleanField\n is always \nblank=True\n). If you want to change this behaviour explicitly declare the \nBooleanField\n on the serializer class.\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:///\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. It must be either \nNone\n or an integer greater than or equal to \ndecimal_places\n.\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\nrounding\n Sets the rounding mode used when quantising to the configured precision. Valid values are \ndecimal\n module rounding modes\n. Defaults to \nNone\n.\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\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\nSignature:\n \nDurationField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the duration provided is no greater than this value.\n\n\nmin_value\n Validate that the duration provided is no less than this value.\n\n\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=, min_length=None, max_length=None)\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\nmin_length\n - Validates that the list contains no fewer than this number of elements.\n\n\nmax_length\n - Validates that the list contains no more than this number of elements.\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\nHStoreField\n\n\nA preconfigured \nDictField\n that is compatible with Django's postgres \nHStoreField\n.\n\n\nSignature\n: \nHStoreField(child=)\n\n\n\n\nchild\n - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.\n\n\n\n\nNote that the child field \nmust\n be an instance of \nCharField\n, as the hstore extension stores values as strings.\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=)\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_\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\nA Basic Custom Field\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 >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 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, value):\n return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.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, instance):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return instance\n\n def to_representation(self, value):\n \"\"\"\n Serialize the value's class name.\n \"\"\"\n return value.__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 > 255 or col < 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 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 > 255 or col < 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 your error messages cleaner and more separated from your code, and should be preferred.\n\n\nUsing \nsource='*'\n\n\nHere we'll take an example of a \nflat\n \nDataPoint\n model with \nx_coordinate\n and \ny_coordinate\n attributes.\n\n\nclass DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField()\n\n\n\nUsing a custom field and \nsource='*'\n we can provide a nested representation of\nthe coordinate pair:\n\n\nclass CoordinateField(serializers.Field):\n\n def to_representation(self, value):\n ret = {\n \"x\": value.x_coordinate,\n \"y\": value.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n\n\n\nNote that this example doesn't handle validation. Partly for that reason, in a\nreal project, the coordinate nesting might be better handled with a nested serialiser\nusing \nsource='*'\n, with two \nIntegerField\n instances, each with their own \nsource\n\npointing to the relevant field.\n\n\nThe key points from the example, though, are:\n\n\n\n\n\n\nto_representation\n is passed the entire \nDataPoint\n object and must map from that\nto the desired output.\n\n\n>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'), ('coordinates', {'x': 1, 'y': 2})])\n\n\n\n\n\n\n\nUnless our field is to be read-only, \nto_internal_value\n must map back to a dict\nsuitable for updating our target object. With \nsource='*'\n, the return from\n\nto_internal_value\n will update the root validated data dictionary, rather than a single key.\n\n\n>>> data = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)])\n\n\n\n\n\n\n\nFor completeness lets do the same thing again but with the nested serialiser\napproach suggested above:\n\n\nclass NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n\n\n\nHere the mapping between the target and source attribute pairs (\nx\n and\n\nx_coordinate\n, \ny\n and \ny_coordinate\n) is handled in the \nIntegerField\n\ndeclarations. It's our \nNestedCoordinateSerializer\n that takes \nsource='*'\n.\n\n\nOur new \nDataPointSerializer\n exhibits the same behaviour as the custom field\napproach.\n\n\nSerialising:\n\n\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])\n\n\n\nDeserialising:\n\n\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)])\n\n\n\nBut we also get the built-in validation for free:\n\n\n>>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})])\n\n\n\nFor this reason, the nested serialiser approach would be the first to try. You\nwould use the custom field approach when the nested serialiser becomes infeasible\nor overly complex.\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\ndjangorestframework-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 \u2014 normalizing it to a consistent format.\n\n\n\u2014 \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.\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\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\nWhen serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.\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\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\nNote that, without an explicit \ndefault\n, setting this argument to \nTrue\n will imply a \ndefault\n value of \nnull\n for serialization output, but does not imply a default for input deserialization.\n\n\nDefaults to \nFalse\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. When serializing fields with dotted notation, it may be necessary to provide a \ndefault\n value if any object is not present or is empty during attribute traversal.\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 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 & 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\nNote that default \nBooleanField\n instances will be generated with a \nrequired=False\n option (since Django \nmodels.BooleanField\n is always \nblank=True\n). If you want to change this behaviour explicitly declare the \nBooleanField\n on the serializer class.\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:///\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. It must be either \nNone\n or an integer greater than or equal to \ndecimal_places\n.\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\nrounding\n Sets the rounding mode used when quantising to the configured precision. Valid values are \ndecimal\n module rounding modes\n. Defaults to \nNone\n.\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\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\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=, min_length=None, max_length=None)\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\nmin_length\n - Validates that the list contains no fewer than this number of elements.\n\n\nmax_length\n - Validates that the list contains no more than this number of elements.\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\nHStoreField\n\n\nA preconfigured \nDictField\n that is compatible with Django's postgres \nHStoreField\n.\n\n\nSignature\n: \nHStoreField(child=)\n\n\n\n\nchild\n - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.\n\n\n\n\nNote that the child field \nmust\n be an instance of \nCharField\n, as the hstore extension stores values as strings.\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=)\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_\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\nA Basic Custom Field\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 >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 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 > 255 or col < 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 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 > 255 or col < 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 your error messages cleaner and more separated from your code, and should be preferred.\n\n\nUsing \nsource='*'\n\n\nHere we'll take an example of a \nflat\n \nDataPoint\n model with \nx_coordinate\n and \ny_coordinate\n attributes.\n\n\nclass DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField()\n\n\n\nUsing a custom field and \nsource='*'\n we can provide a nested representation of\nthe coordinate pair:\n\n\nclass CoordinateField(serializers.Field):\n\n def to_representation(self, obj):\n ret = {\n \"x\": obj.x_coordinate,\n \"y\": obj.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n\n\n\nNote that this example doesn't handle validation. Partly for that reason, in a\nreal project, the coordinate nesting might be better handled with a nested serialiser\nusing \nsource='*'\n, with two \nIntegerField\n instances, each with their own \nsource\n\npointing to the relevant field.\n\n\nThe key points from the example, though, are:\n\n\n\n\n\n\nto_representation\n is passed the entire \nDataPoint\n object and must map from that\nto the desired output.\n\n\n>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'), ('coordinates', {'x': 1, 'y': 2})])\n\n\n\n\n\n\n\nUnless our field is to be read-only, \nto_internal_value\n must map back to a dict\nsuitable for updating our target object. With \nsource='*'\n, the return from\n\nto_internal_value\n will update the root validated data dictionary, rather than a single key.\n\n\n>>> data = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)])\n\n\n\n\n\n\n\nFor completeness lets do the same thing again but with the nested serialiser\napproach suggested above:\n\n\nclass NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n\n\n\nHere the mapping between the target and source attribute pairs (\nx\n and\n\nx_coordinate\n, \ny\n and \ny_coordinate\n) is handled in the \nIntegerField\n\ndeclarations. It's our \nNestedCoordinateSerializer\n that takes \nsource='*'\n.\n\n\nOur new \nDataPointSerializer\n exhibits the same behaviour as the custom field\napproach.\n\n\nSerialising:\n\n\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])\n\n\n\nDeserialising:\n\n\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)])\n\n\n\nBut we also get the built-in validation for free:\n\n\n>>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})])\n\n\n\nFor this reason, the nested serialiser approach would be the first to try. You\nwould use the custom field approach when the nested serialiser becomes infeasible\nor overly complex.\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\ndjangorestframework-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" }, { @@ -1962,7 +1957,7 @@ }, { "location": "/api-guide/fields/#durationfield", - "text": "A Duration representation.\nCorresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance.\nThe representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]' . Signature: DurationField(max_value=None, min_value=None) max_value Validate that the duration provided is no greater than this value. min_value Validate that the duration provided is no less than this value.", + "text": "A Duration representation.\nCorresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance.\nThe representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]' . Signature: DurationField()", "title": "DurationField" }, { @@ -2062,7 +2057,7 @@ }, { "location": "/api-guide/fields/#a-basic-custom-field", - "text": "Let's look at an example of serializing a class that represents an RGB color value: class Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 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, value):\n return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.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) By 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 .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field):\n def get_attribute(self, instance):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return instance\n\n def to_representation(self, value):\n \"\"\"\n Serialize the value's class name.\n \"\"\"\n return value.__class__.__name__", + "text": "Let's look at an example of serializing a class that represents an RGB color value: class Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 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) By 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 .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class 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__", "title": "A Basic Custom Field" }, { @@ -2072,7 +2067,7 @@ }, { "location": "/api-guide/fields/#using-source", - "text": "Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField() Using a custom field and source='*' we can provide a nested representation of\nthe coordinate pair: class CoordinateField(serializers.Field):\n\n def to_representation(self, value):\n ret = {\n \"x\": value.x_coordinate,\n \"y\": value.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a\nreal project, the coordinate nesting might be better handled with a nested serialiser\nusing source='*' , with two IntegerField instances, each with their own source \npointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that\nto the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'), ('coordinates', {'x': 1, 'y': 2})]) Unless our field is to be read-only, to_internal_value must map back to a dict\nsuitable for updating our target object. With source='*' , the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)]) For completeness lets do the same thing again but with the nested serialiser\napproach suggested above: class NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates'] Here the mapping between the target and source attribute pairs ( x and x_coordinate , y and y_coordinate ) is handled in the IntegerField \ndeclarations. It's our NestedCoordinateSerializer that takes source='*' . Our new DataPointSerializer exhibits the same behaviour as the custom field\napproach. Serialising: >>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserialising: >>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})]) For this reason, the nested serialiser approach would be the first to try. You\nwould use the custom field approach when the nested serialiser becomes infeasible\nor overly complex.", + "text": "Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField() Using a custom field and source='*' we can provide a nested representation of\nthe coordinate pair: class CoordinateField(serializers.Field):\n\n def to_representation(self, obj):\n ret = {\n \"x\": obj.x_coordinate,\n \"y\": obj.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a\nreal project, the coordinate nesting might be better handled with a nested serialiser\nusing source='*' , with two IntegerField instances, each with their own source \npointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that\nto the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'), ('coordinates', {'x': 1, 'y': 2})]) Unless our field is to be read-only, to_internal_value must map back to a dict\nsuitable for updating our target object. With source='*' , the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)]) For completeness lets do the same thing again but with the nested serialiser\napproach suggested above: class NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates'] Here the mapping between the target and source attribute pairs ( x and x_coordinate , y and y_coordinate ) is handled in the IntegerField \ndeclarations. It's our NestedCoordinateSerializer that takes source='*' . Our new DataPointSerializer exhibits the same behaviour as the custom field\napproach. Serialising: >>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserialising: >>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})]) For this reason, the nested serialiser approach would be the first to try. You\nwould use the custom field approach when the nested serialiser becomes infeasible\nor overly complex.", "title": "Using source='*'" }, { @@ -2107,7 +2102,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\u2014 \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.\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>>> serializer = AccountSerializer()\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', on_delete=models.CASCADE)\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 \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 \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>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\n>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\n>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\n>>> serializer = AlbumSerializer(instance=album)\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>>> 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>>> serializer = AlbumSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.save()\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, 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//customers//\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', on_delete=models.CASCADE)\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/stable/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\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\u2014 \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.\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>>> serializer = AccountSerializer()\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', on_delete=models.CASCADE)\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 \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 \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>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\n>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\n>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\n>>> serializer = AlbumSerializer(instance=album)\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>>> 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>>> serializer = AlbumSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.save()\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//customers//\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', on_delete=models.CASCADE)\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/stable/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\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" }, { @@ -2177,7 +2172,7 @@ }, { "location": "/api-guide/relations/#custom-hyperlinked-fields", - "text": "In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding HyperlinkedRelatedField . There are two methods that may be overridden: get_url(self, obj, view_name, request, format) The get_url method is used to map the object instance to its URL representation. May raise a NoReverseMatch if the view_name and lookup_field \nattributes are not configured to correctly match the URL conf. get_object(self, view_name, view_args, view_kwargs) If you want to support a writable hyperlinked field then you'll also want to override get_object , 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. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an ObjectDoesNotExist exception.", + "text": "In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding HyperlinkedRelatedField . There are two methods that may be overridden: get_url(self, obj, view_name, request, format) The get_url method is used to map the object instance to its URL representation. May raise a NoReverseMatch if the view_name and lookup_field \nattributes are not configured to correctly match the URL conf. get_object(self, queryset, view_name, view_args, view_kwargs) If you want to support a writable hyperlinked field then you'll also want to override get_object , 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. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an ObjectDoesNotExist exception.", "title": "Custom hyperlinked fields" }, { @@ -2357,7 +2352,7 @@ }, { "location": "/api-guide/authentication/", - "text": "Authentication\n\n\n\n\nAuth needs to be pluggable.\n\n\n\u2014 Jacob Kaplan-Moss, \n\"REST worst practices\"\n\n\n\n\nAuthentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The \npermission\n and \nthrottling\n policies can then use those credentials to determine if the request should be permitted.\n\n\nREST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.\n\n\nAuthentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.\n\n\nThe \nrequest.user\n property will typically be set to an instance of the \ncontrib.auth\n package's \nUser\n class.\n\n\nThe \nrequest.auth\n property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.\n\n\n\n\nNote:\n Don't forget that \nauthentication by itself won't allow or disallow an incoming request\n, it simply identifies the credentials that the request was made with.\n\n\nFor information on how to setup the permission polices for your API please see the \npermissions documentation\n.\n\n\n\n\nHow authentication is determined\n\n\nThe authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set \nrequest.user\n and \nrequest.auth\n using the return value of the first class that successfully authenticates.\n\n\nIf no class authenticates, \nrequest.user\n will be set to an instance of \ndjango.contrib.auth.models.AnonymousUser\n, and \nrequest.auth\n will be set to \nNone\n.\n\n\nThe value of \nrequest.user\n and \nrequest.auth\n for unauthenticated requests can be modified using the \nUNAUTHENTICATED_USER\n and \nUNAUTHENTICATED_TOKEN\n settings.\n\n\nSetting the authentication scheme\n\n\nThe default authentication schemes may be set globally, using the \nDEFAULT_AUTHENTICATION_CLASSES\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\n\n\nYou can also set the authentication scheme on a per-view or per-viewset basis,\nusing the \nAPIView\n class-based views.\n\n\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@authentication_classes((SessionAuthentication, BasicAuthentication))\n@permission_classes((IsAuthenticated,))\ndef example_view(request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nUnauthorized and Forbidden responses\n\n\nWhen an unauthenticated request is denied permission there are two different error codes that may be appropriate.\n\n\n\n\nHTTP 401 Unauthorized\n\n\nHTTP 403 Permission Denied\n\n\n\n\nHTTP 401 responses must always include a \nWWW-Authenticate\n header, that instructs the client how to authenticate. HTTP 403 responses do not include the \nWWW-Authenticate\n header.\n\n\nThe kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. \nThe first authentication class set on the view is used when determining the type of response\n.\n\n\nNote that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a \n403 Permission Denied\n response will always be used, regardless of the authentication scheme.\n\n\nApache mod_wsgi specific configuration\n\n\nNote that if deploying to \nApache using mod_wsgi\n, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.\n\n\nIf you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the \nWSGIPassAuthorization\n directive in the appropriate context and setting it to \n'On'\n.\n\n\n# this can go in either server config, virtual host, directory or .htaccess\nWSGIPassAuthorization On\n\n\n\n\n\nAPI Reference\n\n\nBasicAuthentication\n\n\nThis authentication scheme uses \nHTTP Basic Authentication\n, signed against a user's username and password. Basic authentication is generally only appropriate for testing.\n\n\nIf successfully authenticated, \nBasicAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Basic realm=\"api\"\n\n\n\nNote:\n If you use \nBasicAuthentication\n in production you must ensure that your API is only available over \nhttps\n. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.\n\n\nTokenAuthentication\n\n\nThis authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.\n\n\nTo use the \nTokenAuthentication\n scheme you'll need to \nconfigure the authentication classes\n to include \nTokenAuthentication\n, and additionally include \nrest_framework.authtoken\n in your \nINSTALLED_APPS\n setting:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n)\n\n\n\n\n\nNote:\n Make sure to run \nmanage.py migrate\n after changing your settings. The \nrest_framework.authtoken\n app provides Django database migrations.\n\n\n\n\nYou'll also need to create tokens for your users.\n\n\nfrom rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key\n\n\n\nFor clients to authenticate, the token key should be included in the \nAuthorization\n HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example:\n\n\nAuthorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\n\n\n\nNote:\n If you want to use a different keyword in the header, such as \nBearer\n, simply subclass \nTokenAuthentication\n and set the \nkeyword\n class variable.\n\n\nIf successfully authenticated, \nTokenAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be a \nrest_framework.authtoken.models.Token\n instance.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Token\n\n\n\nThe \ncurl\n command line tool may be useful for testing token authenticated APIs. For example:\n\n\ncurl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'\n\n\n\n\n\nNote:\n If you use \nTokenAuthentication\n in production you must ensure that your API is only available over \nhttps\n.\n\n\n\n\nGenerating Tokens\n\n\nBy using signals\n\n\nIf you want every user to have an automatically generated Token, you can simply catch the User's \npost_save\n signal.\n\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n\nNote that you'll want to ensure you place this code snippet in an installed \nmodels.py\n module, or some other location that will be imported by Django on startup.\n\n\nIf you've already created some users, you can generate tokens for all existing users like this:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n\n\n\nBy exposing an api endpoint\n\n\nWhen using \nTokenAuthentication\n, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the \nobtain_auth_token\n view to your URLconf:\n\n\nfrom rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n]\n\n\n\nNote that the URL part of the pattern can be whatever you want to use.\n\n\nThe \nobtain_auth_token\n view will return a JSON response when valid \nusername\n and \npassword\n fields are POSTed to the view using form data or JSON:\n\n\n{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }\n\n\n\nNote that the default \nobtain_auth_token\n view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.\n\n\nBy default there are no permissions or throttling applied to the \nobtain_auth_token\n view. If you do wish to apply throttling you'll need to override the view class,\nand include them using the \nthrottle_classes\n attribute.\n\n\nIf you need a customized version of the \nobtain_auth_token\n view, you can do so by subclassing the \nObtainAuthToken\n view class, and using that in your url conf instead.\n\n\nFor example, you may return additional user information beyond the \ntoken\n value:\n\n\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nclass CustomAuthToken(ObtainAuthToken):\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data,\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'user_id': user.pk,\n 'email': user.email\n })\n\n\n\nAnd in your \nurls.py\n:\n\n\nurlpatterns += [\n url(r'^api-token-auth/', CustomAuthToken.as_view())\n]\n\n\n\nWith Django admin\n\n\nIt is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the \nTokenAdmin\n class to customize it to your needs, more specifically by declaring the \nuser\n field as \nraw_field\n.\n\n\nyour_app/admin.py\n:\n\n\nfrom rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)\n\n\n\nUsing Django manage.py command\n\n\nSince version 3.6.4 it's possible to generate a user token using the following command:\n\n\n./manage.py drf_create_token \n\n\n\nthis command will return the API token for the given user, creating it if it doesn't exist:\n\n\nGenerated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1\n\n\n\nIn case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:\n\n\n./manage.py drf_create_token -r \n\n\n\nSessionAuthentication\n\n\nThis authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.\n\n\nIf successfully authenticated, \nSessionAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 403 Forbidden\n response.\n\n\nIf you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as \nPUT\n, \nPATCH\n, \nPOST\n or \nDELETE\n requests. See the \nDjango CSRF documentation\n for more details.\n\n\nWarning\n: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.\n\n\nCSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.\n\n\nRemoteUserAuthentication\n\n\nThis authentication scheme allows you to delegate authentication to your web server, which sets the \nREMOTE_USER\n\nenvironment variable.\n\n\nTo use it, you must have \ndjango.contrib.auth.backends.RemoteUserBackend\n (or a subclass) in your\n\nAUTHENTICATION_BACKENDS\n setting. By default, \nRemoteUserBackend\n creates \nUser\n objects for usernames that don't\nalready exist. To change this and other behaviour, consult the\n\nDjango documentation\n.\n\n\nIf successfully authenticated, \nRemoteUserAuthentication\n provides the following credentials:\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nConsult your web server's documentation for information about configuring an authentication method, e.g.:\n\n\n\n\nApache Authentication How-To\n\n\nNGINX (Restricting Access)\n\n\n\n\nCustom authentication\n\n\nTo implement a custom authentication scheme, subclass \nBaseAuthentication\n and override the \n.authenticate(self, request)\n method. The method should return a two-tuple of \n(user, auth)\n if authentication succeeds, or \nNone\n otherwise.\n\n\nIn some circumstances instead of returning \nNone\n, you may want to raise an \nAuthenticationFailed\n exception from the \n.authenticate()\n method.\n\n\nTypically the approach you should take is:\n\n\n\n\nIf authentication is not attempted, return \nNone\n. Any other authentication schemes also in use will still be checked.\n\n\nIf authentication is attempted but fails, raise a \nAuthenticationFailed\n exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.\n\n\n\n\nYou \nmay\n also override the \n.authenticate_header(self, request)\n method. If implemented, it should return a string that will be used as the value of the \nWWW-Authenticate\n header in a \nHTTP 401 Unauthorized\n response.\n\n\nIf the \n.authenticate_header()\n method is not overridden, the authentication scheme will return \nHTTP 403 Forbidden\n responses when an unauthenticated request is denied access.\n\n\n\n\nNote:\n When your custom authenticator is invoked by the request object's \n.user\n or \n.auth\n properties, you may see an \nAttributeError\n re-raised as a \nWrappedAttributeError\n. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the \nAttributeError\n orginates from your custom authenticator and will instead assume that the request object does not have a \n.user\n or \n.auth\n property. These errors should be fixed or otherwise handled by your authenticator.\n\n\n\n\nExample\n\n\nThe following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango OAuth Toolkit\n\n\nThe \nDjango OAuth Toolkit\n package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by \nEvonove\n and uses the excellent \nOAuthLib\n. The package is well documented, and well supported and is currently our \nrecommended package for OAuth 2.0 support\n.\n\n\nInstallation & configuration\n\n\nInstall using \npip\n.\n\n\npip install django-oauth-toolkit\n\n\n\nAdd the package to your \nINSTALLED_APPS\n and modify your REST framework settings.\n\n\nINSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n )\n}\n\n\n\nFor more details see the \nDjango REST framework - Getting started\n documentation.\n\n\nDjango REST framework OAuth\n\n\nThe \nDjango REST framework OAuth\n package provides both OAuth1 and OAuth2 support for REST framework.\n\n\nThis package was previously included directly in REST framework but is now supported and maintained as a third party package.\n\n\nInstallation & configuration\n\n\nInstall the package using \npip\n.\n\n\npip install djangorestframework-oauth\n\n\n\nFor details on configuration and usage see the Django REST framework OAuth documentation for \nauthentication\n and \npermissions\n.\n\n\nDigest Authentication\n\n\nHTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. \nJuan Riaza\n maintains the \ndjangorestframework-digestauth\n package which provides HTTP digest authentication support for REST framework.\n\n\nJSON Web Token Authentication\n\n\nJSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. \nBlimp\n maintains the \ndjangorestframework-jwt\n package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is \ndjangorestframework-simplejwt\n which provides different features as well as a pluggable token blacklist app.\n\n\nHawk HTTP Authentication\n\n\nThe \nHawkREST\n library builds on the \nMohawk\n library to let you work with \nHawk\n signed requests and responses in your API. \nHawk\n lets two parties securely communicate with each other using messages signed by a shared key. It is based on \nHTTP MAC access authentication\n (which was based on parts of \nOAuth 1.0\n).\n\n\nHTTP Signature Authentication\n\n\nHTTP Signature (currently a \nIETF draft\n) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to \nAmazon's HTTP Signature scheme\n, used by many of its services, it permits stateless, per-request authentication. \nElvio Toccalino\n maintains the \ndjangorestframework-httpsignature\n (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of \ndjangorestframework-httpsignature\n, which is \ndrf-httpsig\n.\n\n\nDjoser\n\n\nDjoser\n library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.\n\n\ndjango-rest-auth\n\n\nDjango-rest-auth\n library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.\n\n\ndjango-rest-framework-social-oauth2\n\n\nDjango-rest-framework-social-oauth2\n library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.\n\n\ndjango-rest-knox\n\n\nDjango-rest-knox\n library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).\n\n\ndrfpasswordless\n\n\ndrfpasswordless\n adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.", + "text": "Authentication\n\n\n\n\nAuth needs to be pluggable.\n\n\n\u2014 Jacob Kaplan-Moss, \n\"REST worst practices\"\n\n\n\n\nAuthentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The \npermission\n and \nthrottling\n policies can then use those credentials to determine if the request should be permitted.\n\n\nREST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.\n\n\nAuthentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.\n\n\nThe \nrequest.user\n property will typically be set to an instance of the \ncontrib.auth\n package's \nUser\n class.\n\n\nThe \nrequest.auth\n property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.\n\n\n\n\nNote:\n Don't forget that \nauthentication by itself won't allow or disallow an incoming request\n, it simply identifies the credentials that the request was made with.\n\n\nFor information on how to setup the permission polices for your API please see the \npermissions documentation\n.\n\n\n\n\nHow authentication is determined\n\n\nThe authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set \nrequest.user\n and \nrequest.auth\n using the return value of the first class that successfully authenticates.\n\n\nIf no class authenticates, \nrequest.user\n will be set to an instance of \ndjango.contrib.auth.models.AnonymousUser\n, and \nrequest.auth\n will be set to \nNone\n.\n\n\nThe value of \nrequest.user\n and \nrequest.auth\n for unauthenticated requests can be modified using the \nUNAUTHENTICATED_USER\n and \nUNAUTHENTICATED_TOKEN\n settings.\n\n\nSetting the authentication scheme\n\n\nThe default authentication schemes may be set globally, using the \nDEFAULT_AUTHENTICATION_CLASSES\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\n\n\nYou can also set the authentication scheme on a per-view or per-viewset basis,\nusing the \nAPIView\n class-based views.\n\n\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@authentication_classes((SessionAuthentication, BasicAuthentication))\n@permission_classes((IsAuthenticated,))\ndef example_view(request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nUnauthorized and Forbidden responses\n\n\nWhen an unauthenticated request is denied permission there are two different error codes that may be appropriate.\n\n\n\n\nHTTP 401 Unauthorized\n\n\nHTTP 403 Permission Denied\n\n\n\n\nHTTP 401 responses must always include a \nWWW-Authenticate\n header, that instructs the client how to authenticate. HTTP 403 responses do not include the \nWWW-Authenticate\n header.\n\n\nThe kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. \nThe first authentication class set on the view is used when determining the type of response\n.\n\n\nNote that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a \n403 Permission Denied\n response will always be used, regardless of the authentication scheme.\n\n\nApache mod_wsgi specific configuration\n\n\nNote that if deploying to \nApache using mod_wsgi\n, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.\n\n\nIf you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the \nWSGIPassAuthorization\n directive in the appropriate context and setting it to \n'On'\n.\n\n\n# this can go in either server config, virtual host, directory or .htaccess\nWSGIPassAuthorization On\n\n\n\n\n\nAPI Reference\n\n\nBasicAuthentication\n\n\nThis authentication scheme uses \nHTTP Basic Authentication\n, signed against a user's username and password. Basic authentication is generally only appropriate for testing.\n\n\nIf successfully authenticated, \nBasicAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Basic realm=\"api\"\n\n\n\nNote:\n If you use \nBasicAuthentication\n in production you must ensure that your API is only available over \nhttps\n. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.\n\n\nTokenAuthentication\n\n\nThis authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.\n\n\nTo use the \nTokenAuthentication\n scheme you'll need to \nconfigure the authentication classes\n to include \nTokenAuthentication\n, and additionally include \nrest_framework.authtoken\n in your \nINSTALLED_APPS\n setting:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n)\n\n\n\n\n\nNote:\n Make sure to run \nmanage.py migrate\n after changing your settings. The \nrest_framework.authtoken\n app provides Django database migrations.\n\n\n\n\nYou'll also need to create tokens for your users.\n\n\nfrom rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key\n\n\n\nFor clients to authenticate, the token key should be included in the \nAuthorization\n HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example:\n\n\nAuthorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\n\n\n\nNote:\n If you want to use a different keyword in the header, such as \nBearer\n, simply subclass \nTokenAuthentication\n and set the \nkeyword\n class variable.\n\n\nIf successfully authenticated, \nTokenAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be a \nrest_framework.authtoken.models.Token\n instance.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Token\n\n\n\nThe \ncurl\n command line tool may be useful for testing token authenticated APIs. For example:\n\n\ncurl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'\n\n\n\n\n\nNote:\n If you use \nTokenAuthentication\n in production you must ensure that your API is only available over \nhttps\n.\n\n\n\n\nGenerating Tokens\n\n\nBy using signals\n\n\nIf you want every user to have an automatically generated Token, you can simply catch the User's \npost_save\n signal.\n\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n\nNote that you'll want to ensure you place this code snippet in an installed \nmodels.py\n module, or some other location that will be imported by Django on startup.\n\n\nIf you've already created some users, you can generate tokens for all existing users like this:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n\n\n\nBy exposing an api endpoint\n\n\nWhen using \nTokenAuthentication\n, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the \nobtain_auth_token\n view to your URLconf:\n\n\nfrom rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n]\n\n\n\nNote that the URL part of the pattern can be whatever you want to use.\n\n\nThe \nobtain_auth_token\n view will return a JSON response when valid \nusername\n and \npassword\n fields are POSTed to the view using form data or JSON:\n\n\n{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }\n\n\n\nNote that the default \nobtain_auth_token\n view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.\n\n\nBy default there are no permissions or throttling applied to the \nobtain_auth_token\n view. If you do wish to apply throttling you'll need to override the view class,\nand include them using the \nthrottle_classes\n attribute.\n\n\nIf you need a customized version of the \nobtain_auth_token\n view, you can do so by subclassing the \nObtainAuthToken\n view class, and using that in your url conf instead.\n\n\nFor example, you may return additional user information beyond the \ntoken\n value:\n\n\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nclass CustomAuthToken(ObtainAuthToken):\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data,\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'user_id': user.pk,\n 'email': user.email\n })\n\n\n\nAnd in your \nurls.py\n:\n\n\nurlpatterns += [\n url(r'^api-token-auth/', CustomAuthToken.as_view())\n]\n\n\n\nWith Django admin\n\n\nIt is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the \nTokenAdmin\n class to customize it to your needs, more specifically by declaring the \nuser\n field as \nraw_field\n.\n\n\nyour_app/admin.py\n:\n\n\nfrom rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)\n\n\n\nUsing Django manage.py command\n\n\nSince version 3.6.4 it's possible to generate a user token using the following command:\n\n\n./manage.py drf_create_token \n\n\n\nthis command will return the API token for the given user, creating it if it doesn't exist:\n\n\nGenerated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1\n\n\n\nIn case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:\n\n\n./manage.py drf_create_token -r \n\n\n\nSessionAuthentication\n\n\nThis authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.\n\n\nIf successfully authenticated, \nSessionAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 403 Forbidden\n response.\n\n\nIf you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as \nPUT\n, \nPATCH\n, \nPOST\n or \nDELETE\n requests. See the \nDjango CSRF documentation\n for more details.\n\n\nWarning\n: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.\n\n\nCSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.\n\n\nRemoteUserAuthentication\n\n\nThis authentication scheme allows you to delegate authentication to your web server, which sets the \nREMOTE_USER\n\nenvironment variable.\n\n\nTo use it, you must have \ndjango.contrib.auth.backends.RemoteUserBackend\n (or a subclass) in your\n\nAUTHENTICATION_BACKENDS\n setting. By default, \nRemoteUserBackend\n creates \nUser\n objects for usernames that don't\nalready exist. To change this and other behaviour, consult the\n\nDjango documentation\n.\n\n\nIf successfully authenticated, \nRemoteUserAuthentication\n provides the following credentials:\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nConsult your web server's documentation for information about configuring an authentication method, e.g.:\n\n\n\n\nApache Authentication How-To\n\n\nNGINX (Restricting Access)\n\n\n\n\nCustom authentication\n\n\nTo implement a custom authentication scheme, subclass \nBaseAuthentication\n and override the \n.authenticate(self, request)\n method. The method should return a two-tuple of \n(user, auth)\n if authentication succeeds, or \nNone\n otherwise.\n\n\nIn some circumstances instead of returning \nNone\n, you may want to raise an \nAuthenticationFailed\n exception from the \n.authenticate()\n method.\n\n\nTypically the approach you should take is:\n\n\n\n\nIf authentication is not attempted, return \nNone\n. Any other authentication schemes also in use will still be checked.\n\n\nIf authentication is attempted but fails, raise a \nAuthenticationFailed\n exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.\n\n\n\n\nYou \nmay\n also override the \n.authenticate_header(self, request)\n method. If implemented, it should return a string that will be used as the value of the \nWWW-Authenticate\n header in a \nHTTP 401 Unauthorized\n response.\n\n\nIf the \n.authenticate_header()\n method is not overridden, the authentication scheme will return \nHTTP 403 Forbidden\n responses when an unauthenticated request is denied access.\n\n\n\n\nNote:\n When your custom authenticator is invoked by the request object's \n.user\n or \n.auth\n properties, you may see an \nAttributeError\n re-raised as a \nWrappedAttributeError\n. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the \nAttributeError\n orginates from your custom authenticator and will instead assume that the request object does not have a \n.user\n or \n.auth\n property. These errors should be fixed or otherwise handled by your authenticator.\n\n\n\n\nExample\n\n\nThe following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango OAuth Toolkit\n\n\nThe \nDjango OAuth Toolkit\n package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by \nEvonove\n and uses the excellent \nOAuthLib\n. The package is well documented, and well supported and is currently our \nrecommended package for OAuth 2.0 support\n.\n\n\nInstallation & configuration\n\n\nInstall using \npip\n.\n\n\npip install django-oauth-toolkit\n\n\n\nAdd the package to your \nINSTALLED_APPS\n and modify your REST framework settings.\n\n\nINSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n )\n}\n\n\n\nFor more details see the \nDjango REST framework - Getting started\n documentation.\n\n\nDjango REST framework OAuth\n\n\nThe \nDjango REST framework OAuth\n package provides both OAuth1 and OAuth2 support for REST framework.\n\n\nThis package was previously included directly in REST framework but is now supported and maintained as a third party package.\n\n\nInstallation & configuration\n\n\nInstall the package using \npip\n.\n\n\npip install djangorestframework-oauth\n\n\n\nFor details on configuration and usage see the Django REST framework OAuth documentation for \nauthentication\n and \npermissions\n.\n\n\nDigest Authentication\n\n\nHTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. \nJuan Riaza\n maintains the \ndjangorestframework-digestauth\n package which provides HTTP digest authentication support for REST framework.\n\n\nDjango OAuth2 Consumer\n\n\nThe \nDjango OAuth2 Consumer\n library from \nRediker Software\n is another package that provides \nOAuth 2.0 support for REST framework\n. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.\n\n\nJSON Web Token Authentication\n\n\nJSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. \nBlimp\n maintains the \ndjangorestframework-jwt\n package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is \ndjangorestframework-simplejwt\n which provides different features as well as a pluggable token blacklist app.\n\n\nHawk HTTP Authentication\n\n\nThe \nHawkREST\n library builds on the \nMohawk\n library to let you work with \nHawk\n signed requests and responses in your API. \nHawk\n lets two parties securely communicate with each other using messages signed by a shared key. It is based on \nHTTP MAC access authentication\n (which was based on parts of \nOAuth 1.0\n).\n\n\nHTTP Signature Authentication\n\n\nHTTP Signature (currently a \nIETF draft\n) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to \nAmazon's HTTP Signature scheme\n, used by many of its services, it permits stateless, per-request authentication. \nElvio Toccalino\n maintains the \ndjangorestframework-httpsignature\n package which provides an easy to use HTTP Signature Authentication mechanism.\n\n\nDjoser\n\n\nDjoser\n library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.\n\n\ndjango-rest-auth\n\n\nDjango-rest-auth\n library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.\n\n\ndjango-rest-framework-social-oauth2\n\n\nDjango-rest-framework-social-oauth2\n library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.\n\n\ndjango-rest-knox\n\n\nDjango-rest-knox\n library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).\n\n\ndrfpasswordless\n\n\ndrfpasswordless\n adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.", "title": "Authentication" }, { @@ -2475,6 +2470,11 @@ "text": "HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. Juan Riaza maintains the djangorestframework-digestauth package which provides HTTP digest authentication support for REST framework.", "title": "Digest Authentication" }, + { + "location": "/api-guide/authentication/#django-oauth2-consumer", + "text": "The Django OAuth2 Consumer library from Rediker Software is another package that provides OAuth 2.0 support for REST framework . The package includes token scoping permissions on tokens, which allows finer-grained access to your API.", + "title": "Django OAuth2 Consumer" + }, { "location": "/api-guide/authentication/#json-web-token-authentication", "text": "JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. Blimp maintains the djangorestframework-jwt package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is djangorestframework-simplejwt which provides different features as well as a pluggable token blacklist app.", @@ -2487,7 +2487,7 @@ }, { "location": "/api-guide/authentication/#http-signature-authentication", - "text": "HTTP Signature (currently a IETF draft ) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme , used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature , which is drf-httpsig .", + "text": "HTTP Signature (currently a IETF draft ) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme , used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature package which provides an easy to use HTTP Signature Authentication mechanism.", "title": "HTTP Signature Authentication" }, { @@ -2635,21 +2635,6 @@ "text": "The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.", "title": "Django Rest Framework Role Filters" }, - { - "location": "/api-guide/caching/", - "text": "Caching\n\n\n\n\nA certain woman had a very sharp conciousness but almost no\nmemory ... She remembered enough to work, and she worked hard.\n- Lydia Davis\n\n\n\n\nCaching in REST Framework works well with the cache utilities\nprovided in Django.\n\n\n\n\nUsing cache with apiview and viewsets\n\n\nDjango provides a \nmethod_decorator\n to use\ndecorators with class based views. This can be used with\nwith other cache decorators such as \ncache_page\n and\n\nvary_on_cookie\n.\n\n\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\n\nclass UserViewSet(viewsets.Viewset):\n\n # Cache requested url for each user for 2 hours\n @method_decorator(cache_page(60*60*2))\n @method_decorator(vary_on_cookie)\n def list(self, request, format=None):\n content = {\n 'user_feed': request.user.get_user_feed()\n }\n return Response(content)\n\nclass PostView(APIView):\n\n # Cache page for the requested url\n @method_decorator(cache_page(60*60*2))\n def get(self, request, format=None):\n content = {\n 'title': 'Post title',\n 'body': 'Post content'\n }\n return Response(content)\n\n\n\n\nNOTE:\n The \ncache_page\n decorator only caches the\n\nGET\n and \nHEAD\n responses with status 200.", - "title": "Caching" - }, - { - "location": "/api-guide/caching/#caching", - "text": "A certain woman had a very sharp conciousness but almost no\nmemory ... She remembered enough to work, and she worked hard.\n- Lydia Davis Caching in REST Framework works well with the cache utilities\nprovided in Django.", - "title": "Caching" - }, - { - "location": "/api-guide/caching/#using-cache-with-apiview-and-viewsets", - "text": "Django provides a method_decorator to use\ndecorators with class based views. This can be used with\nwith other cache decorators such as cache_page and vary_on_cookie . from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\n\nclass UserViewSet(viewsets.Viewset):\n\n # Cache requested url for each user for 2 hours\n @method_decorator(cache_page(60*60*2))\n @method_decorator(vary_on_cookie)\n def list(self, request, format=None):\n content = {\n 'user_feed': request.user.get_user_feed()\n }\n return Response(content)\n\nclass PostView(APIView):\n\n # Cache page for the requested url\n @method_decorator(cache_page(60*60*2))\n def get(self, request, format=None):\n content = {\n 'title': 'Post title',\n 'body': 'Post content'\n }\n return Response(content) NOTE: The cache_page decorator only caches the GET and HEAD responses with status 200.", - "title": "Using cache with apiview and viewsets" - }, { "location": "/api-guide/throttling/", "text": "Throttling\n\n\n\n\nHTTP/1.1 420 Enhance Your Calm\n\n\nTwitter API rate limiting response\n\n\n\n\nThrottling is similar to \npermissions\n, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.\n\n\nAs with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.\n\n\nAnother scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.\n\n\nMultiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.\n\n\nThrottles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.\n\n\nHow throttling is determined\n\n\nAs with permissions and authentication, throttling in REST framework is always defined as a list of classes.\n\n\nBefore running the main body of the view each throttle in the list is checked.\nIf any throttle check fails an \nexceptions.Throttled\n exception will be raised, and the main body of the view will not run.\n\n\nSetting the throttling policy\n\n\nThe default throttling policy may be set globally, using the \nDEFAULT_THROTTLE_CLASSES\n and \nDEFAULT_THROTTLE_RATES\n settings. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': (\n 'rest_framework.throttling.AnonRateThrottle',\n 'rest_framework.throttling.UserRateThrottle'\n ),\n 'DEFAULT_THROTTLE_RATES': {\n 'anon': '100/day',\n 'user': '1000/day'\n }\n}\n\n\n\nThe rate descriptions used in \nDEFAULT_THROTTLE_RATES\n may include \nsecond\n, \nminute\n, \nhour\n or \nday\n as the throttle period.\n\n\nYou can also set the throttling policy on a per-view or per-viewset basis,\nusing the \nAPIView\n class-based views.\n\n\nfrom rest_framework.response import Response\nfrom rest_framework.throttling import UserRateThrottle\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n throttle_classes = (UserRateThrottle,)\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@throttle_classes([UserRateThrottle])\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n\n\n\nHow clients are identified\n\n\nThe \nX-Forwarded-For\n HTTP header and \nREMOTE_ADDR\n WSGI variable are used to uniquely identify client IP addresses for throttling. If the \nX-Forwarded-For\n header is present then it will be used, otherwise the value of the \nREMOTE_ADDR\n variable from the WSGI environment will be used.\n\n\nIf you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the \nNUM_PROXIES\n setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the \nX-Forwarded-For\n header, once any application proxy IP addresses have first been excluded. If set to zero, then the \nREMOTE_ADDR\n value will always be used as the identifying IP address.\n\n\nIt is important to understand that if you configure the \nNUM_PROXIES\n setting, then all clients behind a unique \nNAT'd\n gateway will be treated as a single client.\n\n\nFurther context on how the \nX-Forwarded-For\n header works, and identifying a remote client IP can be \nfound here\n.\n\n\nSetting up the cache\n\n\nThe throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate \ncache settings\n. The default value of \nLocMemCache\n backend should be okay for simple setups. See Django's \ncache documentation\n for more details.\n\n\nIf you need to use a cache other than \n'default'\n, you can do so by creating a custom throttle class and setting the \ncache\n attribute. For example:\n\n\nclass CustomAnonRateThrottle(AnonRateThrottle):\n cache = get_cache('alternate')\n\n\n\nYou'll need to remember to also set your custom throttle class in the \n'DEFAULT_THROTTLE_CLASSES'\n settings key, or using the \nthrottle_classes\n view attribute.\n\n\n\n\nAPI Reference\n\n\nAnonRateThrottle\n\n\nThe \nAnonRateThrottle\n will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.\n\n\nThe allowed request rate is determined from one of the following (in order of preference).\n\n\n\n\nThe \nrate\n property on the class, which may be provided by overriding \nAnonRateThrottle\n and setting the property.\n\n\nThe \nDEFAULT_THROTTLE_RATES['anon']\n setting.\n\n\n\n\nAnonRateThrottle\n is suitable if you want to restrict the rate of requests from unknown sources.\n\n\nUserRateThrottle\n\n\nThe \nUserRateThrottle\n will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.\n\n\nThe allowed request rate is determined from one of the following (in order of preference).\n\n\n\n\nThe \nrate\n property on the class, which may be provided by overriding \nUserRateThrottle\n and setting the property.\n\n\nThe \nDEFAULT_THROTTLE_RATES['user']\n setting.\n\n\n\n\nAn API may have multiple \nUserRateThrottles\n in place at the same time. To do so, override \nUserRateThrottle\n and set a unique \"scope\" for each class.\n\n\nFor example, multiple user throttle rates could be implemented by using the following classes...\n\n\nclass BurstRateThrottle(UserRateThrottle):\n scope = 'burst'\n\nclass SustainedRateThrottle(UserRateThrottle):\n scope = 'sustained'\n\n\n\n...and the following settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': (\n 'example.throttles.BurstRateThrottle',\n 'example.throttles.SustainedRateThrottle'\n ),\n 'DEFAULT_THROTTLE_RATES': {\n 'burst': '60/min',\n 'sustained': '1000/day'\n }\n}\n\n\n\nUserRateThrottle\n is suitable if you want simple global rate restrictions per-user.\n\n\nScopedRateThrottle\n\n\nThe \nScopedRateThrottle\n class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a \n.throttle_scope\n property. The unique throttle key will then be formed by concatenating the \"scope\" of the request with the unique user id or IP address.\n\n\nThe allowed request rate is determined by the \nDEFAULT_THROTTLE_RATES\n setting using a key from the request \"scope\".\n\n\nFor example, given the following views...\n\n\nclass ContactListView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass ContactDetailView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass UploadView(APIView):\n throttle_scope = 'uploads'\n ...\n\n\n\n...and the following settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': (\n 'rest_framework.throttling.ScopedRateThrottle',\n ),\n 'DEFAULT_THROTTLE_RATES': {\n 'contacts': '1000/day',\n 'uploads': '20/day'\n }\n}\n\n\n\nUser requests to either \nContactListView\n or \nContactDetailView\n would be restricted to a total of 1000 requests per-day. User requests to \nUploadView\n would be restricted to 20 requests per day.\n\n\n\n\nCustom throttles\n\n\nTo create a custom throttle, override \nBaseThrottle\n and implement \n.allow_request(self, request, view)\n. The method should return \nTrue\n if the request should be allowed, and \nFalse\n otherwise.\n\n\nOptionally you may also override the \n.wait()\n method. If implemented, \n.wait()\n should return a recommended number of seconds to wait before attempting the next request, or \nNone\n. The \n.wait()\n method will only be called if \n.allow_request()\n has previously returned \nFalse\n.\n\n\nIf the \n.wait()\n method is implemented and the request is throttled, then a \nRetry-After\n header will be included in the response.\n\n\nExample\n\n\nThe following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.\n\n\nimport random\n\nclass RandomRateThrottle(throttling.BaseThrottle):\n def allow_request(self, request, view):\n return random.randint(1, 10) != 1", @@ -2712,7 +2697,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\u2014 \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.+)/$', 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': ('django_filters.rest_framework.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\nimport django_filters.rest_framework\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (django_filters.rest_framework.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&max_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 \ndjango-filter\n library includes a \nDjangoFilterBackend\n class which\nsupports highly customizable field filtering for REST framework.\n\n\nTo use \nDjangoFilterBackend\n, first install \ndjango-filter\n. Then add \ndjango_filters\n to Django's \nINSTALLED_APPS\n\n\npip install django-filter\n\n\n\nYou should now either add the filter backend to your settings:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)\n}\n\n\n\nOr add the filter backend to an individual View or ViewSet.\n\n\nfrom django_filters.rest_framework import DjangoFilterBackend\n\nclass UserListView(generics.ListAPIView):\n ...\n filter_backends = (DjangoFilterBackend,)\n\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 = (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&in_stock=True\n\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view.\nYou can read more about \nFilterSet\ns in the \ndjango-filter documentation\n.\nIt's also recommended that you read the section on \nDRF integration\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\nfrom rest_framework import filters\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 & 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. This method should have the following signature:\n\n\nget_schema_fields(self, view)\n\n\nThe method 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.", + "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\u2014 \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.+)/$', 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': ('django_filters.rest_framework.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\nimport django_filters.rest_framework\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (django_filters.rest_framework.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&max_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 \ndjango-filter\n library includes a \nDjangoFilterBackend\n class which\nsupports highly customizable field filtering for REST framework.\n\n\nTo use \nDjangoFilterBackend\n, first install \ndjango-filter\n. Then add \ndjango_filters\n to Django's \nINSTALLED_APPS\n\n\npip install django-filter\n\n\n\nYou should now either add the filter backend to your settings:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)\n}\n\n\n\nOr add the filter backend to an individual View or ViewSet.\n\n\nfrom django_filters.rest_framework import DjangoFilterBackend\n\nclass UserListView(generics.ListAPIView):\n ...\n filter_backends = (DjangoFilterBackend,)\n\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 = (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&in_stock=True\n\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view.\nYou can read more about \nFilterSet\ns in the \ndjango-filter documentation\n.\nIt's also recommended that you read the section on \nDRF integration\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 & 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. This method should have the following signature:\n\n\nget_schema_fields(self, view)\n\n\nThe method 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" }, { @@ -2767,7 +2752,7 @@ }, { "location": "/api-guide/filtering/#searchfilter", - "text": "The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality . When in use, the browsable API will include a SearchFilter control: The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField . from rest_framework import filters\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email') This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ('username', 'email', 'profile__profession') By 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. The search behavior may be restricted by prepending various characters to the search_fields . '^' Starts-with search. '=' Exact matches. '@' Full-text search. (Currently only supported Django's MySQL backend.) '$' Regex search. For example: search_fields = ('=username', '=email') By default, the search parameter is named 'search ', but this may be overridden with the SEARCH_PARAM setting. For more details, see the Django documentation .", + "text": "The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality . When in use, the browsable API will include a SearchFilter control: The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField . class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email') This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ('username', 'email', 'profile__profession') By 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. The search behavior may be restricted by prepending various characters to the search_fields . '^' Starts-with search. '=' Exact matches. '@' Full-text search. (Currently only supported Django's MySQL backend.) '$' Regex search. For example: search_fields = ('=username', '=email') By default, the search parameter is named 'search ', but this may be overridden with the SEARCH_PARAM setting. For more details, see the Django documentation .", "title": "SearchFilter" }, { @@ -3122,7 +3107,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\u2014 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\nInstall Core API\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\nInternal schema representation\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\nAlternate schema formats\n\n\nOther schema formats such as \nOpen API\n (\"Swagger\"),\n\nJSON HyperSchema\n, or \nAPI Blueprint\n can also\nbe supported by implementing a custom renderer class that handles converting a\n\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\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\nCreating a schema\n\n\nREST framework includes functionality for auto-generating a schema,\nor allows you to specify one explicitly.\n\n\nManual Schema Specification\n\n\nTo manually specify a schema you create a Core API \nDocument\n, similar to the\nexample above.\n\n\nschema = coreapi.Document(\n title='Flight Search API',\n content={\n ...\n }\n)\n\n\n\nAutomatic Schema Generation\n\n\nAutomatic schema generation is provided by the \nSchemaGenerator\n class.\n\n\nSchemaGenerator\n processes a list of routed URL pattterns and compiles the\nappropriately structured Core API Document.\n\n\nBasic usage is just to provide the title for your schema and call\n\nget_schema()\n:\n\n\ngenerator = schemas.SchemaGenerator(title='Flight Search API')\nschema = generator.get_schema()\n\n\n\nPer-View Schema Customisation\n\n\nBy default, view introspection is performed by an \nAutoSchema\n instance\naccessible via the \nschema\n attribute on \nAPIView\n. This provides the\nappropriate Core API \nLink\n object for the view, request method and path:\n\n\nauto_schema = view.schema\ncoreapi_link = auto_schema.get_link(...)\n\n\n\n(In compiling the schema, \nSchemaGenerator\n calls \nview.schema.get_link()\n for\neach view, allowed method and path.)\n\n\n\n\nNote\n: For basic \nAPIView\n subclasses, default introspection is essentially\nlimited to the URL kwarg path parameters. For \nGenericAPIView\n\nsubclasses, which includes all the provided class based views, \nAutoSchema\n will\nattempt to introspect serialiser, pagination and filter fields, as well as\nprovide richer path field descriptions. (The key hooks here are the relevant\n\nGenericAPIView\n attributes and methods: \nget_serializer\n, \npagination_class\n,\n\nfilter_backends\n and so on.)\n\n\n\n\nTo customise the \nLink\n generation you may:\n\n\n\n\n\n\nInstantiate \nAutoSchema\n on your view with the \nmanual_fields\n kwarg:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n ...\n schema = AutoSchema(\n manual_fields=[\n coreapi.Field(\"extra_field\", ...),\n ]\n )\n\n\n\nThis allows extension for the most common case without subclassing.\n\n\n\n\n\n\nProvide an \nAutoSchema\n subclass with more complex customisation:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomSchema(AutoSchema):\n def get_link(...):\n # Implement custom introspection here (or in other sub-methods)\n\nclass CustomView(APIView):\n ...\n schema = CustomSchema()\n\n\n\nThis provides complete control over view introspection.\n\n\n\n\n\n\nInstantiate \nManualSchema\n on your view, providing the Core API \nFields\n for\n the view explicitly:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import ManualSchema\n\nclass CustomView(APIView):\n ...\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ])\n\n\n\nThis allows manually specifying the schema for some views whilst maintaining\nautomatic generation elsewhere.\n\n\n\n\n\n\nYou may disable schema generation for a view by setting \nschema\n to \nNone\n:\n\n\n class CustomView(APIView):\n ...\n schema = None # Will not appear in schema\n\n\n\nThis also applies to extra actions for \nViewSet\ns:\n\n\n class CustomViewSet(viewsets.ModelViewSet):\n\n @action(detail=True, schema=None)\n def extra_action(self, request, pk=None):\n ...\n\n\n\n\n\nNote\n: For full details on \nSchemaGenerator\n plus the \nAutoSchema\n and\n\nManualSchema\n descriptors see the \nAPI Reference below\n.\n\n\n\n\nAdding a schema view\n\n\nThere are a few different ways to add a schema view to your API, depending on\nexactly 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\nfrom rest_framework.schemas import get_schema_view\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/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\nurlconf\n\n\nA string representing the import path to the URL conf that you want\nto generate an API schema for. This defaults to the value of Django's\nROOT_URLCONF setting.\n\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n urlconf='myproject.urls'\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.schemas import get_schema_view\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\npatterns\n\n\nList of url patterns to limit the schema introspection to. If you only want the \nmyproject.api\n urls\nto be exposed in the schema:\n\n\nschema_url_patterns = [\n url(r'^api/', include('myproject.api.urls')),\n]\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n patterns=schema_url_patterns,\n)\n\n\n\ngenerator_class\n\n\nMay be used to specify a \nSchemaGenerator\n subclass to be passed to the\n\nSchemaView\n.\n\n\nauthentication_classes\n\n\nMay be used to specify the list of authentication classes that will apply to the schema endpoint.\nDefaults to \nsettings.DEFAULT_AUTHENTICATION_CLASSES\n\n\npermission_classes\n\n\nMay be used to specify the list of permission classes that will apply to the schema endpoint.\nDefaults to \nsettings.DEFAULT_PERMISSION_CLASSES\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: List all the users.\n post: Create a new user.\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\nAPI Reference\n\n\nSchemaGenerator\n\n\nA class that walks a list of routed URL patterns, requests the schema for each view,\nand collates the resulting CoreAPI Document.\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 \nrequired\n - The name of the API.\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(self, request)\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\nThe \nrequest\n argument is optional, and may be used if you want to apply per-user\npermissions to the resulting schema generation.\n\n\nget_links(self, request)\n\n\nReturn a nested dictionary containing all the links that should be included in the API schema.\n\n\nThis is a good point to override if you want to modify the resulting structure of the generated schema,\nas you can build a new dictionary with a different layout.\n\n\nAutoSchema\n\n\nA class that deals with introspection of individual views for schema generation.\n\n\nAutoSchema\n is attached to \nAPIView\n via the \nschema\n attribute.\n\n\nThe \nAutoSchema\n constructor takes a single keyword argument \nmanual_fields\n.\n\n\nmanual_fields\n: a \nlist\n of \ncoreapi.Field\n instances that will be added to\nthe generated fields. Generated fields with a matching \nname\n will be overwritten.\n\n\nclass CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field(\n \"my_extra_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ])\n\n\n\nFor more advanced customisation subclass \nAutoSchema\n to customise schema generation.\n\n\nclass CustomViewSchema(AutoSchema):\n \"\"\"\n Overrides `get_link()` to provide Custom Behavior X\n \"\"\"\n\n def get_link(self, path, method, base_url):\n link = super().get_link(path, method, base_url)\n # Do something to customize link here...\n return link\n\nclass MyView(APIView):\n schema = CustomViewSchema()\n\n\n\nThe following methods are available to override.\n\n\nget_link(self, path, method, base_url)\n\n\nReturns a \ncoreapi.Link\n instance corresponding to the given view.\n\n\nThis is the main entry point.\nYou can override this if you need to provide custom behaviors for particular views.\n\n\nget_description(self, path, method)\n\n\nReturns a string to use as the link description. By default this is based on the\nview docstring as described in the \"Schemas as Documentation\" section above.\n\n\nget_encoding(self, path, method)\n\n\nReturns a string to indicate the encoding for any request body, when interacting\nwith the given view. Eg. \n'application/json'\n. May return a blank string for views\nthat do not expect a request body.\n\n\nget_path_fields(self, path, method):\n\n\nReturn a list of \ncoreapi.Field()\n instances. One for each path parameter in the URL.\n\n\nget_serializer_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Field()\n instances. One for each field in the serializer class used by the view.\n\n\nget_pagination_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Field()\n instances, as returned by the \nget_schema_fields()\n method on any pagination class used by the view.\n\n\nget_filter_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Field()\n instances, as returned by the \nget_schema_fields()\n method of any filter classes used by the view.\n\n\nget_manual_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Field()\n instances to be added to or replace generated fields. Defaults to (optional) \nmanual_fields\n passed to \nAutoSchema\n constructor.\n\n\nMay be overridden to customise manual fields by \npath\n or \nmethod\n. For example, a per-method adjustment may look like this:\n\n\ndef get_manual_fields(self, path, method):\n \"\"\"Example adding per-method fields.\"\"\"\n\n extra_fields = []\n if method=='GET':\n extra_fields = # ... list of extra fields for GET ...\n if method=='POST':\n extra_fields = # ... list of extra fields for POST ...\n\n manual_fields = super().get_manual_fields(path, method)\n return manual_fields + extra_fields\n\n\n\n\nupdate_fields(fields, update_with)\n\n\nUtility \nstaticmethod\n. Encapsulates logic to add or replace fields from a list\nby \nField.name\n. May be overridden to adjust replacement criteria.\n\n\nManualSchema\n\n\nAllows manually providing a list of \ncoreapi.Field\n instances for the schema,\nplus an optional description.\n\n\nclass MyView(APIView):\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ]\n )\n\n\n\nThe \nManualSchema\n constructor takes two arguments:\n\n\nfields\n: A list of \ncoreapi.Field\n instances. Required.\n\n\ndescription\n: A string description. Optional.\n\n\nencoding\n: Default \nNone\n. A string encoding, e.g \napplication/json\n. Optional.\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.\n\n\n\n\nThird party packages\n\n\ndrf-yasg - Yet Another Swagger Generator\n\n\ndrf-yasg\n generates \nOpenAPI\n documents suitable for code generation - nested schemas, \nnamed models, response bodies, enum/pattern/min/max validators, form parameters, etc.\n\n\nDRF OpenAPI\n\n\nDRF OpenAPI\n renders the schema generated by Django Rest Framework\nin \nOpenAPI\n format.", + "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\u2014 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\nInstall Core API\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\nInternal schema representation\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\nAlternate schema formats\n\n\nOther schema formats such as \nOpen API\n (\"Swagger\"),\n\nJSON HyperSchema\n, or \nAPI Blueprint\n can also\nbe supported by implementing a custom renderer class that handles converting a\n\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\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\nCreating a schema\n\n\nREST framework includes functionality for auto-generating a schema,\nor allows you to specify one explicitly.\n\n\nManual Schema Specification\n\n\nTo manually specify a schema you create a Core API \nDocument\n, similar to the\nexample above.\n\n\nschema = coreapi.Document(\n title='Flight Search API',\n content={\n ...\n }\n)\n\n\n\nAutomatic Schema Generation\n\n\nAutomatic schema generation is provided by the \nSchemaGenerator\n class.\n\n\nSchemaGenerator\n processes a list of routed URL pattterns and compiles the\nappropriately structured Core API Document.\n\n\nBasic usage is just to provide the title for your schema and call\n\nget_schema()\n:\n\n\ngenerator = schemas.SchemaGenerator(title='Flight Search API')\nschema = generator.get_schema()\n\n\n\nPer-View Schema Customisation\n\n\nBy default, view introspection is performed by an \nAutoSchema\n instance\naccessible via the \nschema\n attribute on \nAPIView\n. This provides the\nappropriate Core API \nLink\n object for the view, request method and path:\n\n\nauto_schema = view.schema\ncoreapi_link = auto_schema.get_link(...)\n\n\n\n(In compiling the schema, \nSchemaGenerator\n calls \nview.schema.get_link()\n for\neach view, allowed method and path.)\n\n\n\n\nNote\n: For basic \nAPIView\n subclasses, default introspection is essentially\nlimited to the URL kwarg path parameters. For \nGenericAPIView\n\nsubclasses, which includes all the provided class based views, \nAutoSchema\n will\nattempt to introspect serialiser, pagination and filter fields, as well as\nprovide richer path field descriptions. (The key hooks here are the relevant\n\nGenericAPIView\n attributes and methods: \nget_serializer\n, \npagination_class\n,\n\nfilter_backends\n and so on.)\n\n\n\n\nTo customise the \nLink\n generation you may:\n\n\n\n\n\n\nInstantiate \nAutoSchema\n on your view with the \nmanual_fields\n kwarg:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n ...\n schema = AutoSchema(\n manual_fields=[\n coreapi.Field(\"extra_field\", ...),\n ]\n )\n\n\n\nThis allows extension for the most common case without subclassing.\n\n\n\n\n\n\nProvide an \nAutoSchema\n subclass with more complex customisation:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomSchema(AutoSchema):\n def get_link(...):\n # Implement custom introspection here (or in other sub-methods)\n\nclass CustomView(APIView):\n ...\n schema = CustomSchema()\n\n\n\nThis provides complete control over view introspection.\n\n\n\n\n\n\nInstantiate \nManualSchema\n on your view, providing the Core API \nFields\n for\n the view explicitly:\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import ManualSchema\n\nclass CustomView(APIView):\n ...\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ])\n\n\n\nThis allows manually specifying the schema for some views whilst maintaining\nautomatic generation elsewhere.\n\n\n\n\n\n\nYou may disable schema generation for a view by setting \nschema\n to \nNone\n:\n\n\n class CustomView(APIView):\n ...\n schema = None # Will not appear in schema\n\n\n\n\n\nNote\n: For full details on \nSchemaGenerator\n plus the \nAutoSchema\n and\n\nManualSchema\n descriptors see the \nAPI Reference below\n.\n\n\n\n\nAdding a schema view\n\n\nThere are a few different ways to add a schema view to your API, depending on\nexactly 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\nfrom rest_framework.schemas import get_schema_view\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/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\nurlconf\n\n\nA string representing the import path to the URL conf that you want\nto generate an API schema for. This defaults to the value of Django's\nROOT_URLCONF setting.\n\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n urlconf='myproject.urls'\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.schemas import get_schema_view\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\npatterns\n\n\nList of url patterns to limit the schema introspection to. If you only want the \nmyproject.api\n urls\nto be exposed in the schema:\n\n\nschema_url_patterns = [\n url(r'^api/', include('myproject.api.urls')),\n]\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n patterns=schema_url_patterns,\n)\n\n\n\ngenerator_class\n\n\nMay be used to specify a \nSchemaGenerator\n subclass to be passed to the\n\nSchemaView\n.\n\n\nauthentication_classes\n\n\nMay be used to specify the list of authentication classes that will apply to the schema endpoint.\nDefaults to \nsettings.DEFAULT_AUTHENTICATION_CLASSES\n\n\npermission_classes\n\n\nMay be used to specify the list of permission classes that will apply to the schema endpoint.\nDefaults to \nsettings.DEFAULT_PERMISSION_CLASSES\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: List all the users.\n post: Create a new user.\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\nAPI Reference\n\n\nSchemaGenerator\n\n\nA class that walks a list of routed URL patterns, requests the schema for each view,\nand collates the resulting CoreAPI Document.\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 \nrequired\n - The name of the API.\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(self, request)\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\nThe \nrequest\n argument is optional, and may be used if you want to apply per-user\npermissions to the resulting schema generation.\n\n\nget_links(self, request)\n\n\nReturn a nested dictionary containing all the links that should be included in the API schema.\n\n\nThis is a good point to override if you want to modify the resulting structure of the generated schema,\nas you can build a new dictionary with a different layout.\n\n\nAutoSchema\n\n\nA class that deals with introspection of individual views for schema generation.\n\n\nAutoSchema\n is attached to \nAPIView\n via the \nschema\n attribute.\n\n\nThe \nAutoSchema\n constructor takes a single keyword argument \nmanual_fields\n.\n\n\nmanual_fields\n: a \nlist\n of \ncoreapi.Field\n instances that will be added to\nthe generated fields. Generated fields with a matching \nname\n will be overwritten.\n\n\nclass CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field(\n \"my_extra_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ])\n\n\n\nFor more advanced customisation subclass \nAutoSchema\n to customise schema generation.\n\n\nclass CustomViewSchema(AutoSchema):\n \"\"\"\n Overrides `get_link()` to provide Custom Behavior X\n \"\"\"\n\n def get_link(self, path, method, base_url):\n link = super().get_link(path, method, base_url)\n # Do something to customize link here...\n return link\n\nclass MyView(APIView):\n schema = CustomViewSchema()\n\n\n\nThe following methods are available to override.\n\n\nget_link(self, path, method, base_url)\n\n\nReturns a \ncoreapi.Link\n instance corresponding to the given view.\n\n\nThis is the main entry point.\nYou can override this if you need to provide custom behaviors for particular views.\n\n\nget_description(self, path, method)\n\n\nReturns a string to use as the link description. By default this is based on the\nview docstring as described in the \"Schemas as Documentation\" section above.\n\n\nget_encoding(self, path, method)\n\n\nReturns a string to indicate the encoding for any request body, when interacting\nwith the given view. Eg. \n'application/json'\n. May return a blank string for views\nthat do not expect a request body.\n\n\nget_path_fields(self, path, method):\n\n\nReturn a list of \ncoreapi.Link()\n instances. One for each path parameter in the URL.\n\n\nget_serializer_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Link()\n instances. One for each field in the serializer class used by the view.\n\n\nget_pagination_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Link()\n instances, as returned by the \nget_schema_fields()\n method on any pagination class used by the view.\n\n\nget_filter_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Link()\n instances, as returned by the \nget_schema_fields()\n method of any filter classes used by the view.\n\n\nget_manual_fields(self, path, method)\n\n\nReturn a list of \ncoreapi.Field()\n instances to be added to or replace generated fields. Defaults to (optional) \nmanual_fields\n passed to \nAutoSchema\n constructor.\n\n\nMay be overridden to customise manual fields by \npath\n or \nmethod\n. For example, a per-method adjustment may look like this:\n\n\ndef get_manual_fields(self, path, method):\n \"\"\"Example adding per-method fields.\"\"\"\n\n extra_fields = []\n if method=='GET':\n extra_fields = # ... list of extra fields for GET ...\n if method=='POST':\n extra_fields = # ... list of extra fields for POST ...\n\n manual_fields = super().get_manual_fields(path, method)\n return manual_fields + extra_fields\n\n\n\n\nupdate_fields(fields, update_with)\n\n\nUtility \nstaticmethod\n. Encapsulates logic to add or replace fields from a list\nby \nField.name\n. May be overridden to adjust replacement criteria.\n\n\nManualSchema\n\n\nAllows manually providing a list of \ncoreapi.Field\n instances for the schema,\nplus an optional description.\n\n\nclass MyView(APIView):\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ]\n )\n\n\n\nThe \nManualSchema\n constructor takes two arguments:\n\n\nfields\n: A list of \ncoreapi.Field\n instances. Required.\n\n\ndescription\n: A string description. Optional.\n\n\nencoding\n: Default \nNone\n. A string encoding, e.g \napplication/json\n. Optional.\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.\n\n\n\n\nThird party packages\n\n\ndrf-yasg - Yet Another Swagger Generator\n\n\ndrf-yasg\n generates \nOpenAPI\n documents suitable for code generation - nested schemas, \nnamed models, response bodies, enum/pattern/min/max validators, form parameters, etc.\n\n\nDRF OpenAPI\n\n\nDRF OpenAPI\n renders the schema generated by Django Rest Framework\nin \nOpenAPI\n format.", "title": "Schemas" }, { @@ -3177,7 +3162,7 @@ }, { "location": "/api-guide/schemas/#per-view-schema-customisation", - "text": "By default, view introspection is performed by an AutoSchema instance\naccessible via the schema attribute on APIView . This provides the\nappropriate Core API Link object for the view, request method and path: auto_schema = view.schema\ncoreapi_link = auto_schema.get_link(...) (In compiling the schema, SchemaGenerator calls view.schema.get_link() for\neach view, allowed method and path.) Note : For basic APIView subclasses, default introspection is essentially\nlimited to the URL kwarg path parameters. For GenericAPIView \nsubclasses, which includes all the provided class based views, AutoSchema will\nattempt to introspect serialiser, pagination and filter fields, as well as\nprovide richer path field descriptions. (The key hooks here are the relevant GenericAPIView attributes and methods: get_serializer , pagination_class , filter_backends and so on.) To customise the Link generation you may: Instantiate AutoSchema on your view with the manual_fields kwarg: from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n ...\n schema = AutoSchema(\n manual_fields=[\n coreapi.Field(\"extra_field\", ...),\n ]\n ) This allows extension for the most common case without subclassing. Provide an AutoSchema subclass with more complex customisation: from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomSchema(AutoSchema):\n def get_link(...):\n # Implement custom introspection here (or in other sub-methods)\n\nclass CustomView(APIView):\n ...\n schema = CustomSchema() This provides complete control over view introspection. Instantiate ManualSchema on your view, providing the Core API Fields for\n the view explicitly: from rest_framework.views import APIView\nfrom rest_framework.schemas import ManualSchema\n\nclass CustomView(APIView):\n ...\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ]) This allows manually specifying the schema for some views whilst maintaining\nautomatic generation elsewhere. You may disable schema generation for a view by setting schema to None : class CustomView(APIView):\n ...\n schema = None # Will not appear in schema This also applies to extra actions for ViewSet s: class CustomViewSet(viewsets.ModelViewSet):\n\n @action(detail=True, schema=None)\n def extra_action(self, request, pk=None):\n ... Note : For full details on SchemaGenerator plus the AutoSchema and ManualSchema descriptors see the API Reference below .", + "text": "By default, view introspection is performed by an AutoSchema instance\naccessible via the schema attribute on APIView . This provides the\nappropriate Core API Link object for the view, request method and path: auto_schema = view.schema\ncoreapi_link = auto_schema.get_link(...) (In compiling the schema, SchemaGenerator calls view.schema.get_link() for\neach view, allowed method and path.) Note : For basic APIView subclasses, default introspection is essentially\nlimited to the URL kwarg path parameters. For GenericAPIView \nsubclasses, which includes all the provided class based views, AutoSchema will\nattempt to introspect serialiser, pagination and filter fields, as well as\nprovide richer path field descriptions. (The key hooks here are the relevant GenericAPIView attributes and methods: get_serializer , pagination_class , filter_backends and so on.) To customise the Link generation you may: Instantiate AutoSchema on your view with the manual_fields kwarg: from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n ...\n schema = AutoSchema(\n manual_fields=[\n coreapi.Field(\"extra_field\", ...),\n ]\n ) This allows extension for the most common case without subclassing. Provide an AutoSchema subclass with more complex customisation: from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomSchema(AutoSchema):\n def get_link(...):\n # Implement custom introspection here (or in other sub-methods)\n\nclass CustomView(APIView):\n ...\n schema = CustomSchema() This provides complete control over view introspection. Instantiate ManualSchema on your view, providing the Core API Fields for\n the view explicitly: from rest_framework.views import APIView\nfrom rest_framework.schemas import ManualSchema\n\nclass CustomView(APIView):\n ...\n schema = ManualSchema(fields=[\n coreapi.Field(\n \"first_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n coreapi.Field(\n \"second_field\",\n required=True,\n location=\"path\",\n schema=coreschema.String()\n ),\n ]) This allows manually specifying the schema for some views whilst maintaining\nautomatic generation elsewhere. You may disable schema generation for a view by setting schema to None : class CustomView(APIView):\n ...\n schema = None # Will not appear in schema Note : For full details on SchemaGenerator plus the AutoSchema and ManualSchema descriptors see the API Reference below .", "title": "Per-View Schema Customisation" }, { @@ -3297,22 +3282,22 @@ }, { "location": "/api-guide/schemas/#get_path_fieldsself-path-method", - "text": "Return a list of coreapi.Field() instances. One for each path parameter in the URL.", + "text": "Return a list of coreapi.Link() instances. One for each path parameter in the URL.", "title": "get_path_fields(self, path, method):" }, { "location": "/api-guide/schemas/#get_serializer_fieldsself-path-method", - "text": "Return a list of coreapi.Field() instances. One for each field in the serializer class used by the view.", + "text": "Return a list of coreapi.Link() instances. One for each field in the serializer class used by the view.", "title": "get_serializer_fields(self, path, method)" }, { "location": "/api-guide/schemas/#get_pagination_fieldsself-path-method", - "text": "Return a list of coreapi.Field() instances, as returned by the get_schema_fields() method on any pagination class used by the view.", + "text": "Return a list of coreapi.Link() instances, as returned by the get_schema_fields() method on any pagination class used by the view.", "title": "get_pagination_fields(self, path, method)" }, { "location": "/api-guide/schemas/#get_filter_fieldsself-path-method", - "text": "Return a list of coreapi.Field() instances, as returned by the get_schema_fields() method of any filter classes used by the view.", + "text": "Return a list of coreapi.Link() instances, as returned by the get_schema_fields() method of any filter classes used by the view.", "title": "get_filter_fields(self, path, method)" }, { @@ -3477,7 +3462,7 @@ }, { "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\u2014 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, the 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.get_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>>> print(exc.get_codes())\npermission_denied\n>>> print(exc.get_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>>> print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}\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\".\n\n\n\n\nGeneric Error Views\n\n\nDjango REST Framework provides two error views suitable for providing generic JSON \n500\n Server Error and\n\n400\n Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an\nAPI-only application.)\n\n\nUse these as per \nDjango's Customizing error views documentation\n.\n\n\nrest_framework.exceptions.server_error\n\n\nReturns a response with status code \n500\n and \napplication/json\n content type.\n\n\nSet as \nhandler500\n:\n\n\nhandler500 = 'rest_framework.exceptions.server_error'\n\n\n\nrest_framework.exceptions.bad_request\n\n\nReturns a response with status code \n400\n and \napplication/json\n content type.\n\n\nSet as \nhandler400\n:\n\n\nhandler400 = 'rest_framework.exceptions.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\u2014 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, the 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.get_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>>> print(exc.get_codes())\npermission_denied\n>>> print(exc.get_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>>> print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}\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\".\n\n\n\n\nGeneric Error Views\n\n\nDjango REST Framework provides two error views suitable for providing generic JSON \n500\n Server Error and\n\n400\n Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an\nAPI-only application.)\n\n\nUse these as per \nDjango's Customizing error views documentation\n.\n\n\nrest_framework.exceptions.server_error\n\n\nReturns a response with status code \n500\n and \napplication/json\n content type.\n\n\nSet as \nhandler500\n:\n\n\nhandler500 = 'rest_framework.exceptions.server_error'\n\n\n\nrest_framework.exceptions.server_error\n\n\nReturns a response with status code \n400\n and \napplication/json\n content type.\n\n\nSet as \nhandler400\n:\n\n\nhandler400 = 'rest_framework.exceptions.bad_request'", "title": "Exceptions" }, { @@ -3571,9 +3556,9 @@ "title": "rest_framework.exceptions.server_error" }, { - "location": "/api-guide/exceptions/#rest_frameworkexceptionsbad_request", + "location": "/api-guide/exceptions/#rest_frameworkexceptionsserver_error_1", "text": "Returns a response with status code 400 and application/json content type. Set as handler400 : handler400 = 'rest_framework.exceptions.bad_request'", - "title": "rest_framework.exceptions.bad_request" + "title": "rest_framework.exceptions.server_error" }, { "location": "/api-guide/status-codes/", @@ -3617,7 +3602,7 @@ }, { "location": "/api-guide/testing/", - "text": "Testing\n\n\n\n\nCode without tests is broken as designed.\n\n\n\u2014 \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.auth_token)\n\n\n\n\n\nNote\n: \nforce_authenticate\n directly sets \nrequest.user\n to the in-memory \nuser\n instance. If you are re-using the same \nuser\n instance across multiple tests that update the saved \nuser\n state, you may need to call \nrefresh_from_db()\n between tests.\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 entirely and 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. This may be useful if:\n\n\n\n\nYou are expecting to interface with the API primarily from another Python service,\nand want to test the service at the same level as the client will see.\n\n\nYou want to write tests in such a way that they can also be run against a staging or\nlive environment. (See \"Live tests\" below.)\n\n\n\n\nThis exposes exactly the same interface as if you were using a requests session\ndirectly.\n\n\nfrom rest_framework.test import RequestsClient\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n\n\n\nNote that the requests client requires you to pass fully qualified URLs.\n\n\nRequestsClient\n and working with the database\n\n\nThe \nRequestsClient\n class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.\n\n\nIf you're using \nRequestsClient\n you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that \nCustomer.objects.count() == 3\n you would list the customers endpoint, and ensure that it contains three records.\n\n\nHeaders & 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('http://testserver/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('http://testserver/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\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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 & 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\nAPI Test 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\nURLPatternsTestCase\n\n\nREST framework also provides a test case class for isolating \nurlpatterns\n on a per-class basis. Note that this inherits from Django's \nSimpleTestCase\n, and will most likely need to be mixed with another test case class.\n\n\nExample\n\n\nfrom django.urls import include, path, reverse\nfrom rest_framework.test import APITestCase, URLPatternsTestCase\n\n\nclass AccountTests(APITestCase, URLPatternsTestCase):\n urlpatterns = [\n path('api/', include('api.urls')),\n ]\n\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 1)\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\u2014 \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.auth_token)\n\n\n\n\n\nNote\n: \nforce_authenticate\n directly sets \nrequest.user\n to the in-memory \nuser\n instance. If you are re-using the same \nuser\n instance across multiple tests that update the saved \nuser\n state, you may need to call \nrefresh_from_db()\n between tests.\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 entirely and 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. This may be useful if:\n\n\n\n\nYou are expecting to interface with the API primarily from another Python service,\nand want to test the service at the same level as the client will see.\n\n\nYou want to write tests in such a way that they can also be run against a staging or\nlive environment. (See \"Live tests\" below.)\n\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/')\nassert response.status_code == 200\n\n\n\nNote that the requests client requires you to pass fully qualified URLs.\n\n\nRequestsClient\n and working with the database\n\n\nThe \nRequestsClient\n class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.\n\n\nIf you're using \nRequestsClient\n you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that \nCustomer.objects.count() == 3\n you would list the customers endpoint, and ensure that it contains three records.\n\n\nHeaders & 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\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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 & 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\nAPI Test 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\nURLPatternsTestCase\n\n\nREST framework also provides a test case class for isolating \nurlpatterns\n on a per-class basis. Note that this inherits from Django's \nSimpleTestCase\n, and will most likely need to be mixed with another test case class.\n\n\nExample\n\n\nfrom django.urls import include, path, reverse\nfrom rest_framework.test import APITestCase, URLPatternsTestCase\n\n\nclass AccountTests(APITestCase, URLPatternsTestCase):\n urlpatterns = [\n path('api/', include('api.urls')),\n ]\n\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 1)\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" }, { @@ -3697,7 +3682,7 @@ }, { "location": "/api-guide/testing/#requestsclient", - "text": "REST framework also includes a client for interacting with your application\nusing the popular Python library, requests . This may be useful if: You are expecting to interface with the API primarily from another Python service,\nand want to test the service at the same level as the client will see. You want to write tests in such a way that they can also be run against a staging or\nlive environment. (See \"Live tests\" below.) This exposes exactly the same interface as if you were using a requests session\ndirectly. from rest_framework.test import RequestsClient\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200 Note that the requests client requires you to pass fully qualified URLs.", + "text": "REST framework also includes a client for interacting with your application\nusing the popular Python library, requests . This may be useful if: You are expecting to interface with the API primarily from another Python service,\nand want to test the service at the same level as the client will see. You want to write tests in such a way that they can also be run against a staging or\nlive environment. (See \"Live tests\" below.) This exposes exactly the same interface as if you were using a requests session\ndirectly. client = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200 Note that the requests client requires you to pass fully qualified URLs.", "title": "RequestsClient" }, { @@ -3712,7 +3697,7 @@ }, { "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('http://testserver/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('http://testserver/organisations/', json={\n 'name': 'MegaCorp',\n 'status': 'active'\n}, headers={'X-CSRFToken': csrftoken})\nassert response.status_code == 200", + "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" }, { @@ -3782,7 +3767,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\u2014 \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\nDEFAULT_SCHEMA_CLASS\n\n\nA view inspector class that will be used for schema generation.\n\n\nDefault: \n'rest_framework.schemas.AutoSchema'\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 has been removed.\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(If removing authentication entirely, e.g. by removing \ndjango.contrib.auth\n from\n\nINSTALLED_APPS\n, set \nUNAUTHENTICATED_USER\n to \nNone\n.)\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, whereas \"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\nSTRICT_JSON\n\n\nWhen set to \nTrue\n, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (\nnan\n, \ninf\n, \n-inf\n) accepted by Python's \njson\n module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's \nJSON.Parse\n nor PostgreSQL's JSON data type accept these values.\n\n\nWhen set to \nFalse\n, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.\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(self)\n\n\n\n\n\nself\n: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing \nself.__class__.__name__\n.\n\n\n\n\nIf the view instance inherits \nViewSet\n, it may have been initialized with several optional arguments:\n\n\n\n\nname\n: A name expliticly provided to a view in the viewset. Typically, this value should be used as-is when provided.\n\n\nsuffix\n: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to \nname\n.\n\n\ndetail\n: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.\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(self, html=False)\n\n\n\n\n\nself\n: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing \nself.__class__.__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\nIf the view instance inherits \nViewSet\n, it may have been initialized with several optional arguments:\n\n\n\n\ndescription\n: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset \naction\ns, and should be used as-is.\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", + "text": "Settings\n\n\n\n\nNamespaces are one honking great idea - let's do more of those!\n\n\n\u2014 \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\nDEFAULT_SCHEMA_CLASS\n\n\nA view inspector class that will be used for schema generation.\n\n\nDefault: \n'rest_framework.schemas.AutoSchema'\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 has been removed.\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(If removing authentication entirely, e.g. by removing \ndjango.contrib.auth\n from\n\nINSTALLED_APPS\n, set \nUNAUTHENTICATED_USER\n to \nNone\n.)\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, whereas \"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\nSTRICT_JSON\n\n\nWhen set to \nTrue\n, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (\nnan\n, \ninf\n, \n-inf\n) accepted by Python's \njson\n module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's \nJSON.Parse\n nor PostgreSQL's JSON data type accept these values.\n\n\nWhen set to \nFalse\n, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.\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" }, { @@ -4032,12 +4017,12 @@ }, { "location": "/api-guide/settings/#view_name_function", - "text": "A string representing the function that should be used when generating view names. This should be a function with the following signature: view_name(self) self : The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing self.__class__.__name__ . If the view instance inherits ViewSet , it may have been initialized with several optional arguments: name : A name expliticly provided to a view in the viewset. Typically, this value should be used as-is when provided. suffix : Text used when differentiating individual views in a viewset. This argument is mutually exclusive to name . detail : Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view. Default: 'rest_framework.views.get_view_name'", + "text": "A string representing the function that should be used when generating view names. This should be a function with the following signature: view_name(cls, suffix=None) cls : The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing cls.__name__ . suffix : The optional suffix used when differentiating individual views in a viewset. Default: 'rest_framework.views.get_view_name'", "title": "VIEW_NAME_FUNCTION" }, { "location": "/api-guide/settings/#view_description_function", - "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(self, html=False) self : The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing self.__class__.__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. If the view instance inherits ViewSet , it may have been initialized with several optional arguments: description : A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset action s, and should be used as-is. Default: 'rest_framework.views.get_view_description'", + "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" }, { @@ -4192,7 +4177,7 @@ }, { "location": "/topics/api-clients/", - "text": "API Clients\n\n\nAn API client handles the underlying details of how network requests are made\nand how responses are decoded. They present the developer with an application\ninterface to work against, rather than working directly with the network interface.\n\n\nThe API clients documented here are not restricted to APIs built with Django REST framework.\n They can be used with any API that exposes a supported schema format.\n\n\nFor example, \nthe Heroku platform API\n exposes a schema in the JSON\nHyperschema format. As a result, the Core API command line client and Python\nclient library can be \nused to interact with the Heroku API\n.\n\n\nClient-side Core API\n\n\nCore API\n is a document specification that can be used to describe APIs. It can\nbe used either server-side, as is done with REST framework's \nschema generation\n,\nor used client-side, as described here.\n\n\nWhen used client-side, Core API allows for \ndynamically driven client libraries\n\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nUsing a dynamically driven client has a number of advantages over interacting\nwith an API by building HTTP requests directly.\n\n\nMore meaningful interaction\n\n\nAPI interactions are presented in a more meaningful way. You're working at\nthe application interface layer, rather than the network interface layer.\n\n\nResilience & evolvability\n\n\nThe client determines what endpoints are available, what parameters exist\nagainst each particular endpoint, and how HTTP requests are formed.\n\n\nThis also allows for a degree of API evolvability. URLs can be modified\nwithout breaking existing clients, or more efficient encodings can be used\non-the-wire, with clients transparently upgrading.\n\n\nSelf-descriptive APIs\n\n\nA dynamically driven client is able to present documentation on the API to the\nend user. This documentation allows the user to discover the available endpoints\nand parameters, and better understand the API they are working with.\n\n\nBecause this documentation is driven by the API schema it will always be fully\nup to date with the most recently deployed version of the service.\n\n\n\n\nCommand line client\n\n\nThe command line client allows you to inspect and interact with any API that\nexposes a supported schema format.\n\n\nGetting started\n\n\nTo install the Core API command line client, use \npip\n.\n\n\nNote that the command-line client is a separate package to the\npython client library. Make sure to install \ncoreapi-cli\n.\n\n\n$ pip install coreapi-cli\n\n\n\nTo start inspecting and interacting with an API the schema must first be loaded\nfrom the network.\n\n\n$ coreapi get http://api.example.org/\n\nsnippets: {\n create(code, [title], [linenos], [language], [style])\n destroy(pk)\n highlight(pk)\n list([page])\n partial_update(pk, [title], [code], [linenos], [language], [style])\n retrieve(pk)\n update(pk, code, [title], [linenos], [language], [style])\n}\nusers: {\n list([page])\n retrieve(pk)\n}\n\n\n\nThis will then load the schema, displaying the resulting \nDocument\n. This\n\nDocument\n includes all the available interactions that may be made against the API.\n\n\nTo interact with the API, use the \naction\n command. This command requires a list\nof keys that are used to index into the link.\n\n\n$ coreapi action users list\n[\n {\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"id\": 2,\n \"username\": \"aziz\",\n \"snippets\": []\n },\n ...\n]\n\n\n\nTo inspect the underlying HTTP request and response, use the \n--debug\n flag.\n\n\n$ coreapi action users list --debug\n> GET /users/ HTTP/1.1\n> Accept: application/vnd.coreapi+json, */*\n> Authorization: Basic bWF4Om1heA==\n> Host: 127.0.0.1\n> User-Agent: coreapi\n< 200 OK\n< Allow: GET, HEAD, OPTIONS\n< Content-Type: application/json\n< Date: Thu, 30 Jun 2016 10:51:46 GMT\n< Server: WSGIServer/0.1 Python/2.7.10\n< Vary: Accept, Cookie\n<\n< [{\"url\":\"http://127.0.0.1/users/2/\",\"id\":2,\"username\":\"aziz\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/3/\",\"id\":3,\"username\":\"amy\",\"snippets\":[\"http://127.0.0.1/snippets/3/\"]},{\"url\":\"http://127.0.0.1/users/4/\",\"id\":4,\"username\":\"max\",\"snippets\":[\"http://127.0.0.1/snippets/4/\",\"http://127.0.0.1/snippets/5/\",\"http://127.0.0.1/snippets/6/\",\"http://127.0.0.1/snippets/7/\"]},{\"url\":\"http://127.0.0.1/users/5/\",\"id\":5,\"username\":\"jose\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/6/\",\"id\":6,\"username\":\"admin\",\"snippets\":[\"http://127.0.0.1/snippets/1/\",\"http://127.0.0.1/snippets/2/\"]}]\n\n[\n ...\n]\n\n\n\nSome actions may include optional or required parameters.\n\n\n$ coreapi action users create --param username=example\n\n\n\nWhen using \n--param\n, the type of the input will be determined automatically.\n\n\nIf you want to be more explicit about the parameter type then use \n--data\n for\nany null, numeric, boolean, list, or object inputs, and use \n--string\n for string inputs.\n\n\n$ coreapi action users edit --string username=tomchristie --data is_admin=true\n\n\n\nAuthentication & headers\n\n\nThe \ncredentials\n command is used to manage the request \nAuthentication:\n header.\nAny credentials added are always linked to a particular domain, so as to ensure\nthat credentials are not leaked across differing APIs.\n\n\nThe format for adding a new credential is:\n\n\n$ coreapi credentials add \n\n\n\nFor instance:\n\n\n$ coreapi credentials add api.example.org \"Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\"\n\n\n\nThe optional \n--auth\n flag also allows you to add specific types of authentication,\nhandling the encoding for you. Currently only \n\"basic\"\n is supported as an option here.\nFor example:\n\n\n$ coreapi credentials add api.example.org tomchristie:foobar --auth basic\n\n\n\nYou can also add specific request headers, using the \nheaders\n command:\n\n\n$ coreapi headers add api.example.org x-api-version 2\n\n\n\nFor more information and a listing of the available subcommands use \ncoreapi\ncredentials --help\n or \ncoreapi headers --help\n.\n\n\nCodecs\n\n\nBy default the command line client only includes support for reading Core JSON\nschemas, however it includes a plugin system for installing additional codecs.\n\n\n$ pip install openapi-codec jsonhyperschema-codec hal-codec\n$ coreapi codecs show\nCodecs\ncorejson application/vnd.coreapi+json encoding, decoding\nhal application/hal+json encoding, decoding\nopenapi application/openapi+json encoding, decoding\njsonhyperschema application/schema+json decoding\njson application/json data\ntext text/* data\n\n\n\nUtilities\n\n\nThe command line client includes functionality for bookmarking API URLs\nunder a memorable name. For example, you can add a bookmark for the\nexisting API, like so...\n\n\n$ coreapi bookmarks add accountmanagement\n\n\n\nThere is also functionality for navigating forward or backward through the\nhistory of which API URLs have been accessed.\n\n\n$ coreapi history show\n$ coreapi history back\n\n\n\nFor more information and a listing of the available subcommands use\n\ncoreapi bookmarks --help\n or \ncoreapi history --help\n.\n\n\nOther commands\n\n\nTo display the current \nDocument\n:\n\n\n$ coreapi show\n\n\n\nTo reload the current \nDocument\n from the network:\n\n\n$ coreapi reload\n\n\n\nTo load a schema file from disk:\n\n\n$ coreapi load my-api-schema.json --format corejson\n\n\n\nTo dump the current document to console in a given format:\n\n\n$ coreapi dump --format openapi\n\n\n\nTo remove the current document, along with all currently saved history,\ncredentials, headers and bookmarks:\n\n\n$ coreapi clear\n\n\n\n\n\nPython client library\n\n\nThe \ncoreapi\n Python package allows you to programmatically interact with any\nAPI that exposes a supported schema format.\n\n\nGetting started\n\n\nYou'll need to install the \ncoreapi\n package using \npip\n before you can get\nstarted.\n\n\n$ pip install coreapi\n\n\n\nIn order to start working with an API, we first need a \nClient\n instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour.\n\n\nimport coreapi\nclient = coreapi.Client()\n\n\n\nOnce we have a \nClient\n instance, we can fetch an API schema from the network.\n\n\nschema = client.get('https://api.example.org/')\n\n\n\nThe object returned from this call will be a \nDocument\n instance, which is\na representation of the API schema.\n\n\nAuthentication\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=''\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\nclient = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'create']\nparams = {\"username\": \"example\", \"password\": \"secret\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nauth = coreapi.auth.BasicAuthentication(\n username='',\n password=''\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nInteracting with the API\n\n\nNow that we have a client and have fetched our schema \nDocument\n, we can now\nstart to interact with the API:\n\n\nusers = client.action(schema, ['users', 'list'])\n\n\n\nSome endpoints may include named parameters, which might be either optional or required:\n\n\nnew_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})\n\n\n\nCodecs\n\n\nCodecs are responsible for encoding or decoding Documents.\n\n\nThe decoding process is used by a client to take a bytestring of an API schema\ndefinition, and returning the Core API \nDocument\n that represents that interface.\n\n\nA codec should be associated with a particular media type, such as \n'application/coreapi+json'\n.\n\n\nThis media type is used by the server in the response \nContent-Type\n header,\nin order to indicate what kind of data is being returned in the response.\n\n\nConfiguring codecs\n\n\nThe codecs that are available can be configured when instantiating a client.\nThe keyword argument used here is \ndecoders\n, because in the context of a\nclient the codecs are only for \ndecoding\n responses.\n\n\nIn the following example we'll configure a client to only accept \nCore JSON\n\nand \nJSON\n responses. This will allow us to receive and decode a Core JSON schema,\nand subsequently to receive JSON responses made against the API.\n\n\nfrom coreapi import codecs, Client\n\ndecoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]\nclient = Client(decoders=decoders)\n\n\n\nLoading and saving schemas\n\n\nYou can use a codec directly, in order to load an existing schema definition,\nand return the resulting \nDocument\n.\n\n\ninput_file = open('my-api-schema.json', 'rb')\nschema_definition = input_file.read()\ncodec = codecs.CoreJSONCodec()\nschema = codec.load(schema_definition)\n\n\n\nYou can also use a codec directly to generate a schema definition given a \nDocument\n instance:\n\n\nschema_definition = codec.dump(schema)\noutput_file = open('my-api-schema.json', 'rb')\noutput_file.write(schema_definition)\n\n\n\nTransports\n\n\nTransports are responsible for making network requests. The set of transports\nthat a client has installed determines which network protocols it is able to\nsupport.\n\n\nCurrently the \ncoreapi\n library only includes an HTTP/HTTPS transport, but\nother protocols can also be supported.\n\n\nConfiguring transports\n\n\nThe behavior of the network layer can be customized by configuring the\ntransports that the client is instantiated with.\n\n\nimport requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports)\n\n\n\nMore complex customizations can also be achieved, for example modifying the\nunderlying \nrequests.Session\n instance to \nattach transport adaptors\n\nthat modify the outgoing requests.\n\n\n\n\nJavaScript Client Library\n\n\nThe JavaScript client library allows you to interact with your API either from a browser, or using node.\n\n\nInstalling the JavaScript client\n\n\nThere are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static \ncoreapi.js\n file, which contains the code for the dynamic client library, and a templated \nschema.js\n resource, which exposes your API schema.\n\n\nFirst, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API service'))\n]\n\n\n\nOnce the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.\n\n\n\n{% load static %}\n\n\n\n\n\nThe \ncoreapi\n library, and the \nschema\n object will now both be available on the \nwindow\n instance.\n\n\nconst coreapi = window.coreapi\nconst schema = window.schema\n\n\n\nInstantiating a client\n\n\nIn order to interact with the API you'll need a client instance.\n\n\nvar client = new coreapi.Client()\n\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nSession authentication\n\n\nThe \nSessionAuthentication\n class allows session cookies to provide the user\nauthentication. You'll want to provide a standard HTML login flow, to allow\nthe user to login, and then instantiate a client using session authentication:\n\n\nlet auth = new coreapi.auth.SessionAuthentication({\n csrfCookieName: 'csrftoken',\n csrfHeaderName: 'X-CSRFToken'\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nThe authentication scheme will handle including a CSRF header in any outgoing\nrequests for unsafe HTTP methods.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nlet auth = new coreapi.auth.TokenAuthentication({\n scheme: 'JWT'\n token: ''\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\n// Setup some globally accessible state\nwindow.client = new coreapi.Client()\nwindow.loggedIn = false\n\nfunction loginUser(username, password) {\n let action = [\"api-token-auth\", \"obtain-token\"]\n let params = {username: \"example\", email: \"example@example.com\"}\n client.action(schema, action, params).then(function(result) {\n // On success, instantiate an authenticated client.\n let auth = window.coreapi.auth.TokenAuthentication({\n scheme: 'JWT',\n token: result['token']\n })\n window.client = coreapi.Client({auth: auth})\n window.loggedIn = true\n }).catch(function (error) {\n // Handle error case where eg. user provides incorrect credentials.\n })\n}\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nlet auth = new coreapi.auth.BasicAuthentication({\n username: '',\n password: ''\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nUsing the client\n\n\nMaking requests:\n\n\nlet action = [\"users\", \"list\"]\nclient.action(schema, action).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nIncluding parameters:\n\n\nlet action = [\"users\", \"create\"]\nlet params = {username: \"example\", email: \"example@example.com\"}\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nHandling errors:\n\n\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n}).catch(function (error) {\n // Error value is in 'error'\n})\n\n\n\nInstallation with node\n\n\nThe coreapi package is available on NPM.\n\n\n$ npm install coreapi\n$ node\nconst coreapi = require('coreapi')\n\n\n\nYou'll either want to include the API schema in your codebase directly, by copying it from the \nschema.js\n resource, or else load the schema asynchronously. For example:\n\n\nlet client = new coreapi.Client()\nlet schema = null\nclient.get(\"https://api.example.org/\").then(function(data) {\n // Load a CoreJSON API schema.\n schema = data\n console.log('schema loaded')\n})", + "text": "API Clients\n\n\nAn API client handles the underlying details of how network requests are made\nand how responses are decoded. They present the developer with an application\ninterface to work against, rather than working directly with the network interface.\n\n\nThe API clients documented here are not restricted to APIs built with Django REST framework.\n They can be used with any API that exposes a supported schema format.\n\n\nFor example, \nthe Heroku platform API\n exposes a schema in the JSON\nHyperschema format. As a result, the Core API command line client and Python\nclient library can be \nused to interact with the Heroku API\n.\n\n\nClient-side Core API\n\n\nCore API\n is a document specification that can be used to describe APIs. It can\nbe used either server-side, as is done with REST framework's \nschema generation\n,\nor used client-side, as described here.\n\n\nWhen used client-side, Core API allows for \ndynamically driven client libraries\n\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nUsing a dynamically driven client has a number of advantages over interacting\nwith an API by building HTTP requests directly.\n\n\nMore meaningful interaction\n\n\nAPI interactions are presented in a more meaningful way. You're working at\nthe application interface layer, rather than the network interface layer.\n\n\nResilience & evolvability\n\n\nThe client determines what endpoints are available, what parameters exist\nagainst each particular endpoint, and how HTTP requests are formed.\n\n\nThis also allows for a degree of API evolvability. URLs can be modified\nwithout breaking existing clients, or more efficient encodings can be used\non-the-wire, with clients transparently upgrading.\n\n\nSelf-descriptive APIs\n\n\nA dynamically driven client is able to present documentation on the API to the\nend user. This documentation allows the user to discover the available endpoints\nand parameters, and better understand the API they are working with.\n\n\nBecause this documentation is driven by the API schema it will always be fully\nup to date with the most recently deployed version of the service.\n\n\n\n\nCommand line client\n\n\nThe command line client allows you to inspect and interact with any API that\nexposes a supported schema format.\n\n\nGetting started\n\n\nTo install the Core API command line client, use \npip\n.\n\n\nNote that the command-line client is a separate package to the\npython client library. Make sure to install \ncoreapi-cli\n.\n\n\n$ pip install coreapi-cli\n\n\n\nTo start inspecting and interacting with an API the schema must first be loaded\nfrom the network.\n\n\n$ coreapi get http://api.example.org/\n\nsnippets: {\n create(code, [title], [linenos], [language], [style])\n destroy(pk)\n highlight(pk)\n list([page])\n partial_update(pk, [title], [code], [linenos], [language], [style])\n retrieve(pk)\n update(pk, code, [title], [linenos], [language], [style])\n}\nusers: {\n list([page])\n retrieve(pk)\n}\n\n\n\nThis will then load the schema, displaying the resulting \nDocument\n. This\n\nDocument\n includes all the available interactions that may be made against the API.\n\n\nTo interact with the API, use the \naction\n command. This command requires a list\nof keys that are used to index into the link.\n\n\n$ coreapi action users list\n[\n {\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"id\": 2,\n \"username\": \"aziz\",\n \"snippets\": []\n },\n ...\n]\n\n\n\nTo inspect the underlying HTTP request and response, use the \n--debug\n flag.\n\n\n$ coreapi action users list --debug\n> GET /users/ HTTP/1.1\n> Accept: application/vnd.coreapi+json, */*\n> Authorization: Basic bWF4Om1heA==\n> Host: 127.0.0.1\n> User-Agent: coreapi\n< 200 OK\n< Allow: GET, HEAD, OPTIONS\n< Content-Type: application/json\n< Date: Thu, 30 Jun 2016 10:51:46 GMT\n< Server: WSGIServer/0.1 Python/2.7.10\n< Vary: Accept, Cookie\n<\n< [{\"url\":\"http://127.0.0.1/users/2/\",\"id\":2,\"username\":\"aziz\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/3/\",\"id\":3,\"username\":\"amy\",\"snippets\":[\"http://127.0.0.1/snippets/3/\"]},{\"url\":\"http://127.0.0.1/users/4/\",\"id\":4,\"username\":\"max\",\"snippets\":[\"http://127.0.0.1/snippets/4/\",\"http://127.0.0.1/snippets/5/\",\"http://127.0.0.1/snippets/6/\",\"http://127.0.0.1/snippets/7/\"]},{\"url\":\"http://127.0.0.1/users/5/\",\"id\":5,\"username\":\"jose\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/6/\",\"id\":6,\"username\":\"admin\",\"snippets\":[\"http://127.0.0.1/snippets/1/\",\"http://127.0.0.1/snippets/2/\"]}]\n\n[\n ...\n]\n\n\n\nSome actions may include optional or required parameters.\n\n\n$ coreapi action users create --param username=example\n\n\n\nWhen using \n--param\n, the type of the input will be determined automatically.\n\n\nIf you want to be more explicit about the parameter type then use \n--data\n for\nany null, numeric, boolean, list, or object inputs, and use \n--string\n for string inputs.\n\n\n$ coreapi action users edit --string username=tomchristie --data is_admin=true\n\n\n\nAuthentication & headers\n\n\nThe \ncredentials\n command is used to manage the request \nAuthentication:\n header.\nAny credentials added are always linked to a particular domain, so as to ensure\nthat credentials are not leaked across differing APIs.\n\n\nThe format for adding a new credential is:\n\n\n$ coreapi credentials add \n\n\n\nFor instance:\n\n\n$ coreapi credentials add api.example.org \"Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\"\n\n\n\nThe optional \n--auth\n flag also allows you to add specific types of authentication,\nhandling the encoding for you. Currently only \n\"basic\"\n is supported as an option here.\nFor example:\n\n\n$ coreapi credentials add api.example.org tomchristie:foobar --auth basic\n\n\n\nYou can also add specific request headers, using the \nheaders\n command:\n\n\n$ coreapi headers add api.example.org x-api-version 2\n\n\n\nFor more information and a listing of the available subcommands use \ncoreapi\ncredentials --help\n or \ncoreapi headers --help\n.\n\n\nCodecs\n\n\nBy default the command line client only includes support for reading Core JSON\nschemas, however it includes a plugin system for installing additional codecs.\n\n\n$ pip install openapi-codec jsonhyperschema-codec hal-codec\n$ coreapi codecs show\nCodecs\ncorejson application/vnd.coreapi+json encoding, decoding\nhal application/hal+json encoding, decoding\nopenapi application/openapi+json encoding, decoding\njsonhyperschema application/schema+json decoding\njson application/json data\ntext text/* data\n\n\n\nUtilities\n\n\nThe command line client includes functionality for bookmarking API URLs\nunder a memorable name. For example, you can add a bookmark for the\nexisting API, like so...\n\n\n$ coreapi bookmarks add accountmanagement\n\n\n\nThere is also functionality for navigating forward or backward through the\nhistory of which API URLs have been accessed.\n\n\n$ coreapi history show\n$ coreapi history back\n\n\n\nFor more information and a listing of the available subcommands use\n\ncoreapi bookmarks --help\n or \ncoreapi history --help\n.\n\n\nOther commands\n\n\nTo display the current \nDocument\n:\n\n\n$ coreapi show\n\n\n\nTo reload the current \nDocument\n from the network:\n\n\n$ coreapi reload\n\n\n\nTo load a schema file from disk:\n\n\n$ coreapi load my-api-schema.json --format corejson\n\n\n\nTo dump the current document to console in a given format:\n\n\n$ coreapi dump --format openapi\n\n\n\nTo remove the current document, along with all currently saved history,\ncredentials, headers and bookmarks:\n\n\n$ coreapi clear\n\n\n\n\n\nPython client library\n\n\nThe \ncoreapi\n Python package allows you to programmatically interact with any\nAPI that exposes a supported schema format.\n\n\nGetting started\n\n\nYou'll need to install the \ncoreapi\n package using \npip\n before you can get\nstarted.\n\n\n$ pip install coreapi\n\n\n\nIn order to start working with an API, we first need a \nClient\n instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour.\n\n\nimport coreapi\nclient = coreapi.Client()\n\n\n\nOnce we have a \nClient\n instance, we can fetch an API schema from the network.\n\n\nschema = client.get('https://api.example.org/')\n\n\n\nThe object returned from this call will be a \nDocument\n instance, which is\na representation of the API schema.\n\n\nAuthentication\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT'\n token=''\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\nclient = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'obtain-token']\nparams = {username: \"example\", email: \"example@example.com\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nauth = coreapi.auth.BasicAuthentication(\n username='',\n password=''\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nInteracting with the API\n\n\nNow that we have a client and have fetched our schema \nDocument\n, we can now\nstart to interact with the API:\n\n\nusers = client.action(schema, ['users', 'list'])\n\n\n\nSome endpoints may include named parameters, which might be either optional or required:\n\n\nnew_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})\n\n\n\nCodecs\n\n\nCodecs are responsible for encoding or decoding Documents.\n\n\nThe decoding process is used by a client to take a bytestring of an API schema\ndefinition, and returning the Core API \nDocument\n that represents that interface.\n\n\nA codec should be associated with a particular media type, such as \n'application/coreapi+json'\n.\n\n\nThis media type is used by the server in the response \nContent-Type\n header,\nin order to indicate what kind of data is being returned in the response.\n\n\nConfiguring codecs\n\n\nThe codecs that are available can be configured when instantiating a client.\nThe keyword argument used here is \ndecoders\n, because in the context of a\nclient the codecs are only for \ndecoding\n responses.\n\n\nIn the following example we'll configure a client to only accept \nCore JSON\n\nand \nJSON\n responses. This will allow us to receive and decode a Core JSON schema,\nand subsequently to receive JSON responses made against the API.\n\n\nfrom coreapi import codecs, Client\n\ndecoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]\nclient = Client(decoders=decoders)\n\n\n\nLoading and saving schemas\n\n\nYou can use a codec directly, in order to load an existing schema definition,\nand return the resulting \nDocument\n.\n\n\ninput_file = open('my-api-schema.json', 'rb')\nschema_definition = input_file.read()\ncodec = codecs.CoreJSONCodec()\nschema = codec.load(schema_definition)\n\n\n\nYou can also use a codec directly to generate a schema definition given a \nDocument\n instance:\n\n\nschema_definition = codec.dump(schema)\noutput_file = open('my-api-schema.json', 'rb')\noutput_file.write(schema_definition)\n\n\n\nTransports\n\n\nTransports are responsible for making network requests. The set of transports\nthat a client has installed determines which network protocols it is able to\nsupport.\n\n\nCurrently the \ncoreapi\n library only includes an HTTP/HTTPS transport, but\nother protocols can also be supported.\n\n\nConfiguring transports\n\n\nThe behavior of the network layer can be customized by configuring the\ntransports that the client is instantiated with.\n\n\nimport requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports)\n\n\n\nMore complex customizations can also be achieved, for example modifying the\nunderlying \nrequests.Session\n instance to \nattach transport adaptors\n\nthat modify the outgoing requests.\n\n\n\n\nJavaScript Client Library\n\n\nThe JavaScript client library allows you to interact with your API either from a browser, or using node.\n\n\nInstalling the JavaScript client\n\n\nThere are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static \ncoreapi.js\n file, which contains the code for the dynamic client library, and a templated \nschema.js\n resource, which exposes your API schema.\n\n\nFirst, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API service'))\n]\n\n\n\nOnce the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.\n\n\n\n{% load static %}\n\n\n\n\n\nThe \ncoreapi\n library, and the \nschema\n object will now both be available on the \nwindow\n instance.\n\n\nconst coreapi = window.coreapi\nconst schema = window.schema\n\n\n\nInstantiating a client\n\n\nIn order to interact with the API you'll need a client instance.\n\n\nvar client = new coreapi.Client()\n\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nSession authentication\n\n\nThe \nSessionAuthentication\n class allows session cookies to provide the user\nauthentication. You'll want to provide a standard HTML login flow, to allow\nthe user to login, and then instantiate a client using session authentication:\n\n\nlet auth = new coreapi.auth.SessionAuthentication({\n csrfCookieName: 'csrftoken',\n csrfHeaderName: 'X-CSRFToken'\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nThe authentication scheme will handle including a CSRF header in any outgoing\nrequests for unsafe HTTP methods.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nlet auth = new coreapi.auth.TokenAuthentication({\n scheme: 'JWT'\n token: ''\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\n// Setup some globally accessible state\nwindow.client = new coreapi.Client()\nwindow.loggedIn = false\n\nfunction loginUser(username, password) {\n let action = [\"api-token-auth\", \"obtain-token\"]\n let params = {username: \"example\", email: \"example@example.com\"}\n client.action(schema, action, params).then(function(result) {\n // On success, instantiate an authenticated client.\n let auth = window.coreapi.auth.TokenAuthentication({\n scheme: 'JWT',\n token: result['token']\n })\n window.client = coreapi.Client({auth: auth})\n window.loggedIn = true\n }).catch(function (error) {\n // Handle error case where eg. user provides incorrect credentials.\n })\n}\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nlet auth = new coreapi.auth.BasicAuthentication({\n username: '',\n password: ''\n})\nlet client = new coreapi.Client({auth: auth})\n\n\n\nUsing the client\n\n\nMaking requests:\n\n\nlet action = [\"users\", \"list\"]\nclient.action(schema, action).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nIncluding parameters:\n\n\nlet action = [\"users\", \"create\"]\nlet params = {username: \"example\", email: \"example@example.com\"}\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nHandling errors:\n\n\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n}).catch(function (error) {\n // Error value is in 'error'\n})\n\n\n\nInstallation with node\n\n\nThe coreapi package is available on NPM.\n\n\n$ npm install coreapi\n$ node\nconst coreapi = require('coreapi')\n\n\n\nYou'll either want to include the API schema in your codebase directly, by copying it from the \nschema.js\n resource, or else load the schema asynchronously. For example:\n\n\nlet client = new coreapi.Client()\nlet schema = null\nclient.get(\"https://api.example.org/\").then(function(data) {\n // Load a CoreJSON API schema.\n schema = data\n console.log('schema loaded')\n})", "title": "API Clients" }, { @@ -4267,7 +4252,7 @@ }, { "location": "/topics/api-clients/#token-authentication", - "text": "The TokenAuthentication class can be used to support REST framework's built-in TokenAuthentication , as well as OAuth and JWT schemes. auth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=''\n)\nclient = coreapi.Client(auth=auth) When using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client. A suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint For example, using the \"Django REST framework JWT\" package client = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'create']\nparams = {\"username\": \"example\", \"password\": \"secret\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)", + "text": "The TokenAuthentication class can be used to support REST framework's built-in TokenAuthentication , as well as OAuth and JWT schemes. auth = coreapi.auth.TokenAuthentication(\n scheme='JWT'\n token=''\n)\nclient = coreapi.Client(auth=auth) When using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client. A suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint For example, using the \"Django REST framework JWT\" package client = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'obtain-token']\nparams = {username: \"example\", email: \"example@example.com\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)", "title": "Token authentication" }, { @@ -4407,12 +4392,12 @@ }, { "location": "/topics/html-and-forms/", - "text": "HTML & Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be 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\n\n

        Profiles

        \n
          \n {% for profile in profiles %}\n
        • {{ profile.name }}
        • \n {% endfor %}\n
        \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\n\n

        Profile - {{ profile.name }}

        \n\n\n {% csrf_token %}\n {% render_form serializer %}\n \n\n\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\n\n \u2026\n \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', 'autofocus': True}\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
        \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \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
        \n {% csrf_token %}\n {% render_form serializer %}\n
        \n
        \n \n
        \n
        \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
        \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \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, autofocus\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", + "text": "HTML & 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\n\n

        Profiles

        \n
          \n {% for profile in profiles %}\n
        • {{ profile.name }}
        • \n {% endfor %}\n
        \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\n\n

        Profile - {{ profile.name }}

        \n\n
        \n {% csrf_token %}\n {% render_form serializer %}\n \n
        \n\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\n\n \u2026\n \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', 'autofocus': True}\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
        \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \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
        \n {% csrf_token %}\n {% render_form serializer %}\n
        \n
        \n \n
        \n
        \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
        \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \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, autofocus\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", "title": "HTML & Forms" }, { "location": "/topics/html-and-forms/#html-forms", - "text": "REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.", + "text": "REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.", "title": "HTML & Forms" }, { @@ -4447,7 +4432,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, autofocus 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, autofocus 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" }, { @@ -4591,1524 +4576,1514 @@ "title": "What REST framework doesn't provide." }, { - "location": "/community/tutorials-and-resources/", - "text": "Tutorials and Resources\n\n\nThere are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.\n\n\nBooks\n\n\n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n\n\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django REST Framework\n\n\nDjango REST Framework - An Introduction\n\n\nDjango REST Framework Tutorial\n\n\nDjango REST Framework Course\n\n\nBuilding a RESTful API with Django REST Framework\n\n\nGetting Started with Django REST Framework and AngularJS\n\n\nEnd to End Web App with Django REST Framework & AngularJS\n\n\nStart Your API - Django REST Framework Part 1\n\n\nPermissions & 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\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 1\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 2\n\n\nDjango REST Framework Tutorial - Build a Blog API\n\n\nDjango REST Framework & React Tutorial - Build a Todo List API\n\n\nTutorial: Django REST with React (Django 2.0)\n\n\n\n\nVideos\n\n\nTalks\n\n\n\n\nLevel Up! Rethinking the Web API Framework\n\n\nHow to Make a Full Fledged REST API with Django OAuth Toolkit\n\n\nDjango REST API - So Easy You Can Learn It in 25 Minutes\n\n\nTom Christie about Django Rest Framework at Django: Under The Hood\n\n\nDjango REST Framework: Schemas, Hypermedia & Client Libraries\n\n\n\n\nTutorials\n\n\n\n\nDjango REST Framework Part 1\n\n\nDjango REST Framework in Your PJ's!\n\n\nBuilding a REST API Using Django & Django REST Framework\n\n\nBlog API with Django REST Framework\n\n\nEmber and Django Part 1\n\n\nDjango REST Framework Image Upload Tutorial (with AngularJS)\n\n\nDjango REST Framework Tutorials\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\nIntegrating Pandas, Django REST Framework and Bokeh\n\n\nControlling Uncertainty on Web Applications and APIs\n\n\nFull Text Search in Django REST Framework with Database Backends\n\n\nOAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends\n\n\nNested Resources with Django REST Framework\n\n\nImage Fields with Django REST Framework\n\n\nChatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3\n\n\nNew Django Admin with DRF and EmberJS... What are the News?\n\n\nBlog posts about Django REST Framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework\n\n\nDRF-schema-adapter\n\n\n\n\nWant your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please \nsubmit a pull request\n or \nemail us\n!", - "title": "Tutorials and Resources" - }, - { - "location": "/community/tutorials-and-resources/#tutorials-and-resources", - "text": "There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.", - "title": "Tutorials and Resources" - }, - { - "location": "/community/tutorials-and-resources/#books", - "text": "", - "title": "Books" - }, - { - "location": "/community/tutorials-and-resources/#tutorials", - "text": "Beginner's Guide to the Django REST Framework Django REST Framework - An Introduction Django REST Framework Tutorial Django REST Framework Course Building a RESTful API with Django REST Framework Getting Started with Django REST Framework and AngularJS End to End Web App with Django REST Framework & AngularJS Start Your API - Django REST Framework Part 1 Permissions & Authentication - Django REST Framework Part 2 ViewSets and Routers - Django REST Framework Part 3 Django REST Framework User Endpoint Check Credentials Using Django REST Framework Creating a Production Ready API with Python and Django REST Framework \u2013 Part 1 Creating a Production Ready API with Python and Django REST Framework \u2013 Part 2 Django REST Framework Tutorial - Build a Blog API Django REST Framework & React Tutorial - Build a Todo List API Tutorial: Django REST with React (Django 2.0)", - "title": "Tutorials" - }, - { - "location": "/community/tutorials-and-resources/#videos", - "text": "", - "title": "Videos" - }, - { - "location": "/community/tutorials-and-resources/#talks", - "text": "Level Up! Rethinking the Web API Framework How to Make a Full Fledged REST API with Django OAuth Toolkit Django REST API - So Easy You Can Learn It in 25 Minutes Tom Christie about Django Rest Framework at Django: Under The Hood Django REST Framework: Schemas, Hypermedia & Client Libraries", - "title": "Talks" - }, - { - "location": "/community/tutorials-and-resources/#tutorials_1", - "text": "Django REST Framework Part 1 Django REST Framework in Your PJ's! Building a REST API Using Django & Django REST Framework Blog API with Django REST Framework Ember and Django Part 1 Django REST Framework Image Upload Tutorial (with AngularJS) Django REST Framework Tutorials", - "title": "Tutorials" - }, - { - "location": "/community/tutorials-and-resources/#articles", - "text": "Web API performance: Profiling Django REST Framework API Development with Django and Django REST Framework Integrating Pandas, Django REST Framework and Bokeh Controlling Uncertainty on Web Applications and APIs Full Text Search in Django REST Framework with Database Backends OAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends Nested Resources with Django REST Framework Image Fields with Django REST Framework Chatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3 New Django Admin with DRF and EmberJS... What are the News? Blog posts about Django REST Framework", - "title": "Articles" - }, - { - "location": "/community/tutorials-and-resources/#documentations", - "text": "Classy Django REST Framework DRF-schema-adapter Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us !", - "title": "Documentations" - }, - { - "location": "/community/third-party-packages/", - "text": "Third Party Packages\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\u2014 \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 Packages\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\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\ndjangorestframework-simplejwt\n - An alternative package that 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\ndrf-oidc-auth\n - Implements OpenID Connect token authentication for DRF.\n\n\ndrfpasswordless\n - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.\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\ndjango-rest-framework-serializer-extensions\n -\n Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis.\n\n\ndjangorestframework-queryfields\n - Serializer mixin allowing clients to control which fields will be sent in the API response.\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\ndjangorestframework-rapidjson\n - Provides rapidjson support with parser and renderer.\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\ndrf_tweaks\n - Serializers with one-step validation (and more), pagination without counts and other tweaks.\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\ndjangorest-alchemy\n - SQLAlchemy support for REST framework.\n\n\ndjangorestframework-datatables\n - Seamless integration between Django REST framework and \nDatatables\n.", + "location": "/topics/third-party-packages/", + "text": "Third Party Packages\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\u2014 \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 Packages\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\ndjangorestframework-simplejwt\n - An alternative package that 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\ndrf-oidc-auth\n - Implements OpenID Connect token authentication for DRF.\n\n\ndrfpasswordless\n - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.\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\ndjango-rest-framework-serializer-extensions\n -\n Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis.\n\n\ndjangorestframework-queryfields\n - Serializer mixin allowing clients to control which fields will be sent in the API response.\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\ndjangorestframework-rapidjson\n - Provides rapidjson support with parser and renderer.\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\ndrf_tweaks\n - Serializers with one-step validation (and more), pagination without counts and other tweaks.\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\ndjangorest-alchemy\n - SQLAlchemy support for REST framework.\n\n\ndjangorestframework-datatables\n - Seamless integration between Django REST framework and \nDatatables\n.", "title": "Third Party Packages" }, { - "location": "/community/third-party-packages/#third-party-packages", + "location": "/topics/third-party-packages/#third-party-packages", "text": "Software ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills. \u2014 Jan Bosch .", "title": "Third Party Packages" }, { - "location": "/community/third-party-packages/#about-third-party-packages", + "location": "/topics/third-party-packages/#about-third-party-packages", "text": "Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases. We support , encourage and strongly favor the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework. We aim to make creating third party packages as easy as possible, whilst keeping a simple and well maintained 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. If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the Mailing List .", "title": "About Third Party Packages" }, { - "location": "/community/third-party-packages/#how-to-create-a-third-party-package", + "location": "/topics/third-party-packages/#how-to-create-a-third-party-package", "text": "", "title": "How to create a Third Party Package" }, { - "location": "/community/third-party-packages/#creating-your-package", + "location": "/topics/third-party-packages/#creating-your-package", "text": "You can use this cookiecutter template 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. Note: Let us know if you have an alternate cookiecuter package so we can also link to it.", "title": "Creating your package" }, { - "location": "/community/third-party-packages/#running-the-initial-cookiecutter-command", + "location": "/topics/third-party-packages/#running-the-initial-cookiecutter-command", "text": "To run the initial cookiecutter command, you'll first need to install the Python cookiecutter package. $ pip install cookiecutter Once cookiecutter is installed just run the following to create a new project. $ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values. full_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\")?", "title": "Running the initial cookiecutter command" }, { - "location": "/community/third-party-packages/#getting-it-onto-github", + "location": "/topics/third-party-packages/#getting-it-onto-github", "text": "To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository here . If you need help, check out the Create A Repo article on GitHub.", "title": "Getting it onto GitHub" }, { - "location": "/community/third-party-packages/#adding-to-travis-ci", + "location": "/topics/third-party-packages/#adding-to-travis-ci", "text": "We recommend using Travis CI , a hosted continuous integration service which integrates well with GitHub and is free for public repositories. To get started with Travis CI, sign in with your GitHub account. Once you're signed in, go to your profile page and enable the service hook for the repository you want. If you use the cookiecutter template, your project will already contain a .travis.yml 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.", "title": "Adding to Travis CI" }, { - "location": "/community/third-party-packages/#uploading-to-pypi", + "location": "/topics/third-party-packages/#uploading-to-pypi", "text": "Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via pip . You must register an account before publishing to PyPI. To register your package on PyPI run the following command. $ python setup.py register If this is the first time publishing to PyPI, you'll be prompted to login. Note: Before publishing you'll need to make sure you have the latest pip that supports wheel as well as install the wheel package. $ pip install --upgrade pip\n$ pip install wheel After this, every time you want to release a new version on PyPI just run the following command. $ 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 After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release. We recommend to follow Semantic Versioning for your package's versions.", "title": "Uploading to PyPI" }, { - "location": "/community/third-party-packages/#development", + "location": "/topics/third-party-packages/#development", "text": "", "title": "Development" }, { - "location": "/community/third-party-packages/#version-requirements", + "location": "/topics/third-party-packages/#version-requirements", "text": "The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, tox.ini , .travis.yml , and setup.py to match the set of versions you wish to support.", "title": "Version requirements" }, { - "location": "/community/third-party-packages/#tests", + "location": "/topics/third-party-packages/#tests", "text": "The cookiecutter template includes a runtests.py which uses the pytest package as a test runner. Before running, you'll need to install a couple test requirements. $ pip install -r requirements.txt Once requirements installed, you can run runtests.py . $ ./runtests.py Run using a more concise output style. $ ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. $ ./runtests.py --fast Don't run the flake8 code linting. $ ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. $ ./runtests.py --lintonly Run the tests for a given test case. $ ./runtests.py MyTestCase Run the tests for a given test method. $ ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. $ ./runtests.py test_this_method To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using tox . Tox is a generic virtualenv management and test command line tool. First, install tox globally. $ pip install tox To run tox , just simply run: $ tox To run a particular tox environment: $ tox -e envlist envlist is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run: $ tox -l", "title": "Tests" }, { - "location": "/community/third-party-packages/#version-compatibility", + "location": "/topics/third-party-packages/#version-compatibility", "text": "Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a compat.py module, and should provide a single common interface that the rest of the codebase can use. Check out Django REST framework's compat.py for an example.", "title": "Version compatibility" }, { - "location": "/community/third-party-packages/#once-your-package-is-available", + "location": "/topics/third-party-packages/#once-your-package-is-available", "text": "Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.", "title": "Once your package is available" }, { - "location": "/community/third-party-packages/#adding-to-the-django-rest-framework-grid", + "location": "/topics/third-party-packages/#adding-to-the-django-rest-framework-grid", "text": "We suggest adding your package to the REST Framework grid on Django Packages.", "title": "Adding to the Django REST framework grid" }, { - "location": "/community/third-party-packages/#adding-to-the-django-rest-framework-docs", + "location": "/topics/third-party-packages/#adding-to-the-django-rest-framework-docs", "text": "Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions . You can also link your package under the Third Party Packages section.", "title": "Adding to the Django REST framework docs" }, { - "location": "/community/third-party-packages/#announce-on-the-discussion-group", + "location": "/topics/third-party-packages/#announce-on-the-discussion-group", "text": "You can also let others know about your package through the discussion group .", "title": "Announce on the discussion group." }, { - "location": "/community/third-party-packages/#existing-third-party-packages", + "location": "/topics/third-party-packages/#existing-third-party-packages", "text": "Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages . To submit new content, open an issue or create a pull request .", "title": "Existing Third Party Packages" }, { - "location": "/community/third-party-packages/#authentication", - "text": "djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. djangorestframework-simplejwt - An alternative package that provides JSON Web Token Authentication support. hawkrest - Provides Hawk HTTP Authorization. djangorestframework-httpsignature - Provides an easy to use HTTP Signature Authentication mechanism. djoser - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. django-rest-auth - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. drf-oidc-auth - Implements OpenID Connect token authentication for DRF. drfpasswordless - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.", + "location": "/topics/third-party-packages/#authentication", + "text": "djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. doac - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. djangorestframework-simplejwt - An alternative package that provides JSON Web Token Authentication support. hawkrest - Provides Hawk HTTP Authorization. djangorestframework-httpsignature - Provides an easy to use HTTP Signature Authentication mechanism. djoser - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. django-rest-auth - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. drf-oidc-auth - Implements OpenID Connect token authentication for DRF. drfpasswordless - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.", "title": "Authentication" }, { - "location": "/community/third-party-packages/#permissions", + "location": "/topics/third-party-packages/#permissions", "text": "drf-any-permissions - Provides alternative permission handling. djangorestframework-composed-permissions - Provides a simple way to define complex permissions. rest_condition - Another extension for building complex permissions in a simple and convenient way. dry-rest-permissions - Provides a simple way to define permissions for individual api actions.", "title": "Permissions" }, { - "location": "/community/third-party-packages/#serializers", + "location": "/topics/third-party-packages/#serializers", "text": "django-rest-framework-mongoengine - Serializer class that supports using MongoDB as the storage layer for Django REST framework. djangorestframework-gis - Geographic add-ons djangorestframework-hstore - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. html-json-forms - Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec. django-rest-framework-serializer-extensions -\n Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis. djangorestframework-queryfields - Serializer mixin allowing clients to control which fields will be sent in the API response.", "title": "Serializers" }, { - "location": "/community/third-party-packages/#serializer-fields", + "location": "/topics/third-party-packages/#serializer-fields", "text": "drf-compound-fields - Provides \"compound\" serializer fields, such as lists of simple values. django-extra-fields - Provides extra serializer fields. django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here .", "title": "Serializer fields" }, { - "location": "/community/third-party-packages/#views", + "location": "/topics/third-party-packages/#views", "text": "djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.", "title": "Views" }, { - "location": "/community/third-party-packages/#routers", + "location": "/topics/third-party-packages/#routers", "text": "drf-nested-routers - Provides routers and relationship fields for working with nested resources. wq.db.rest - Provides an admin-style model registration API with reasonable default URLs and viewsets.", "title": "Routers" }, { - "location": "/community/third-party-packages/#parsers", + "location": "/topics/third-party-packages/#parsers", "text": "djangorestframework-msgpack - Provides MessagePack renderer and parser support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. djangorestframework-camel-case - Provides camel case JSON renderers and parsers.", "title": "Parsers" }, { - "location": "/community/third-party-packages/#renderers", + "location": "/topics/third-party-packages/#renderers", "text": "djangorestframework-csv - Provides CSV renderer support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. drf_ujson - Implements JSON rendering using the UJSON package. rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats. djangorestframework-rapidjson - Provides rapidjson support with parser and renderer.", "title": "Renderers" }, { - "location": "/community/third-party-packages/#filtering", + "location": "/topics/third-party-packages/#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. 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" }, { - "location": "/community/third-party-packages/#misc", + "location": "/topics/third-party-packages/#misc", "text": "cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. django-rest-swagger - An API documentation generator for Swagger UI. django-rest-framework-proxy - Proxy to redirect incoming request to another API server. gaiarestframework - Utils for django-rest-framework drf-extensions - A collection of custom extensions ember-django-adapter - An adapter for working with Ember.js django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . drf-tracking - Utilities to track requests to DRF API views. drf_tweaks - Serializers with one-step validation (and more), pagination without counts and other tweaks. django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm , which are adapters between DRF serializers and Django forms. drf-haystack - Haystack search for Django Rest Framework django-rest-framework-version-transforms - Enables the use of delta transformations for versioning of DRF resource representations. django-rest-messaging , django-rest-messaging-centrifugo and django-rest-messaging-js - A real-time pluggable messaging service using DRM. djangorest-alchemy - SQLAlchemy support for REST framework. djangorestframework-datatables - Seamless integration between Django REST framework and Datatables .", "title": "Misc" }, { - "location": "/community/contributing/", + "location": "/topics/tutorials-and-resources/", + "text": "Tutorials and Resources\n\n\nThere are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.\n\n\nBooks\n\n\n\n \n\n \n\n \n\n \n\n \n\n \n\n\n\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django REST Framework\n\n\nDjango REST Framework - An Introduction\n\n\nDjango REST Framework Tutorial\n\n\nDjango REST Framework Course\n\n\nBuilding a RESTful API with Django REST Framework\n\n\nGetting Started with Django REST Framework and AngularJS\n\n\nEnd to End Web App with Django REST Framework & AngularJS\n\n\nStart Your API - Django REST Framework Part 1\n\n\nPermissions & 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\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 1\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 2\n\n\nDjango REST Framework Tutorial - Build a Blog API\n\n\nDjango REST Framework & React Tutorial - Build a Todo List API\n\n\nTutorial: Django REST with React (Django 2.0)\n\n\n\n\nVideos\n\n\nTalks\n\n\n\n\nLevel Up! Rethinking the Web API Framework\n\n\nHow to Make a Full Fledged REST API with Django OAuth Toolkit\n\n\nDjango REST API - So Easy You Can Learn It in 25 Minutes\n\n\nTom Christie about Django Rest Framework at Django: Under The Hood\n\n\nDjango REST Framework: Schemas, Hypermedia & Client Libraries\n\n\n\n\nTutorials\n\n\n\n\nDjango REST Framework Part 1\n\n\nDjango REST Framework in Your PJ's!\n\n\nBuilding a REST API Using Django & Django REST Framework\n\n\nBlog API with Django REST Framework\n\n\nEmber and Django Part 1\n\n\nDjango REST Framework Image Upload Tutorial (with AngularJS)\n\n\nDjango REST Framework Tutorials\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\nIntegrating Pandas, Django REST Framework and Bokeh\n\n\nControlling Uncertainty on Web Applications and APIs\n\n\nFull Text Search in Django REST Framework with Database Backends\n\n\nOAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends\n\n\nNested Resources with Django REST Framework\n\n\nImage Fields with Django REST Framework\n\n\nChatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3\n\n\nNew Django Admin with DRF and EmberJS... What are the News?\n\n\nBlog posts about Django REST Framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework\n\n\nDRF-schema-adapter\n\n\n\n\nWant your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please \nsubmit a pull request\n or \nemail us\n!", + "title": "Tutorials and Resources" + }, + { + "location": "/topics/tutorials-and-resources/#tutorials-and-resources", + "text": "There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.", + "title": "Tutorials and Resources" + }, + { + "location": "/topics/tutorials-and-resources/#books", + "text": "", + "title": "Books" + }, + { + "location": "/topics/tutorials-and-resources/#tutorials", + "text": "Beginner's Guide to the Django REST Framework Django REST Framework - An Introduction Django REST Framework Tutorial Django REST Framework Course Building a RESTful API with Django REST Framework Getting Started with Django REST Framework and AngularJS End to End Web App with Django REST Framework & AngularJS Start Your API - Django REST Framework Part 1 Permissions & Authentication - Django REST Framework Part 2 ViewSets and Routers - Django REST Framework Part 3 Django REST Framework User Endpoint Check Credentials Using Django REST Framework Creating a Production Ready API with Python and Django REST Framework \u2013 Part 1 Creating a Production Ready API with Python and Django REST Framework \u2013 Part 2 Django REST Framework Tutorial - Build a Blog API Django REST Framework & React Tutorial - Build a Todo List API Tutorial: Django REST with React (Django 2.0)", + "title": "Tutorials" + }, + { + "location": "/topics/tutorials-and-resources/#videos", + "text": "", + "title": "Videos" + }, + { + "location": "/topics/tutorials-and-resources/#talks", + "text": "Level Up! Rethinking the Web API Framework How to Make a Full Fledged REST API with Django OAuth Toolkit Django REST API - So Easy You Can Learn It in 25 Minutes Tom Christie about Django Rest Framework at Django: Under The Hood Django REST Framework: Schemas, Hypermedia & Client Libraries", + "title": "Talks" + }, + { + "location": "/topics/tutorials-and-resources/#tutorials_1", + "text": "Django REST Framework Part 1 Django REST Framework in Your PJ's! Building a REST API Using Django & Django REST Framework Blog API with Django REST Framework Ember and Django Part 1 Django REST Framework Image Upload Tutorial (with AngularJS) Django REST Framework Tutorials", + "title": "Tutorials" + }, + { + "location": "/topics/tutorials-and-resources/#articles", + "text": "Web API performance: Profiling Django REST Framework API Development with Django and Django REST Framework Integrating Pandas, Django REST Framework and Bokeh Controlling Uncertainty on Web Applications and APIs Full Text Search in Django REST Framework with Database Backends OAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends Nested Resources with Django REST Framework Image Fields with Django REST Framework Chatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3 New Django Admin with DRF and EmberJS... What are the News? Blog posts about Django REST Framework", + "title": "Articles" + }, + { + "location": "/topics/tutorials-and-resources/#documentations", + "text": "Classy Django REST Framework DRF-schema-adapter Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us !", + "title": "Documentations" + }, + { + "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\u2014 \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 & 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, first create a Fork from the\n\nDjango REST Framework repo\n on GitHub.\n\n\nThen clone your fork. The clone command will look like this, with your GitHub\nusername instead of YOUR-USERNAME:\n\n\ngit clone https://github.com/YOUR-USERNAME/Spoon-Knife\n\n\n\nSee GitHub's \nFork a Repo\n Guide for more help.\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" }, { - "location": "/community/contributing/#contributing-to-rest-framework", + "location": "/topics/contributing/#contributing-to-rest-framework", "text": "The world can only really be changed one piece at a time. The art is picking that piece. \u2014 Tim Berners-Lee There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.", "title": "Contributing to REST framework" }, { - "location": "/community/contributing/#community", + "location": "/topics/contributing/#community", "text": "The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case. If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with. Other really great ways you can help move the community forward include helping to answer questions on the discussion group , or setting up an email alert on StackOverflow so that you get notified of any new questions with the django-rest-framework tag. When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.", "title": "Community" }, { - "location": "/community/contributing/#code-of-conduct", + "location": "/topics/contributing/#code-of-conduct", "text": "Please keep the tone polite & 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. Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations. The Django code of conduct gives a fuller set of guidelines for participating in community forums.", "title": "Code of conduct" }, { - "location": "/community/contributing/#issues", + "location": "/topics/contributing/#issues", "text": "It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the discussion group . Feature requests, bug reports and other issues should be raised on the GitHub issue tracker . Some tips on good issue reporting: When describing issues try to phrase your ticket in terms of the behavior you think needs changing rather than the code you think need changing. Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue. If 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. Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.", "title": "Issues" }, { - "location": "/community/contributing/#triaging-issues", + "location": "/topics/contributing/#triaging-issues", "text": "Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to Read through the ticket - does it make sense, is it missing any context that would help explain it better? Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group? If 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? If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package? If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.", "title": "Triaging issues" }, { - "location": "/community/contributing/#development", + "location": "/topics/contributing/#development", "text": "To start developing on Django REST framework, first create a Fork from the Django REST Framework repo on GitHub. Then clone your fork. The clone command will look like this, with your GitHub\nusername instead of YOUR-USERNAME: git clone https://github.com/YOUR-USERNAME/Spoon-Knife See GitHub's Fork a Repo Guide for more help. Changes should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.", "title": "Development" }, { - "location": "/community/contributing/#testing", + "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 django\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py", "title": "Testing" }, { - "location": "/community/contributing/#test-options", + "location": "/topics/contributing/#test-options", "text": "Run using a more concise output style. ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. ./runtests.py --fast Don't run the flake8 code linting. ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. ./runtests.py --lintonly Run the tests for a given test case. ./runtests.py MyTestCase Run the tests for a given test method. ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. ./runtests.py test_this_method Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.", "title": "Test options" }, { - "location": "/community/contributing/#running-against-multiple-environments", + "location": "/topics/contributing/#running-against-multiple-environments", "text": "You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run: tox", "title": "Running against multiple environments" }, { - "location": "/community/contributing/#pull-requests", + "location": "/topics/contributing/#pull-requests", "text": "It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests. It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests. GitHub's documentation for working on pull requests is available here . Always run the tests before submitting pull requests, and ideally run tox 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. Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect. Above: Travis build notifications", "title": "Pull requests" }, { - "location": "/community/contributing/#managing-compatibility-issues", + "location": "/topics/contributing/#managing-compatibility-issues", "text": "Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the compat.py module, and should provide a single common interface that the rest of the codebase can use.", "title": "Managing compatibility issues" }, { - "location": "/community/contributing/#documentation", + "location": "/topics/contributing/#documentation", "text": "The documentation for REST framework is built from the Markdown source files in the docs directory . There are many great Markdown editors that make working with the documentation really easy. The Mou editor for Mac is one such editor that comes highly recommended.", "title": "Documentation" }, { - "location": "/community/contributing/#building-the-documentation", + "location": "/topics/contributing/#building-the-documentation", "text": "To build the documentation, install MkDocs with pip install mkdocs and then run the following command. mkdocs build This will build the documentation into the site directory. You can build the documentation and open a preview in a browser window by using the serve command. mkdocs serve", "title": "Building the documentation" }, { - "location": "/community/contributing/#language-style", + "location": "/topics/contributing/#language-style", "text": "Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible. Some other tips: Keep paragraphs reasonably short. Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.", "title": "Language style" }, { - "location": "/community/contributing/#markdown-style", + "location": "/topics/contributing/#markdown-style", "text": "There are a couple of conventions you should follow when working on the documentation.", "title": "Markdown style" }, { - "location": "/community/contributing/#1-headers", + "location": "/topics/contributing/#1-headers", "text": "Headers should use the hash style. For example: ### Some important topic The underline style should not be used. Don't do this: Some important topic\n====================", "title": "1. Headers" }, { - "location": "/community/contributing/#2-links", + "location": "/topics/contributing/#2-links", "text": "Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. Here is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing This style helps keep the documentation source consistent and readable. If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example: [authentication]: ../api-guide/authentication.md Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.", "title": "2. Links" }, { - "location": "/community/contributing/#3-notes", + "location": "/topics/contributing/#3-notes", "text": "If you want to draw attention to a note or warning, use a pair of enclosing lines, like so: ---\n\n**Note:** A useful documentation note.\n\n---", "title": "3. Notes" }, { - "location": "/community/project-management/", + "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\u2014 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/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).\n- [ ] Update supported versions:\n - [ ] `setup.py` `python_requires` list\n - [ ] `setup.py` Python & Django version trove classifiers\n - [ ] `README` Python & Django versions\n - [ ] `docs` Python & Django versions\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/encode/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 & 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": "/community/project-management/#project-management", + "location": "/topics/project-management/#project-management", "text": "\"No one can whistle a symphony; it takes a whole orchestra to play it\" \u2014 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" }, { - "location": "/community/project-management/#maintenance-team", + "location": "/topics/project-management/#maintenance-team", "text": "We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.", "title": "Maintenance team" }, { - "location": "/community/project-management/#current-team", + "location": "/topics/project-management/#current-team", "text": "The maintenance team for Q4 2015 : @tomchristie @xordoquy (Release manager.) @carltongibson @kevin-brown @jpadilla", "title": "Current team" }, { - "location": "/community/project-management/#maintenance-cycles", + "location": "/topics/project-management/#maintenance-cycles", "text": "Each maintenance cycle is initiated by an issue being opened with the Process label. To be considered for a maintainer role simply comment against the issue. Existing members must explicitly opt-in to the next cycle by check-marking their name. The final decision on the incoming team will be made by @tomchristie . Members of the maintenance team will be added as collaborators to the repository. The following template should be used for the description of the issue, and serves as the formal process for selecting the team. This 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.", "title": "Maintenance cycles" }, { - "location": "/community/project-management/#responsibilities-of-team-members", + "location": "/topics/project-management/#responsibilities-of-team-members", "text": "Team members have the following responsibilities. Close invalid or resolved tickets. Add triage labels and milestones to tickets. Merge finalized pull requests. Build and deploy the documentation, using mkdocs gh-deploy . Build and update the included translation packs. Further notes for maintainers: Code changes should come in the form of a pull request - do not push directly to master. Maintainers should typically not merge their own pull requests. Each issue/pull request should have exactly one label once triaged. Search for un-triaged issues with is:open no:label . It should be noted that participating actively in the REST framework project clearly does not require being part of the maintenance team . Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.", "title": "Responsibilities of team members" }, { - "location": "/community/project-management/#release-process", + "location": "/topics/project-management/#release-process", "text": "The release manager is selected on every quarterly maintenance cycle. The manager should be selected by @tomchristie . The manager will then have the maintainer role added to PyPI package. The previous manager will then have the maintainer role removed from the PyPI package. Our PyPI releases will be handled by either the current release manager, or by @tomchristie . Every release should have an open issue tagged with the Release label and marked against the appropriate milestone. The following template should be used for the description of the issue, and serves as a release checklist. Release 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/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).\n- [ ] Update supported versions:\n - [ ] `setup.py` `python_requires` list\n - [ ] `setup.py` Python & Django version trove classifiers\n - [ ] `README` Python & Django versions\n - [ ] `docs` Python & Django versions\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/encode/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. When pushing the release to PyPI ensure that your environment has been installed from our development requirement.txt , so that documentation and PyPI installs are consistently being built against a pinned set of packages.", "title": "Release process" }, { - "location": "/community/project-management/#translations", + "location": "/topics/project-management/#translations", "text": "The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the transifex service .", "title": "Translations" }, { - "location": "/community/project-management/#managing-transifex", + "location": "/topics/project-management/#managing-transifex", "text": "The official Transifex client is used to upload and download translations to Transifex. The client is installed using pip: pip install transifex-client To 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 ~/.transifexrc file which contains your credentials. [https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com", "title": "Managing Transifex" }, { - "location": "/community/project-management/#upload-new-source-files", + "location": "/topics/project-management/#upload-new-source-files", "text": "When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run: # 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 When pushing source files, Transifex will update the source strings of a resource to match those from the new source file. Here's how differences between the old and new source files will be handled: New strings will be added. Modified strings will be added as well. Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then Transifex Translation Memory will automatically include the translation string.", "title": "Upload new source files" }, { - "location": "/community/project-management/#download-translations", + "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 --minimum-perc 10\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages", "title": "Download translations" }, { - "location": "/community/project-management/#project-requirements", + "location": "/topics/project-management/#project-requirements", "text": "All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the requirements directory. The requirements files are referenced from the tox.ini configuration file, ensuring we have a single source of truth for package versions used in testing. Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the pip list --outdated .", "title": "Project requirements" }, { - "location": "/community/project-management/#project-ownership", + "location": "/topics/project-management/#project-ownership", "text": "The PyPI package is owned by @tomchristie . As a backup @j4mie also has ownership of the package. If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties.", "title": "Project ownership" }, { - "location": "/community/project-management/#outstanding-management-ownership-issues", + "location": "/topics/project-management/#outstanding-management-ownership-issues", "text": "The following issues still need to be addressed: Consider moving the repo into a proper GitHub organization . Ensure @jamie has back-up access to the django-rest-framework.org domain setup and admin. Document ownership of the live example API. Document ownership of the mailing list and IRC channel. Document ownership and management of the security mailing list.", "title": "Outstanding management & ownership issues" }, { - "location": "/community/release-notes/", - "text": "Release Notes\n\n\n\n\nRelease Early, Release Often\n\n\n\u2014 Eric S. Raymond, \nThe Cathedral and the Bazaar\n.\n\n\n\n\nVersioning\n\n\nMinor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.\n\n\nMedium version numbers (0.x.0) may include API changes, in line with the \ndeprecation policy\n. You should read the release notes carefully before upgrading between medium point releases.\n\n\nMajor version numbers (x.0.0) are reserved for substantial project milestones.\n\n\nDeprecation policy\n\n\nREST framework releases follow a formal deprecation policy, which is in line with \nDjango's deprecation policy\n.\n\n\nThe timeline for deprecation of a feature present in version 1.0 would work as follows:\n\n\n\n\n\n\nVersion 1.1 would remain \nfully backwards compatible\n with 1.0, but would raise \nPendingDeprecationWarning\n warnings if you use the feature that are due to be deprecated. These warnings are \nsilent by default\n, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using \npython -Wd manage.py test\n, you'll be warned of any API changes you need to make.\n\n\n\n\n\n\nVersion 1.2 would escalate these warnings to \nDeprecationWarning\n, which is loud by default.\n\n\n\n\n\n\nVersion 1.3 would remove the deprecated bits of API entirely.\n\n\n\n\n\n\nNote that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.\n\n\nUpgrading\n\n\nTo upgrade Django REST framework to the latest version, use pip:\n\n\npip install -U djangorestframework\n\n\n\nYou can determine your currently installed version using \npip show\n:\n\n\npip show djangorestframework\n\n\n\n\n\n3.9.x series\n\n\n3.9.0\n\n\nDate\n: Unreleased\n\n\n\n\nDeprecate the \nRouter.register\n \nbase_name\n argument in favor of \nbasename\n. \n#5990\n\n\nDeprecate the \nRouter.get_default_base_name\n method in favor of \nRouter.get_default_basename\n. \n#5990\n\n\n\n\n3.8.x series\n\n\n3.8.2\n\n\nDate\n: \n6th April 2018\n\n\n\n\nFix \nread_only\n + \ndefault\n \nunique_together\n validation. \n#5922\n\n\nauthtoken.views import coreapi from rest_framework.compat, not directly. \n#5921\n\n\nDocs: Add missing argument 'detail' to Route \n#5920\n\n\n\n\n3.8.1\n\n\nDate\n: \n4th April 2018\n\n\n\n\n\n\nUse old \nurl_name\n behavior in route decorators \n#5915\n\n\nFor \nlist_route\n and \ndetail_route\n maintain the old behavior of \nurl_name\n,\nbasing it on the \nurl_path\n instead of the function name.\n\n\n\n\n\n\n3.8.0\n\n\nDate\n: \n3rd April 2018\n\n\n\n\n\n\nBreaking Change\n: Alter \nread_only\n plus \ndefault\n behaviour. \n#5886\n\n\nread_only\n fields will now \nalways\n be excluded from writable fields.\n\n\nPreviously \nread_only\n fields with a \ndefault\n value would use the \ndefault\n for create and update operations.\n\n\nIn order to maintain the old behaviour you may need to pass the value of \nread_only\n fields when calling \nsave()\n in\nthe view:\n\n\ndef perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n\n\n\nAlternatively you may override \nsave()\n or \ncreate()\n or \nupdate()\n on the serialiser as appropriate.\n\n\n\n\n\n\nCorrect allow_null behaviour when required=False \n#5888\n\n\nWithout an explicit \ndefault\n, \nallow_null\n implies a default of \nnull\n for outgoing serialisation. Previously such\nfields were being skipped when read-only or otherwise not required.\n\n\nPossible backwards compatibility break\n if you were relying on such fields being excluded from the outgoing\nrepresentation. In order to restore the old behaviour you can override \ndata\n to exclude the field when \nNone\n.\n\n\nFor example:\n\n\n@property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data\n\n\n\n\n\n\n\nRefactor dynamic route generation and improve viewset action introspectibility. \n#5705\n\n\nViewSet\ns have been provided with new attributes and methods that allow\nit to introspect its set of actions and the details of the current action.\n\n\n\n\nMerged \nlist_route\n and \ndetail_route\n into a single \naction\n decorator.\n\n\nGet all extra actions on a \nViewSet\n with \n.get_extra_actions()\n.\n\n\nExtra actions now set the \nurl_name\n and \nurl_path\n on the decorated method.\n\n\nurl_name\n is now based on the function name, instead of the \nurl_path\n,\n as the path is not always suitable (e.g., capturing arguments in the path).\n\n\nEnable action url reversing through \n.reverse_action()\n method (added in 3.7.4)\n\n\nExample reverse call: \nself.reverse_action(self.custom_action.url_name)\n\n\nAdd \ndetail\n initkwarg to indicate if the current action is operating on a\n collection or a single instance.\n\n\n\n\nAdditional changes:\n\n\n\n\nDeprecated \nlist_route\n & \ndetail_route\n in favor of \naction\n decorator with \ndetail\n boolean.\n\n\nDeprecated dynamic list/detail route variants in favor of \nDynamicRoute\n with \ndetail\n boolean.\n\n\nRefactored the router's dynamic route generation.\n\n\nlist_route\n and \ndetail_route\n maintain the old behavior of \nurl_name\n,\n basing it on the \nurl_path\n instead of the function name.\n\n\n\n\n\n\n\n\nFix formatting of the 3.7.4 release note \n#5704\n\n\n\n\nDocs: Update DRF Writable Nested Serializers references \n#5711\n\n\nDocs: Fixed typo in auth URLs example. \n#5713\n\n\nImprove composite field child errors \n#5655\n\n\nDisable HTML inputs for dict/list fields \n#5702\n\n\nFix typo in HostNameVersioning doc \n#5709\n\n\nUse rsplit to get module and classname for imports \n#5712\n\n\nFormalize URLPatternsTestCase \n#5703\n\n\nAdd exception translation test \n#5700\n\n\nTest staticfiles \n#5701\n\n\nAdd drf-yasg to documentation and schema 3rd party packages \n#5720\n\n\nRemove unused \ncompat._resolve_model()\n \n#5733\n\n\nDrop compat workaround for unsupported Python 3.2 \n#5734\n\n\nPrefer \niter(dict)\n over \niter(dict.keys())\n \n#5736\n\n\nPass \npython_requires\n argument to setuptools \n#5739\n\n\nRemove unused links from docs \n#5735\n\n\nPrefer https protocol for links in docs when available \n#5729\n\n\nAdd HStoreField, postgres fields tests \n#5654\n\n\nAlways fully qualify ValidationError in docs \n#5751\n\n\nRemove unreachable code from ManualSchema \n#5766\n\n\nAllowed customising API documentation code samples \n#5752\n\n\nUpdated docs to use \npip show\n \n#5757\n\n\nLoad 'static' instead of 'staticfiles' in templates \n#5773\n\n\nFixed a typo in \nfields\n docs \n#5783\n\n\nRefer to \"NamespaceVersioning\" instead of \"NamespacedVersioning\" in the documentation \n#5754\n\n\nErrorDetail: add \n__eq__\n/\n__ne__\n and \n__repr__\n \n#5787\n\n\nReplace \nbackground-attachment: fixed\n in docs \n#5777\n\n\nMake 404 & 403 responses consistent with \nexceptions.APIException\n output \n#5763\n\n\nSmall fix to API documentation: schemas \n#5796\n\n\nFix schema generation for PrimaryKeyRelatedField \n#5764\n\n\nRepresent serializer DictField as an Object in schema \n#5765\n\n\nAdded docs example reimplementing ObtainAuthToken \n#5802\n\n\nAdd schema to the ObtainAuthToken view \n#5676\n\n\nFix request formdata handling \n#5800\n\n\nFix authtoken views imports \n#5818\n\n\nUpdate pytest, isort \n#5815\n \n#5817\n \n#5894\n\n\nFixed active timezone handling for non ISO8601 datetimes. \n#5833\n\n\nMade TemplateHTMLRenderer render IntegerField inputs when value is \n0\n. \n#5834\n\n\nCorrected endpoint in tutorial instructions \n#5835\n\n\nAdd Django Rest Framework Role Filters to Third party packages \n#5809\n\n\nUse single copy of static assets. Update jQuery \n#5823\n\n\nChanges ternary conditionals to be PEP308 compliant \n#5827\n\n\nAdded links to 'A Todo List API with React' and 'Blog API' tutorials \n#5837\n\n\nFix comment typo in ModelSerializer \n#5844\n\n\nAdd admin to installed apps to avoid test failures. \n#5870\n\n\nFixed schema for UUIDField in SimpleMetadata. \n#5872\n\n\nCorrected docs on router include with namespaces. \n#5843\n\n\nTest using model objects for dotted source default \n#5880\n\n\nAllow traversing nullable related fields \n#5849\n\n\nAdded: Tutorial: Django REST with React (Django 2.0) \n#5891\n\n\nAdd \nLimitOffsetPagination.get_count\n to allow method override \n#5846\n\n\nDon't show hidden fields in metadata \n#5854\n\n\nEnable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. \n#5899\n\n\nAdded generic 500 and 400 JSON error handlers. \n#5904\n\n\n\n\n3.7.x series\n\n\n3.7.7\n\n\nDate\n: \n21st December 2017\n\n\n\n\nFix typo to include *.mo locale files to packaging. \n#5697\n, \n#5695\n\n\n\n\n3.7.6\n\n\nDate\n: \n21st December 2017\n\n\n\n\nAdd missing *.ico icon files to packaging.\n\n\n\n\n3.7.5\n\n\nDate\n: \n21st December 2017\n\n\n\n\nAdd missing *.woff2 font files to packaging. \n#5692\n\n\nAdd missing *.mo locale files to packaging. \n#5695\n, \n#5696\n\n\n\n\n3.7.4\n\n\nDate\n: \n20th December 2017\n\n\n\n\n\n\nSchema: Extract method for \nmanual_fields\n processing \n#5633\n\n\nAllows for easier customisation of \nmanual_fields\n processing, for example\nto provide per-method manual fields. \nAutoSchema\n adds \nget_manual_fields\n,\nas the intended override point, and a utility method \nupdate_fields\n, to\nhandle by-name field replacement from a list, which, in general, you are not\nexpected to override.\n\n\nNote: \nAutoSchema.__init__\n now ensures \nmanual_fields\n is a list.\nPreviously may have been stored internally as \nNone\n.\n\n\n\n\n\n\nRemove ulrparse compatability shim; use six instead \n#5579\n\n\n\n\nDrop compat wrapper for \nTimeDelta.total_seconds()\n \n#5577\n\n\nClean up all whitespace throughout project \n#5578\n\n\nCompat cleanup \n#5581\n\n\nAdd pygments CSS block in browsable API views \n#5584\n \n#5587\n\n\nRemove \nset_rollback()\n from compat \n#5591\n\n\nFix request body/POST access \n#5590\n\n\nRename test to reference correct issue \n#5610\n\n\nDocumentation Fixes \n#5611\n \n#5612\n\n\nRemove references to unsupported Django versions in docs and code \n#5602\n\n\nTest Serializer exclude for declared fields \n#5599\n\n\nFixed schema generation for filter backends \n#5613\n\n\nMinor cleanup for ModelSerializer tests \n#5598\n\n\nReimplement request attribute access w/ \n__getattr__\n \n#5617\n\n\nFixed SchemaJSRenderer renders invalid Javascript \n#5607\n\n\nMake Django 2.0 support official/explicit \n#5619\n\n\nPerform type check on passed request argument \n#5618\n\n\nFix AttributeError hiding on request authenticators \n#5600\n\n\nUpdate test requirements \n#5626\n\n\nDocs: \nSerializer._declared_fields\n enable modifying fields on a serializer \n#5629\n\n\nFix packaging \n#5624\n\n\nFix readme rendering for PyPI, add readme build to CI \n#5625\n\n\nUpdate tutorial \n#5622\n\n\nNon-required fields with \nallow_null=True\n should not imply a default value \n#5639\n\n\nDocs: Add \nallow_null\n serialization output note \n#5641\n\n\nUpdate to use the Django 2.0 release in tox.ini \n#5645\n\n\nFix \nSerializer.data\n for Browsable API rendering when provided invalid \ndata\n \n#5646\n\n\nDocs: Note AutoSchema limitations on bare APIView \n#5649\n\n\nAdd \n.basename\n and \n.reverse_action()\n to ViewSet \n#5648\n\n\nDocs: Fix typos in serializers documentation \n#5652\n\n\nFix \noverride_settings\n compat \n#5668\n\n\nAdd DEFAULT_SCHEMA_CLASS setting \n#5658\n\n\nAdd docs note re generated BooleanField being \nrequired=False\n \n#5665\n\n\nAdd 'dist' build \n#5656\n\n\nFix typo in docstring \n#5678\n\n\nDocs: Add \nUNAUTHENTICATED_USER = None\n note \n#5679\n\n\nUpdate OPTIONS example from \u201cDocumenting Your API\u201d \n#5680\n\n\nDocs: Add note on object permissions for FBVs \n#5681\n\n\nDocs: Add example to \nto_representation\n docs \n#5682\n\n\nAdd link to Classy DRF in docs \n#5683\n\n\nDocument ViewSet.action \n#5685\n\n\nFix schema docs typo \n#5687\n\n\nFix URL pattern parsing in schema generation \n#5689\n\n\nAdd example using \nsource=\u2018*\u2019\n to custom field docs. \n#5688\n\n\nFix format_suffix_patterns behavior with Django 2 path() routes \n#5691\n\n\n\n\n3.7.3\n\n\nDate\n: \n6th November 2017\n\n\n\n\nFix \nAppRegistryNotReady\n error from contrib.auth view imports \n#5567\n\n\n\n\n3.7.2\n\n\nDate\n: \n6th November 2017\n\n\n\n\nFixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. \n#5510\n\n\nAdd missing import for TextLexer. \n#5512\n\n\nAdding examples and documentation for caching \n#5514\n\n\nInclude date and date-time format for schema generation \n#5511\n\n\nUse triple backticks for markdown code blocks \n#5513\n\n\nInteractive docs - make bottom sidebar items sticky \n#5516\n\n\nClarify pagination system check \n#5524\n\n\nStop JSONBoundField mangling invalid JSON \n#5527\n\n\nHave JSONField render as textarea in Browsable API \n#5530\n\n\nSchema: Exclude OPTIONS/HEAD for ViewSet actions \n#5532\n\n\nFix ordering for dotted sources \n#5533\n\n\nFix: Fields with \nallow_null=True\n should imply a default serialization value \n#5518\n\n\nEnsure Location header is strictly a 'str', not subclass. \n#5544\n\n\nAdd import to example in api-guide/parsers \n#5547\n\n\nCatch OverflowError for \"out of range\" datetimes \n#5546\n\n\nAdd djangorestframework-rapidjson to third party packages \n#5549\n\n\nIncrease test coverage for \ndrf_create_token\n command \n#5550\n\n\nAdd trove classifier for Python 3.6 support. \n#5555\n\n\nAdd pip cache support to the Travis CI configuration \n#5556\n\n\nRename [\nwheel\n] section to [\nbdist_wheel\n] as the former is legacy \n#5557\n\n\nFix invalid escape sequence deprecation warnings \n#5560\n\n\nAdd interactive docs error template \n#5548\n\n\nAdd rounding parameter to DecimalField \n#5562\n\n\nFix all BytesWarning caught during tests \n#5561\n\n\nUse dict and set literals instead of calls to dict() and set() \n#5559\n\n\nChange ImageField validation pattern, use validators from DjangoImageField \n#5539\n\n\nFix processing unicode symbols in query_string by Python 2 \n#5552\n\n\n\n\n3.7.1\n\n\nDate\n: \n16th October 2017\n\n\n\n\nFix Interactive documentation always uses false for boolean fields in requests \n#5492\n\n\nImprove compatibility with Django 2.0 alpha. \n#5500\n \n#5503\n\n\nImproved handling of schema naming collisions \n#5486\n\n\nAdded additional docs and tests around providing a default value for dotted \nsource\n fields \n#5489\n\n\n\n\n3.7.0\n\n\nDate\n: \n6th October 2017\n\n\n\n\nFix \nDjangoModelPermissions\n to ensure user authentication before calling the view's \nget_queryset()\n method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. \n#5376\n\n\nDeprecated \nexclude_from_schema\n on \nAPIView\n and \napi_view\n decorator. Set \nschema = None\n or \n@schema(None)\n as appropriate. \n#5422\n\n\n\n\nTimezone-aware \nDateTimeField\ns now respect active or default \ntimezone\n during serialization, instead of always using UTC. \n#5435\n\n\nResolves inconsistency whereby instances were serialised with supplied datetime for \ncreate\n but UTC for \nretrieve\n. \n#3732\n\n\nPossible backwards compatibility break\n if you were relying on datetime strings being UTC. Have client interpret datetimes or \nset default or active timezone (docs)\n to UTC if needed.\n\n\n\n\n\n\nRemoved DjangoFilterBackend inline with deprecation policy. Use \ndjango_filters.rest_framework.FilterSet\n and/or \ndjango_filters.rest_framework.DjangoFilterBackend\n instead. \n#5273\n\n\n\n\nDon't strip microseconds from \ntime\n when encoding. Makes consistent with \ndatetime\n.\n \nBC Change\n: Previously only milliseconds were encoded. \n#5440\n\n\nAdded \nSTRICT_JSON\n setting (default \nTrue\n) to raise exception for the extended float values (\nnan\n, \ninf\n, \n-inf\n) accepted by Python's \njson\n module.\n \nBC Change\n: Previously these values would converted to corresponding strings. Set \nSTRICT_JSON\n to \nFalse\n to restore the previous behaviour. \n#5265\n\n\nAdd support for \npage_size\n parameter in CursorPaginator class \n#5250\n\n\nMake \nDEFAULT_PAGINATION_CLASS\n \nNone\n by default.\n \nBC Change\n: If your were \njust\n setting \nPAGE_SIZE\n to enable pagination you will need to add \nDEFAULT_PAGINATION_CLASS\n.\n The previous default was \nrest_framework.pagination.PageNumberPagination\n. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. \n#5170\n\n\nCatch \nAPIException\n from \nget_serializer_fields\n in schema generation. \n#5443\n\n\nAllow custom authentication and permission classes when using \ninclude_docs_urls\n \n#5448\n\n\nDefer translated string evaluation on validators. \n#5452\n\n\nAdded default value for 'detail' param into 'ValidationError' exception \n#5342\n\n\nAdjust schema get_filter_fields rules to match framework \n#5454\n\n\nUpdated test matrix to add Django 2.0 and drop Django 1.8 & 1.9\n \nBC Change\n: This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. \n#5457\n\n\nFixed a deprecation warning in serializers.ModelField \n#5058\n\n\nAdded a more explicit error message when \nget_queryset\n returned \nNone\n \n#5348\n\n\nFix docs for Response \ndata\n description \n#5361\n\n\nFix \npycache\n/.pyc excludes when packaging \n#5373\n\n\nFix default value handling for dotted sources \n#5375\n\n\nEnsure content_type is set when passing empty body to RequestFactory \n#5351\n\n\nFix ErrorDetail Documentation \n#5380\n\n\nAllow optional content in the generic content form \n#5372\n\n\nUpdated supported values for the NullBooleanField \n#5387\n\n\nFix ModelSerializer custom named fields with source on model \n#5388\n\n\nFixed the MultipleFieldLookupMixin documentation example to properly check for object level permission \n#5398\n\n\nUpdate get_object() example in permissions.md \n#5401\n\n\nFix authtoken management command \n#5415\n\n\nFix schema generation markdown \n#5421\n\n\nAllow \nChoiceField.choices\n to be set dynamically \n#5426\n\n\nAdd the project layout to the quickstart \n#5434\n\n\nReuse 'apply_markdown' function in 'render_markdown' templatetag \n#5469\n\n\nAdded links to \ndrf-openapi\n package in docs \n#5470\n\n\nAdded docstrings code highlighting with pygments \n#5462\n\n\nFixed documentation rendering for views named \ndata\n \n#5472\n\n\nDocs: Clarified 'to_internal_value()' validation behavior \n#5466\n\n\nFix missing six.text_type() call on APIException.\nstr\n \n#5476\n\n\nDocument documentation.py \n#5478\n\n\nFix naming collisions in Schema Generation \n#5464\n\n\nCall Django's authenticate function with the request object \n#5295\n\n\nUpdate coreapi JS to 0.1.1 \n#5479\n\n\nHave \nis_list_view\n recognise RetrieveModel\u2026 views \n#5480\n\n\nRemove Django 1.8 & 1.9 compatibility code \n#5481\n\n\nRemove deprecated schema code from DefaultRouter \n#5482\n\n\nRefactor schema generation to allow per-view customisation.\n \nBC Change\n: \nSchemaGenerator.get_serializer_fields\n has been refactored as \nAutoSchema.get_serializer_fields\n and drops the \nview\n argument [#5354][gh5354]\n\n\n\n\n3.6.x series\n\n\n3.6.4\n\n\nDate\n: \n21st August 2017\n\n\n\n\nIgnore any invalidly formed query parameters for OrderingFilter. \n#5131\n\n\nImprove memory footprint when reading large JSON requests. \n#5147\n\n\nFix schema generation for pagination. \n#5161\n\n\nFix exception when \nHTML_CUTOFF\n is set to \nNone\n. \n#5174\n\n\nFix browsable API not supporting \nmultipart/form-data\n correctly. \n#5176\n\n\nFixed \ntest_hyperlinked_related_lookup_url_encoded_exists\n. \n#5179\n\n\nMake sure max_length is in FileField kwargs. \n#5186\n\n\nFix \nlist_route\n & \ndetail_route\n with kwargs contains curly bracket in \nurl_path\n \n#5187\n\n\nAdd Django manage command to create a DRF user Token. \n#5188\n\n\nEnsure API documentation templates do not check for user authentication \n#5162\n\n\nFix special case where OneToOneField is also primary key. \n#5192\n\n\nAdded aria-label and a new region for accessibility purposes in base.html \n#5196\n\n\nQuote nested API parameters in api.js. \n#5214\n\n\nSet ViewSet args/kwargs/request before dispatch. \n#5229\n\n\nAdded unicode support to SlugField. \n#5231\n\n\nFix HiddenField appears in Raw Data form initial content. \n#5259\n\n\nRaise validation error on invalid timezone parsing. \n#5261\n\n\nFix SearchFilter to-many behavior/performance. \n#5264\n\n\nSimplified chained comparisons and minor code fixes. \n#5276\n\n\nRemoteUserAuthentication, docs, and tests. \n#5306\n\n\nRevert \"Cached the field's root and context property\" \n#5313\n\n\nFix introspection of list field in schema. \n#5326\n\n\nFix interactive docs for multiple nested and extra methods. \n#5334\n\n\nFix/remove undefined template var \"schema\" \n#5346\n\n\n\n\n3.6.3\n\n\nDate\n: \n12th May 2017\n\n\n\n\nRaise 404 if a URL lookup results in ValidationError. (\n#5126\n)\n\n\nHonor http_method_names on class based view, when generating API schemas. (\n#5085\n)\n\n\nAllow overridden \nget_limit\n in LimitOffsetPagination to return all records. (\n#4437\n)\n\n\nFix partial update for the ListSerializer. (\n#4222\n)\n\n\nRender JSONField control correctly in browsable API. (\n#4999\n, \n#5042\n)\n\n\nRaise validation errors for invalid datetime in given timezone. (\n#4987\n)\n\n\nSupport restricting doc & schema shortcuts to a subset of urls. (\n#4979\n)\n\n\nResolve SchemaGenerator error with paginators that have no \npage_size\n attribute. (\n#5086\n, \n#3692\n)\n\n\nResolve HyperlinkedRelatedField exception on string with %20 instead of space. (\n#4748\n, \n#5078\n)\n\n\nCustomizable schema generator classes. (\n#5082\n)\n\n\nUpdate existing vary headers in response instead of overwriting them. (\n#5047\n)\n\n\nSupport passing \n.as_view()\n to view instance. (\n#5053\n)\n\n\nUse correct exception handler when settings overridden on a view. (\n#5055\n, \n#5054\n)\n\n\nUpdate Boolean field to support 'yes' and 'no' values. (\n#5038\n)\n\n\nFix unique validator for ChoiceField. (\n#5004\n, \n#5026\n, \n#5028\n)\n\n\nJavaScript cleanups in API Docs. (\n#5001\n)\n\n\nInclude URL path regexs in API schemas where valid. (\n#5014\n)\n\n\nCorrectly set scheme in coreapi TokenAuthentication. (\n#5000\n, \n#4994\n)\n\n\nHEAD requests on ViewSets should not return 405. (\n#4705\n, \n#4973\n, \n#4864\n)\n\n\nSupport usage of 'source' in \nextra_kwargs\n. (\n#4688\n)\n\n\nFix invalid content type for schema.js (\n#4968\n)\n\n\nFix DjangoFilterBackend inheritance issues. (\n#5089\n, \n#5117\n)\n\n\n\n\n3.6.2\n\n\nDate\n: \n10th March 2017\n\n\n\n\nSupport for Safari & IE in API docs. (\n#4959\n, \n#4961\n)\n\n\nAdd missing \nmark_safe\n in API docs template tags. (\n#4952\n, \n#4953\n)\n\n\nAdd missing glyphicon fonts. (\n#4950\n, \n#4951\n)\n\n\nFix One-to-one fields in API docs. (\n#4955\n, \n#4956\n)\n\n\nTest clean ups. (\n#4949\n)\n\n\n\n\n3.6.1\n\n\nDate\n: \n9th March 2017\n\n\n\n\nEnsure \nmarkdown\n dependency is optional. (\n#4947\n)\n\n\n\n\n3.6.0\n\n\nDate\n: \n9th March 2017\n\n\nSee the \nrelease announcement\n.\n\n\n\n\n3.5.x series\n\n\n3.5.4\n\n\nDate\n: \n10th February 2017\n\n\n\n\nAdd max_length and min_length arguments for ListField. (\n#4877\n)\n\n\nAdd per-view custom exception handler support. (\n#4753\n)\n\n\nSupport disabling of declared fields on serializer subclasses. (\n#4764\n)\n\n\nSupport custom view names on \n@list_route\n and \n@detail_route\n endpoints. (\n#4821\n)\n\n\nCorrect labels for fields in login template when custom user model is used. (\n#4841\n)\n\n\nWhitespace fixes for descriptions generated from docstrings. (\n#4759\n, \n#4869\n, \n#4870\n)\n\n\nBetter error reporting when schemas are returned by views without a schema renderer. (\n#4790\n)\n\n\nFix for returned response of \nPUT\n requests when \nprefetch_related\n is used. (\n#4661\n, \n#4668\n)\n\n\nFix for breadcrumb view names. (\n#4750\n)\n\n\nFix for RequestsClient ensuring fully qualified URLs. (\n#4678\n)\n\n\nFix for incorrect behavior of writable-nested fields check in some cases. (\n#4634\n, \n#4669\n)\n\n\nResolve Django deprecation warnings. (\n#4712\n)\n\n\nVarious cleanup of test cases.\n\n\n\n\n3.5.3\n\n\nDate\n: \n7th November 2016\n\n\n\n\nDon't raise incorrect FilterSet deprecation warnings. (\n#4660\n, \n#4643\n, \n#4644\n)\n\n\nSchema generation should not raise 404 when a view permission class does. (\n#4645\n, \n#4646\n)\n\n\nAdd \nautofocus\n support for input controls. (\n#4650\n)\n\n\n\n\n3.5.2\n\n\nDate\n: \n1st November 2016\n\n\n\n\nRestore exception tracebacks in Python 2.7. (\n#4631\n, \n#4638\n)\n\n\nProperly display dicts in the admin console. (\n#4532\n, \n#4636\n)\n\n\nFix is_simple_callable with variable args, kwargs. (\n#4622\n, \n#4602\n)\n\n\nSupport 'on'/'off' literals with BooleanField. (\n#4640\n, \n#4624\n)\n\n\nEnable cursor pagination of value querysets. (\n#4569\n)\n\n\nFix support of get_full_details() for Throttled exceptions. (\n#4627\n)\n\n\nFix FilterSet proxy. (\n#4620\n)\n\n\nMake serializer fields import explicit. (\n#4628\n)\n\n\nDrop redundant requests adapter. (\n#4639\n)\n\n\n\n\n3.5.1\n\n\nDate\n: \n21st October 2016\n\n\n\n\nMake \nrest_framework/compat.py\n imports. (\n#4612\n, \n#4608\n, \n#4601\n)\n\n\nFix bug in schema base path generation. (\n#4611\n, \n#4605\n)\n\n\nFix broken case of ListSerializer with single item. (\n#4609\n, \n#4606\n)\n\n\nRemove bare \nraise\n for Python 3.5 compat. (\n#4600\n)\n\n\n\n\n3.5.0\n\n\nDate\n: \n20th October 2016\n\n\n\n\n3.4.x series\n\n\n3.4.7\n\n\nDate\n: \n21st September 2016\n\n\n\n\nFallback behavior for request parsing when request.POST already accessed. (\n#3951\n, \n#4500\n)\n\n\nFix regression of \nRegexField\n. (\n#4489\n, \n#4490\n, \n#2617\n)\n\n\nMissing comma in \nadmin.html\n causing CSRF error. (\n#4472\n, \n#4473\n)\n\n\nFix response rendering with empty context. (\n#4495\n)\n\n\nFix indentation regression in API listing. (\n#4493\n)\n\n\nFixed an issue where the incorrect value is set to \nResolverMatch.func_name\n of api_view decorated view. (\n#4465\n, \n#4462\n)\n\n\nFix \nAPIClient.get()\n when path contains unicode arguments (\n#4458\n)\n\n\n\n\n3.4.6\n\n\nDate\n: \n23rd August 2016\n\n\n\n\nFix malformed Javascript in browsable API. (\n#4435\n)\n\n\nSkip HiddenField from Schema fields. (\n#4425\n, \n#4429\n)\n\n\nImprove Create to show the original exception traceback. (\n#3508\n)\n\n\nFix \nAdminRenderer\n display of PK only related fields. (\n#4419\n, \n#4423\n)\n\n\n\n\n3.4.5\n\n\nDate\n: \n19th August 2016\n\n\n\n\nImprove debug error handling. (\n#4416\n, \n#4409\n)\n\n\nAllow custom CSRF_HEADER_NAME setting. (\n#4415\n, \n#4410\n)\n\n\nInclude .action attribute on viewsets when generating schemas. (\n#4408\n, \n#4398\n)\n\n\nDo not include request.FILES items in request.POST. (\n#4407\n)\n\n\nFix rendering of checkbox multiple. (\n#4403\n)\n\n\nFix docstring of Field.get_default. (\n#4404\n)\n\n\nReplace utf8 character with its ascii counterpart in README. (\n#4412\n)\n\n\n\n\n3.4.4\n\n\nDate\n: \n12th August 2016\n\n\n\n\nEnsure views are fully initialized when generating schemas. (\n#4373\n, \n#4382\n, \n#4383\n, \n#4279\n, \n#4278\n)\n\n\nAdd form field descriptions to schemas. (\n#4387\n)\n\n\nFix category generation for schema endpoints. (\n#4391\n, \n#4394\n, \n#4390\n, \n#4386\n, \n#4376\n, \n#4329\n)\n\n\nDon't strip empty query params when paginating. (\n#4392\n, \n#4393\n, \n#4260\n)\n\n\nDo not re-run query for empty results with LimitOffsetPagination. (\n#4201\n, \n#4388\n)\n\n\nStricter type validation for CharField. (\n#4380\n, \n#3394\n)\n\n\nRelatedField.choices should preserve non-string values. (\n#4111\n, \n#4379\n, \n#3365\n)\n\n\nTest case for rendering checkboxes in vertical form style. (\n#4378\n, \n#3868\n, \n#3868\n)\n\n\nShow error traceback HTML in browsable API (\n#4042\n, \n#4172\n)\n\n\nFix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. \n#4370\n\n\nAllow \nmax_digits=None\n on DecimalField. (\n#4377\n, \n#4372\n)\n\n\nLimit queryset when rendering relational choices. (\n#4375\n, \n#4122\n, \n#3329\n, \n#3330\n, \n#3877\n)\n\n\nResolve form display with ChoiceField, MultipleChoiceField and non-string choices. (\n#4374\n, \n#4119\n, \n#4121\n, \n#4137\n, \n#4120\n)\n\n\nFix call to TemplateHTMLRenderer.resolve_context() fallback method. (\n#4371\n)\n\n\n\n\n3.4.3\n\n\nDate\n: \n5th August 2016\n\n\n\n\nInclude fallback for users of older TemplateHTMLRenderer internal API. (\n#4361\n)\n\n\n\n\n3.4.2\n\n\nDate\n: \n5th August 2016\n\n\n\n\nInclude kwargs passed to 'as_view' when generating schemas. (\n#4359\n, \n#4330\n, \n#4331\n)\n\n\nAccess \nrequest.user.is_authenticated\n as property not method, under Django 1.10+ (\n#4358\n, \n#4354\n)\n\n\nFilter HEAD out from schemas. (\n#4357\n)\n\n\nextra_kwargs takes precedence over uniqueness kwargs. (\n#4198\n, \n#4199\n, \n#4349\n)\n\n\nCorrect descriptions when tabs are used in code indentation. (\n#4345\n, \n#4347\n)*\n\n\nChange template context generation in TemplateHTMLRenderer. (\n#4236\n)\n\n\nSerializer defaults should not be included in partial updates. (\n#4346\n, \n#3565\n)\n\n\nConsistent behavior & descriptive error from FileUploadParser when filename not included. (\n#4340\n, \n#3610\n, \n#4292\n, \n#4296\n)\n\n\nDecimalField quantizes incoming digitals. (\n#4339\n, \n#4318\n)\n\n\nHandle non-string input for IP fields. (\n#4335\n, \n#4336\n, \n#4338\n)\n\n\nFix leading slash handling when Schema generation includes a root URL. (\n#4332\n)\n\n\nTest cases for DictField with allow_null options. (\n#4348\n)\n\n\nUpdate tests from Django 1.10 beta to Django 1.10. (\n#4344\n)\n\n\n\n\n3.4.1\n\n\nDate\n: \n28th July 2016\n\n\n\n\nAdded \nroot_renderers\n argument to \nDefaultRouter\n. (\n#4323\n, \n#4268\n)\n\n\nAdded \nurl\n and \nschema_url\n arguments. (\n#4321\n, \n#4308\n, \n#4305\n)\n\n\nUnique together checks should apply to read-only fields which have a default. (\n#4316\n, \n#4294\n)\n\n\nSet view.format_kwarg in schema generator. (\n#4293\n, \n#4315\n)\n\n\nFix schema generator for views with \npagination_class = None\n. (\n#4314\n, \n#4289\n)\n\n\nFix schema generator for views with no \nget_serializer_class\n. (\n#4265\n, \n#4285\n)\n\n\nFixes for media type parameters in \nAccept\n and \nContent-Type\n headers. (\n#4287\n, \n#4313\n, \n#4281\n)\n\n\nUse verbose_name instead of object_name in error messages. (\n#4299\n)\n\n\nMinor version update to Twitter Bootstrap. (\n#4307\n)\n\n\nSearchFilter raises error when using with related field. (\n#4302\n, \n#4303\n, \n#4298\n)\n\n\nAdding support for RFC 4918 status codes. (\n#4291\n)\n\n\nAdd LICENSE.md to the built wheel. (\n#4270\n)\n\n\nSerializing \"complex\" field returns None instead of the value since 3.4 (\n#4272\n, \n#4273\n, \n#4288\n)\n\n\n\n\n3.4.0\n\n\nDate\n: \n14th July 2016\n\n\n\n\nDon't strip microseconds in JSON output. (\n#4256\n)\n\n\nTwo slightly different iso 8601 datetime serialization. (\n#4255\n)\n\n\nResolve incorrect inclusion of media type parameters. (\n#4254\n)\n\n\nResponse Content-Type potentially malformed. (\n#4253\n)\n\n\nFix setup.py error on some platforms. (\n#4246\n)\n\n\nMove alternate formats in coreapi into separate packages. (\n#4244\n)\n\n\nAdd localize keyword argument to \nDecimalField\n. (\n#4233\n)\n\n\nFix issues with routers for custom list-route and detail-routes. (\n#4229\n)\n\n\nNamespace versioning with nested namespaces. (\n#4219\n)\n\n\nRobust uniqueness checks. (\n#4217\n)\n\n\nMinor refactoring of \nmust_call_distinct\n. (\n#4215\n)\n\n\nOverridable offset cutoff in CursorPagination. (\n#4212\n)\n\n\nPass through strings as-in with date/time fields. (\n#4196\n)\n\n\nAdd test confirming that required=False is valid on a relational field. (\n#4195\n)\n\n\nIn LimitOffsetPagination \nlimit=0\n should revert to default limit. (\n#4194\n)\n\n\nExclude read_only=True fields from unique_together validation & add docs. (\n#4192\n)\n\n\nHandle bytestrings in JSON. (\n#4191\n)\n\n\nJSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (\n#4187\n)\n\n\nJSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (\n#4185\n)\n\n\nMore robust form rendering in the browsable API. (\n#4181\n)\n\n\nEmpty cases of \n.validated_data\n and \n.errors\n as lists not dicts for ListSerializer. (\n#4180\n)\n\n\nSchemas & client libraries. (\n#4179\n)\n\n\nRemoved \nAUTH_USER_MODEL\n compat property. (\n#4176\n)\n\n\nClean up existing deprecation warnings. (\n#4166\n)\n\n\nDjango 1.10 support. (\n#4158\n)\n\n\nUpdated jQuery version to 1.12.4. (\n#4157\n)\n\n\nMore robust default behavior on OrderingFilter. (\n#4156\n)\n\n\ndescription.py codes and tests removal. (\n#4153\n)\n\n\nWrap guardian.VERSION in tuple. (\n#4149\n)\n\n\nRefine validator for fields with \n kwargs. (\n#4146\n)\n\n\nFix None values representation in childs of ListField, DictField. (\n#4118\n)\n\n\nResolve TimeField representation for midnight value. (\n#4107\n)\n\n\nSet proper status code in AdminRenderer for the redirection after POST/DELETE requests. (\n#4106\n)\n\n\nTimeField render returns None instead of 00:00:00. (\n#4105\n)\n\n\nFix incorrectly named zh-hans and zh-hant locale path. (\n#4103\n)\n\n\nPrevent raising exception when limit is 0. (\n#4098\n)\n\n\nTokenAuthentication: Allow custom keyword in the header. (\n#4097\n)\n\n\nHandle incorrectly padded HTTP basic auth header. (\n#4090\n)\n\n\nLimitOffset pagination crashes Browseable API when limit=0. (\n#4079\n)\n\n\nFixed DecimalField arbitrary precision support. (\n#4075\n)\n\n\nAdded support for custom CSRF cookie names. (\n#4049\n)\n\n\nFix regression introduced by #4035. (\n#4041\n)\n\n\nNo auth view failing permission should raise 403. (\n#4040\n)\n\n\nFix string_types / text_types confusion. (\n#4025\n)\n\n\nDo not list related field choices in OPTIONS requests. (\n#4021\n)\n\n\nFix typo. (\n#4008\n)\n\n\nReorder initializing the view. (\n#4006\n)\n\n\nType error in DjangoObjectPermissionsFilter on Python 3.4. (\n#4005\n)\n\n\nFixed use of deprecated Query.aggregates. (\n#4003\n)\n\n\nFix blank lines around docstrings. (\n#4002\n)\n\n\nFixed admin pagination when limit is 0. (\n#3990\n)\n\n\nOrderingFilter adjustments. (\n#3983\n)\n\n\nNon-required serializer related fields. (\n#3976\n)\n\n\nUsing safer calling way of \"@api_view\" in tutorial. (\n#3971\n)\n\n\nListSerializer doesn't handle unique_together constraints. (\n#3970\n)\n\n\nAdd missing migration file. (\n#3968\n)\n\n\nOrderingFilter\n should call \nget_serializer_class()\n to determine default fields. (\n#3964\n)\n\n\nRemove old Django checks from tests and compat. (\n#3953\n)\n\n\nSupport callable as the value of \ninitial\n for any \nserializer.Field\n. (\n#3943\n)\n\n\nPrevented unnecessary distinct() call in SearchFilter. (\n#3938\n)\n\n\nFix None UUID ForeignKey serialization. (\n#3936\n)\n\n\nDrop EOL Django 1.7. (\n#3933\n)\n\n\nAdd missing space in serializer error message. (\n#3926\n)\n\n\nFixed _force_text_recursive typo. (\n#3908\n)\n\n\nAttempt to address Django 2.0 deprecate warnings related to \nfield.rel\n. (\n#3906\n)\n\n\nFix parsing multipart data using a nested serializer with list. (\n#3820\n)\n\n\nResolving APIs URL to different namespaces. (\n#3816\n)\n\n\nDo not HTML-escape \nhelp_text\n in Browsable API forms. (\n#3812\n)\n\n\nOPTIONS fetches and shows all possible foreign keys in choices field. (\n#3751\n)\n\n\nDjango 1.9 deprecation warnings (\n#3729\n)\n\n\nTest case for #3598 (\n#3710\n)\n\n\nAdding support for multiple values for search filter. (\n#3541\n)\n\n\nUse get_serializer_class in ordering filter. (\n#3487\n)\n\n\nSerializers with many=True should return empty list rather than empty dict. (\n#3476\n)\n\n\nLimitOffsetPagination limit=0 fix. (\n#3444\n)\n\n\nEnable Validators to defer string evaluation and handle new string format. (\n#3438\n)\n\n\nUnique validator is executed and breaks if field is invalid. (\n#3381\n)\n\n\nDo not ignore overridden View.get_view_name() in breadcrumbs. (\n#3273\n)\n\n\nRetry form rendering when rendering with serializer fails. (\n#3164\n)\n\n\nUnique constraint prevents nested serializers from updating. (\n#2996\n)\n\n\nUniqueness validators should not be run for excluded (read_only) fields. (\n#2848\n)\n\n\nUniqueValidator raises exception for nested objects. (\n#2403\n)\n\n\nlookup_type\n is deprecated in favor of \nlookup_expr\n. (\n#4259\n)\n\n\n\n\n\n\n3.3.x series\n\n\n3.3.3\n\n\nDate\n: \n14th March 2016\n.\n\n\n\n\nRemove version string from templates. Thanks to @blag for the report and fixes. (\n#3878\n, \n#3913\n, \n#3912\n)\n\n\nFixes vertical html layout for \nBooleanField\n. Thanks to Mikalai Radchuk for the fix. (\n#3910\n)\n\n\nSilenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. (\n#3903\n)\n\n\nInternationalization for authtoken. Thanks to Michael Nacharov for the fix. (\n#3887\n, \n#3968\n)\n\n\nFix \nToken\n model as \nabstract\n when the authtoken application isn't declared. Thanks to Adam Thomas for the report. (\n#3860\n, \n#3858\n)\n\n\nImprove Markdown version compatibility. Thanks to Michael J. Schultz for the fix. (\n#3604\n, \n#3842\n)\n\n\nQueryParameterVersioning\n does not use \nDEFAULT_VERSION\n setting. Thanks to Brad Montgomery for the fix. (\n#3833\n)\n\n\nAdd an explicit \non_delete\n on the models. Thanks to Mads Jensen for the fix. (\n#3832\n)\n\n\nFix \nDateField.to_representation\n to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. (\n#3819\n)\n\n\nFixed \nTimeField\n not handling string times. Thanks to Areski Belaid for the fix. (\n#3809\n)\n\n\nAvoid updates of \nMeta.extra_kwargs\n. Thanks to Kevin Massey for the report and fix. (\n#3805\n, \n#3804\n)\n\n\nFix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. (\n#3801\n)\n\n\nDocument how to avoid CSRF and missing button issues with \ndjango-crispy-forms\n. Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. (\n#3787\n, \n#3636\n, \n#3637\n)\n\n\nImprove Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. (\n#3786\n, \n#3815\n)\n\n\nImprove authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. (\n#3785\n)\n\n\nFix \nMin/MaxValueValidator\n transfer from a model's \nDecimalField\n. Thanks to Kevin Brown for the fix. (\n#3774\n)\n\n\nImprove HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. (\n#3769\n)\n\n\nFix \nAutoFilterSet\n to inherit from \ndefault_filter_set\n. Thanks to Tom Linford for the fix. (\n#3753\n)\n\n\nFix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. (\n#3739\n)\n\n\nDateTimeField\n does not handle empty values correctly. Thanks to Mick Parker for the report and fix. (\n#3731\n, \n#3726\n)\n\n\nRaise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. (\n#3715\n)\n\n\nAdd missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. (\n#3703\n)\n\n\nRefactored \n_get_reverse_relationships()\n to use correct \nto_field\n. Thanks to Benjamin Phillips for the fix. (\n#3696\n)\n\n\nDocument the use of \nget_queryset\n for \nRelatedField\n. Thanks to Ryan Hiebert for the fix. (\n#3605\n)\n\n\nFix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix (\n#3962\n)\n\n\n\n\n3.3.2\n\n\nDate\n: \n14th December 2015\n.\n\n\n\n\nListField\n enforces input is a list. (\n#3513\n)\n\n\nFix regression hiding raw data form. (\n#3600\n, \n#3578\n)\n\n\nFix Python 3.5 compatibility. (\n#3534\n, \n#3626\n)\n\n\nAllow setting a custom Django Paginator in \npagination.PageNumberPagination\n. (\n#3631\n, \n#3684\n)\n\n\nFix relational fields without \nto_fields\n attribute. (\n#3635\n, \n#3634\n)\n\n\nFix \ntemplate.render\n deprecation warnings for Django 1.9. (\n#3654\n)\n\n\nSort response headers in browsable API renderer. (\n#3655\n)\n\n\nUse related_objects api for Django 1.9+. (\n#3656\n, \n#3252\n)\n\n\nAdd confirm modal when deleting. (\n#3228\n, \n#3662\n)\n\n\nReveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. (\n#3668\n)\n\n\nMake DRF compatible with multi template engine in Django 1.8. (\n#3672\n)\n\n\nUpdate \nNestedBoundField\n to also handle empty string when rendering its form. (\n#3677\n)\n\n\nFix UUID validation to properly catch invalid input types. (\n#3687\n, \n#3679\n)\n\n\nFix caching issues. (\n#3628\n, \n#3701\n)\n\n\nFix Admin and API browser for views without a filter_class. (\n#3705\n, \n#3596\n, \n#3597\n)\n\n\nAdd app_name to rest_framework.urls. (\n#3714\n)\n\n\nImprove authtoken's views to support url versioning. (\n#3718\n, \n#3723\n)\n\n\n\n\n3.3.1\n\n\nDate\n: \n4th November 2015\n.\n\n\n\n\nResolve parsing bug when accessing \nrequest.POST\n (\n#3592\n)\n\n\nCorrectly deal with \nto_field\n referring to primary key. (\n#3593\n)\n\n\nAllow filter HTML to render when no \nfilter_class\n is defined. (\n#3560\n)\n\n\nFix admin rendering issues. (\n#3564\n, \n#3556\n)\n\n\nFix issue with DecimalValidator. (\n#3568\n)\n\n\n\n\n3.3.0\n\n\nDate\n: \n28th October 2015\n.\n\n\n\n\nHTML controls for filters. (\n#3315\n)\n\n\nForms API. (\n#3475\n)\n\n\nAJAX browsable API. (\n#3410\n)\n\n\nAdded JSONField. (\n#3454\n)\n\n\nCorrectly map \nto_field\n when creating \nModelSerializer\n relational fields. (\n#3526\n)\n\n\nInclude keyword arguments when mapping \nFilePathField\n to a serializer field. (\n#3536\n)\n\n\nMap appropriate model \nerror_messages\n on \nModelSerializer\n uniqueness constraints. (\n#3435\n)\n\n\nInclude \nmax_length\n constraint for \nModelSerializer\n fields mapped from TextField. (\n#3509\n)\n\n\nAdded support for Django 1.9. (\n#3450\n, \n#3525\n)\n\n\nRemoved support for Django 1.5 & 1.6. (\n#3421\n, \n#3429\n)\n\n\nRemoved 'south' migrations. (\n#3495\n)\n\n\n\n\n\n\n3.2.x series\n\n\n3.2.5\n\n\nDate\n: \n27th October 2015\n.\n\n\n\n\nEscape \nusername\n in optional logout tag. (\n#3550\n)\n\n\n\n\n3.2.4\n\n\nDate\n: \n21th September 2015\n.\n\n\n\n\nDon't error on missing \nViewSet.search_fields\n attribute. (\n#3324\n, \n#3323\n)\n\n\nFix \nallow_empty\n not working on serializers with \nmany=True\n. (\n#3361\n, \n#3364\n)\n\n\nLet \nDurationField\n accepts integers. (\n#3359\n)\n\n\nMulti-level dictionaries not supported in multipart requests. (\n#3314\n)\n\n\nFix \nListField\n truncation on HTTP PATCH (\n#3415\n, \n#2761\n)\n\n\n\n\n3.2.3\n\n\nDate\n: \n24th August 2015\n.\n\n\n\n\nAdded \nhtml_cutoff\n and \nhtml_cutoff_text\n for limiting select dropdowns. (\n#3313\n)\n\n\nAdded regex style to \nSearchFilter\n. (\n#3316\n)\n\n\nResolve issues with setting blank HTML fields. (\n#3318\n) (\n#3321\n)\n\n\nCorrectly display existing 'select multiple' values in browsable API forms. (\n#3290\n)\n\n\nResolve duplicated validation message for \nIPAddressField\n. ([#3249[gh3249]) (\n#3250\n)\n\n\nFix to ensure admin renderer continues to work when pagination is disabled. (\n#3275\n)\n\n\nResolve error with \nLimitOffsetPagination\n when count=0, offset=0. (\n#3303\n)\n\n\n\n\n3.2.2\n\n\nDate\n: \n13th August 2015\n.\n\n\n\n\nAdd \ndisplay_value()\n method for use when displaying relational field select inputs. (\n#3254\n)\n\n\nFix issue with \nBooleanField\n checkboxes incorrectly displaying as checked. (\n#3258\n)\n\n\nEnsure empty checkboxes properly set \nBooleanField\n to \nFalse\n in all cases. (\n#2776\n)\n\n\nAllow \nWSGIRequest.FILES\n property without raising incorrect deprecated error. (\n#3261\n)\n\n\nResolve issue with rendering nested serializers in forms. (\n#3260\n)\n\n\nRaise an error if user accidentally pass a serializer instance to a response, rather than data. (\n#3241\n)\n\n\n\n\n3.2.1\n\n\nDate\n: \n7th August 2015\n.\n\n\n\n\nFix for relational select widgets rendering without any choices. (\n#3237\n)\n\n\nFix for \n1\n, \n0\n rendering as \ntrue\n, \nfalse\n in the admin interface. \n#3227\n)\n\n\nFix for ListFields with single value in HTML form input. (\n#3238\n)\n\n\nAllow \nrequest.FILES\n for compat with Django's \nHTTPRequest\n class. (\n#3239\n)\n\n\n\n\n3.2.0\n\n\nDate\n: \n6th August 2015\n.\n\n\n\n\nAdd \nAdminRenderer\n. (\n#2926\n)\n\n\nAdd \nFilePathField\n. (\n#1854\n)\n\n\nAdd \nallow_empty\n to \nListField\n. (\n#2250\n)\n\n\nSupport django-guardian 1.3. (\n#3165\n)\n\n\nSupport grouped choices. (\n#3225\n)\n\n\nSupport error forms in browsable API. (\n#3024\n)\n\n\nAllow permission classes to customize the error message. (\n#2539\n)\n\n\nSupport \nsource=\n on hyperlinked fields. (\n#2690\n)\n\n\nListField(allow_null=True)\n now allows null as the list value, not null items in the list. (\n#2766\n)\n\n\nManyToMany()\n maps to \nallow_empty=False\n, \nManyToMany(blank=True)\n maps to \nallow_empty=True\n. (\n#2804\n)\n\n\nSupport custom serialization styles for primary key fields. (\n#2789\n)\n\n\nOPTIONS\n requests support nested representations. (\n#2915\n)\n\n\nSet \nview.action == \"metadata\"\n for viewsets with \nOPTIONS\n requests. (\n#3115\n)\n\n\nSupport \nallow_blank\n on \nUUIDField\n. ([#3130][gh#3130])\n\n\nDo not display view docstrings with 401 or 403 response codes. (\n#3216\n)\n\n\nResolve Django 1.8 deprecation warnings. (\n#2886\n)\n\n\nFix for \nDecimalField\n validation. (\n#3139\n)\n\n\nFix behavior of \nallow_blank=False\n when used with \ntrim_whitespace=True\n. (\n#2712\n)\n\n\nFix issue with some field combinations incorrectly mapping to an invalid \nallow_blank\n argument. (\n#3011\n)\n\n\nFix for output representations with prefetches and modified querysets. (\n#2704\n, \n#2727\n)\n\n\nFix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920)\ngh2920\n.\n\n\nFix \nUnicodeDecodeError\n when invalid characters included in header with \nTokenAuthentication\n. (\n#2928\n)\n\n\nFix transaction rollbacks with \n@non_atomic_requests\n decorator. (\n#3016\n)\n\n\nFix duplicate results issue with Oracle databases using \nSearchFilter\n. (\n#2935\n)\n\n\nFix checkbox alignment and rendering in browsable API forms. (\n#2783\n)\n\n\nFix for unsaved file objects which should use \n\"url\": null\n in the representation. (\n#2759\n)\n\n\nFix field value rendering in browsable API. (\n#2416\n)\n\n\nFix \nHStoreField\n to include \nallow_blank=True\n in \nDictField\n mapping. (\n#2659\n)\n\n\nNumerous other cleanups, improvements to error messaging, private API & minor fixes.\n\n\n\n\n\n\n3.1.x series\n\n\n3.1.3\n\n\nDate\n: \n4th June 2015\n.\n\n\n\n\nAdd \nDurationField\n. (\n#2481\n, \n#2989\n)\n\n\nAdd \nformat\n argument to \nUUIDField\n. (\n#2788\n, \n#3000\n)\n\n\nMultipleChoiceField\n empties incorrectly on a partial update using multipart/form-data (\n#2993\n, \n#2894\n)\n\n\nFix a bug in options related to read-only \nRelatedField\n. (\n#2981\n, \n#2811\n)\n\n\nFix nested serializers with \nunique_together\n relations. (\n#2975\n)\n\n\nAllow unexpected values for \nChoiceField\n/\nMultipleChoiceField\n representations. (\n#2839\n, \n#2940\n)\n\n\nRollback the transaction on error if \nATOMIC_REQUESTS\n is set. (\n#2887\n, \n#2034\n)\n\n\nSet the action on a view when override_method regardless of its None-ness. (\n#2933\n)\n\n\nDecimalField\n accepts \n2E+2\n as 200 and validates decimal place correctly. (\n#2948\n, \n#2947\n)\n\n\nSupport basic authentication with custom \nUserModel\n that change \nusername\n. (\n#2952\n)\n\n\nIPAddressField\n improvements. (\n#2747\n, \n#2618\n, \n#3008\n)\n\n\nImprove \nDecimalField\n for easier subclassing. (\n#2695\n)\n\n\n\n\n3.1.2\n\n\nDate\n: \n13rd May 2015\n.\n\n\n\n\nDateField.to_representation\n can handle str and empty values. (\n#2656\n, \n#2687\n, \n#2869\n)\n\n\nUse default reason phrases from HTTP standard. (\n#2764\n, \n#2763\n)\n\n\nRaise error when \nModelSerializer\n used with abstract model. (\n#2757\n, \n#2630\n)\n\n\nHandle reversal of non-API view_name in \nHyperLinkedRelatedField\n (\n#2724\n, \n#2711\n)\n\n\nDon't require pk strictly for related fields. (\n#2745\n, \n#2754\n)\n\n\nMetadata detects null boolean field type. (\n#2762\n)\n\n\nProper handling of depth in nested serializers. (\n#2798\n)\n\n\nDisplay viewset without paginator. (\n#2807\n)\n\n\nDon't check for deprecated \n.model\n attribute in permissions (\n#2818\n)\n\n\nRestrict integer field to integers and strings. (\n#2835\n, \n#2836\n)\n\n\nImprove \nIntegerField\n to use compiled decimal regex. (\n#2853\n)\n\n\nPrevent empty \nqueryset\n to raise AssertionError. (\n#2862\n)\n\n\nDjangoModelPermissions\n rely on \nget_queryset\n. (\n#2863\n)\n\n\nCheck \nAcceptHeaderVersioning\n with content negotiation in place. (\n#2868\n)\n\n\nAllow \nDjangoObjectPermissions\n to use views that define \nget_queryset\n. (\n#2905\n)\n\n\n\n\n3.1.1\n\n\nDate\n: \n23rd March 2015\n.\n\n\n\n\nSecurity fix\n: Escape tab switching cookie name in browsable API.\n\n\nDisplay input forms in browsable API if \nserializer_class\n is used, even when \nget_serializer\n method does not exist on the view. (\n#2743\n)\n\n\nUse a password input for the AuthTokenSerializer. (\n#2741\n)\n\n\nFix missing anchor closing tag after next button. (\n#2691\n)\n\n\nFix \nlookup_url_kwarg\n handling in viewsets. (\n#2685\n, \n#2591\n)\n\n\nFix problem with importing \nrest_framework.views\n in \napps.py\n (\n#2678\n)\n\n\nLimitOffsetPagination raises \nTypeError\n if PAGE_SIZE not set (\n#2667\n, \n#2700\n)\n\n\nGerman translation for \nmin_value\n field error message references \nmax_value\n. (\n#2645\n)\n\n\nRemove \nMergeDict\n. (\n#2640\n)\n\n\nSupport serializing unsaved models with related fields. (\n#2637\n, \n#2641\n)\n\n\nAllow blank/null on radio.html choices. (\n#2631\n)\n\n\n\n\n3.1.0\n\n\nDate\n: \n5th March 2015\n.\n\n\nFor full details see the \n3.1 release announcement\n.\n\n\n\n\n3.0.x series\n\n\n3.0.5\n\n\nDate\n: \n10th February 2015\n.\n\n\n\n\nFix a bug where \n_closable_objects\n breaks pickling. (\n#1850\n, \n#2492\n)\n\n\nAllow non-standard \nUser\n models with \nThrottling\n. (\n#2524\n)\n\n\nSupport custom \nUser.db_table\n in TokenAuthentication migration. (\n#2479\n)\n\n\nFix misleading \nAttributeError\n tracebacks on \nRequest\n objects. (\n#2530\n, \n#2108\n)\n\n\nManyRelatedField.get_value\n clearing field on partial update. (\n#2475\n)\n\n\nRemoved '.model' shortcut from code. (\n#2486\n)\n\n\nFix \ndetail_route\n and \nlist_route\n mutable argument. (\n#2518\n)\n\n\nPrefetching the user object when getting the token in \nTokenAuthentication\n. (\n#2519\n)\n\n\n\n\n3.0.4\n\n\nDate\n: \n28th January 2015\n.\n\n\n\n\nDjango 1.8a1 support. (\n#2425\n, \n#2446\n, \n#2441\n)\n\n\nAdd \nDictField\n and support Django 1.8 \nHStoreField\n. (\n#2451\n, \n#2106\n)\n\n\nAdd \nUUIDField\n and support Django 1.8 \nUUIDField\n. (\n#2448\n, \n#2433\n, \n#2432\n)\n\n\nBaseRenderer.render\n now raises \nNotImplementedError\n. (\n#2434\n)\n\n\nFix timedelta JSON serialization on Python 2.6. (\n#2430\n)\n\n\nResultDict\n and \nResultList\n now appear as standard dict/list. (\n#2421\n)\n\n\nFix visible \nHiddenField\n in the HTML form of the web browsable API page. (\n#2410\n)\n\n\nUse \nOrderedDict\n for \nRelatedField.choices\n. (\n#2408\n)\n\n\nFix ident format when using \nHTTP_X_FORWARDED_FOR\n. (\n#2401\n)\n\n\nFix invalid key with memcached while using throttling. (\n#2400\n)\n\n\nFix \nFileUploadParser\n with version 3.x. (\n#2399\n)\n\n\nFix the serializer inheritance. (\n#2388\n)\n\n\nFix caching issues with \nReturnDict\n. (\n#2360\n)\n\n\n\n\n3.0.3\n\n\nDate\n: \n8th January 2015\n.\n\n\n\n\nFix \nMinValueValidator\n on \nmodels.DateField\n. (\n#2369\n)\n\n\nFix serializer missing context when pagination is used. (\n#2355\n)\n\n\nNamespaced router URLs are now supported by the \nDefaultRouter\n. (\n#2351\n)\n\n\nrequired=False\n allows omission of value for output. (\n#2342\n)\n\n\nUse textarea input for \nmodels.TextField\n. (\n#2340\n)\n\n\nUse custom \nListSerializer\n for pagination if required. (\n#2331\n, \n#2327\n)\n\n\nBetter behavior with null and '' for blank HTML fields. (\n#2330\n)\n\n\nEnsure fields in \nexclude\n are model fields. (\n#2319\n)\n\n\nFix \nIntegerField\n and \nmax_length\n argument incompatibility. (\n#2317\n)\n\n\nFix the YAML encoder for 3.0 serializers. (\n#2315\n, \n#2283\n)\n\n\nFix the behavior of empty HTML fields. (\n#2311\n, \n#1101\n)\n\n\nFix Metaclass attribute depth ignoring fields attribute. (\n#2287\n)\n\n\nFix \nformat_suffix_patterns\n to work with Django's \ni18n_patterns\n. (\n#2278\n)\n\n\nAbility to customize router URLs for custom actions, using \nurl_path\n. (\n#2010\n)\n\n\nDon't install Django REST Framework as egg. (\n#2386\n)\n\n\n\n\n3.0.2\n\n\nDate\n: \n17th December 2014\n.\n\n\n\n\nEnsure \nrequest.user\n is made available to response middleware. (\n#2155\n)\n\n\nClient.logout()\n also cancels any existing \nforce_authenticate\n. (\n#2218\n, \n#2259\n)\n\n\nExtra assertions and better checks to preventing incorrect serializer API use. (\n#2228\n, \n#2234\n, \n#2262\n, \n#2263\n, \n#2266\n, \n#2267\n, \n#2289\n, \n#2291\n)\n\n\nFixed \nmin_length\n message for \nCharField\n. (\n#2255\n)\n\n\nFix \nUnicodeDecodeError\n, which can occur on serializer \nrepr\n. (\n#2270\n, \n#2279\n)\n\n\nFix empty HTML values when a default is provided. (\n#2280\n, \n#2294\n)\n\n\nFix \nSlugRelatedField\n raising \nUnicodeEncodeError\n when used as a multiple choice input. (\n#2290\n)\n\n\n\n\n3.0.1\n\n\nDate\n: \n11th December 2014\n.\n\n\n\n\nMore helpful error message when the default Serializer \ncreate()\n fails. (\n#2013\n)\n\n\nRaise error when attempting to save serializer if data is not valid. (\n#2098\n)\n\n\nFix \nFileUploadParser\n breaks with empty file names and multiple upload handlers. (\n#2109\n)\n\n\nImprove \nBindingDict\n to support standard dict-functions. (\n#2135\n, \n#2163\n)\n\n\nAdd \nvalidate()\n to \nListSerializer\n. (\n#2168\n, \n#2225\n, \n#2232\n)\n\n\nFix JSONP renderer failing to escape some characters. (\n#2169\n, \n#2195\n)\n\n\nAdd missing default style for \nFileField\n. (\n#2172\n)\n\n\nActions are required when calling \nViewSet.as_view()\n. (\n#2175\n)\n\n\nAdd \nallow_blank\n to \nChoiceField\n. (\n#2184\n, \n#2239\n)\n\n\nCosmetic fixes in the HTML renderer. (\n#2187\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2193\n, \n#2213\n)\n\n\nImprove checks for nested creates and updates. (\n#2194\n, \n#2196\n)\n\n\nvalidated_attrs\n argument renamed to \nvalidated_data\n in \nSerializer\n \ncreate()\n/\nupdate()\n. (\n#2197\n)\n\n\nRemove deprecated code to reflect the dropped Django versions. (\n#2200\n)\n\n\nBetter serializer errors for nested writes. (\n#2202\n, \n#2215\n)\n\n\nFix pagination and custom permissions incompatibility. (\n#2205\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2213\n)\n\n\nAdd missing translation markers for relational fields. (\n#2231\n)\n\n\nImprove field lookup behavior for dicts/mappings. (\n#2244\n, \n#2243\n)\n\n\nOptimized hyperlinked PK. (\n#2242\n)\n\n\n\n\n3.0.0\n\n\nDate\n: 1st December 2014\n\n\nFor full details see the \n3.0 release announcement\n.\n\n\n\n\nFor older release notes, \nplease see the version 2.x documentation\n.", - "title": "Release Notes" - }, - { - "location": "/community/release-notes/#release-notes", - "text": "Release Early, Release Often \u2014 Eric S. Raymond, The Cathedral and the Bazaar .", - "title": "Release Notes" - }, - { - "location": "/community/release-notes/#versioning", - "text": "Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes. Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy . You should read the release notes carefully before upgrading between medium point releases. Major version numbers (x.0.0) are reserved for substantial project milestones.", - "title": "Versioning" - }, - { - "location": "/community/release-notes/#deprecation-policy", - "text": "REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy . The timeline for deprecation of a feature present in version 1.0 would work as follows: Version 1.1 would remain fully backwards compatible with 1.0, but would raise PendingDeprecationWarning warnings if you use the feature that are due to be deprecated. These warnings are silent by default , but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test , you'll be warned of any API changes you need to make. Version 1.2 would escalate these warnings to DeprecationWarning , which is loud by default. Version 1.3 would remove the deprecated bits of API entirely. Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.", - "title": "Deprecation policy" - }, - { - "location": "/community/release-notes/#upgrading", - "text": "To upgrade Django REST framework to the latest version, use pip: pip install -U djangorestframework You can determine your currently installed version using pip show : pip show djangorestframework", - "title": "Upgrading" - }, - { - "location": "/community/release-notes/#39x-series", - "text": "", - "title": "3.9.x series" - }, - { - "location": "/community/release-notes/#390", - "text": "Date : Unreleased Deprecate the Router.register base_name argument in favor of basename . #5990 Deprecate the Router.get_default_base_name method in favor of Router.get_default_basename . #5990", - "title": "3.9.0" - }, - { - "location": "/community/release-notes/#38x-series", - "text": "", - "title": "3.8.x series" - }, - { - "location": "/community/release-notes/#382", - "text": "Date : 6th April 2018 Fix read_only + default unique_together validation. #5922 authtoken.views import coreapi from rest_framework.compat, not directly. #5921 Docs: Add missing argument 'detail' to Route #5920", - "title": "3.8.2" - }, - { - "location": "/community/release-notes/#381", - "text": "Date : 4th April 2018 Use old url_name behavior in route decorators #5915 For list_route and detail_route maintain the old behavior of url_name ,\nbasing it on the url_path instead of the function name.", - "title": "3.8.1" - }, - { - "location": "/community/release-notes/#380", - "text": "Date : 3rd April 2018 Breaking Change : Alter read_only plus default behaviour. #5886 read_only fields will now always be excluded from writable fields. Previously read_only fields with a default value would use the default for create and update operations. In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in\nthe view: def perform_create(self, serializer):\n serializer.save(owner=self.request.user) Alternatively you may override save() or create() or update() on the serialiser as appropriate. Correct allow_null behaviour when required=False #5888 Without an explicit default , allow_null implies a default of null for outgoing serialisation. Previously such\nfields were being skipped when read-only or otherwise not required. Possible backwards compatibility break if you were relying on such fields being excluded from the outgoing\nrepresentation. In order to restore the old behaviour you can override data to exclude the field when None . For example: @property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data Refactor dynamic route generation and improve viewset action introspectibility. #5705 ViewSet s have been provided with new attributes and methods that allow\nit to introspect its set of actions and the details of the current action. Merged list_route and detail_route into a single action decorator. Get all extra actions on a ViewSet with .get_extra_actions() . Extra actions now set the url_name and url_path on the decorated method. url_name is now based on the function name, instead of the url_path ,\n as the path is not always suitable (e.g., capturing arguments in the path). Enable action url reversing through .reverse_action() method (added in 3.7.4) Example reverse call: self.reverse_action(self.custom_action.url_name) Add detail initkwarg to indicate if the current action is operating on a\n collection or a single instance. Additional changes: Deprecated list_route & detail_route in favor of action decorator with detail boolean. Deprecated dynamic list/detail route variants in favor of DynamicRoute with detail boolean. Refactored the router's dynamic route generation. list_route and detail_route maintain the old behavior of url_name ,\n basing it on the url_path instead of the function name. Fix formatting of the 3.7.4 release note #5704 Docs: Update DRF Writable Nested Serializers references #5711 Docs: Fixed typo in auth URLs example. #5713 Improve composite field child errors #5655 Disable HTML inputs for dict/list fields #5702 Fix typo in HostNameVersioning doc #5709 Use rsplit to get module and classname for imports #5712 Formalize URLPatternsTestCase #5703 Add exception translation test #5700 Test staticfiles #5701 Add drf-yasg to documentation and schema 3rd party packages #5720 Remove unused compat._resolve_model() #5733 Drop compat workaround for unsupported Python 3.2 #5734 Prefer iter(dict) over iter(dict.keys()) #5736 Pass python_requires argument to setuptools #5739 Remove unused links from docs #5735 Prefer https protocol for links in docs when available #5729 Add HStoreField, postgres fields tests #5654 Always fully qualify ValidationError in docs #5751 Remove unreachable code from ManualSchema #5766 Allowed customising API documentation code samples #5752 Updated docs to use pip show #5757 Load 'static' instead of 'staticfiles' in templates #5773 Fixed a typo in fields docs #5783 Refer to \"NamespaceVersioning\" instead of \"NamespacedVersioning\" in the documentation #5754 ErrorDetail: add __eq__ / __ne__ and __repr__ #5787 Replace background-attachment: fixed in docs #5777 Make 404 & 403 responses consistent with exceptions.APIException output #5763 Small fix to API documentation: schemas #5796 Fix schema generation for PrimaryKeyRelatedField #5764 Represent serializer DictField as an Object in schema #5765 Added docs example reimplementing ObtainAuthToken #5802 Add schema to the ObtainAuthToken view #5676 Fix request formdata handling #5800 Fix authtoken views imports #5818 Update pytest, isort #5815 #5817 #5894 Fixed active timezone handling for non ISO8601 datetimes. #5833 Made TemplateHTMLRenderer render IntegerField inputs when value is 0 . #5834 Corrected endpoint in tutorial instructions #5835 Add Django Rest Framework Role Filters to Third party packages #5809 Use single copy of static assets. Update jQuery #5823 Changes ternary conditionals to be PEP308 compliant #5827 Added links to 'A Todo List API with React' and 'Blog API' tutorials #5837 Fix comment typo in ModelSerializer #5844 Add admin to installed apps to avoid test failures. #5870 Fixed schema for UUIDField in SimpleMetadata. #5872 Corrected docs on router include with namespaces. #5843 Test using model objects for dotted source default #5880 Allow traversing nullable related fields #5849 Added: Tutorial: Django REST with React (Django 2.0) #5891 Add LimitOffsetPagination.get_count to allow method override #5846 Don't show hidden fields in metadata #5854 Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. #5899 Added generic 500 and 400 JSON error handlers. #5904", - "title": "3.8.0" - }, - { - "location": "/community/release-notes/#37x-series", - "text": "", - "title": "3.7.x series" - }, - { - "location": "/community/release-notes/#377", - "text": "Date : 21st December 2017 Fix typo to include *.mo locale files to packaging. #5697 , #5695", - "title": "3.7.7" - }, - { - "location": "/community/release-notes/#376", - "text": "Date : 21st December 2017 Add missing *.ico icon files to packaging.", - "title": "3.7.6" - }, - { - "location": "/community/release-notes/#375", - "text": "Date : 21st December 2017 Add missing *.woff2 font files to packaging. #5692 Add missing *.mo locale files to packaging. #5695 , #5696", - "title": "3.7.5" - }, - { - "location": "/community/release-notes/#374", - "text": "Date : 20th December 2017 Schema: Extract method for manual_fields processing #5633 Allows for easier customisation of manual_fields processing, for example\nto provide per-method manual fields. AutoSchema adds get_manual_fields ,\nas the intended override point, and a utility method update_fields , to\nhandle by-name field replacement from a list, which, in general, you are not\nexpected to override. Note: AutoSchema.__init__ now ensures manual_fields is a list.\nPreviously may have been stored internally as None . Remove ulrparse compatability shim; use six instead #5579 Drop compat wrapper for TimeDelta.total_seconds() #5577 Clean up all whitespace throughout project #5578 Compat cleanup #5581 Add pygments CSS block in browsable API views #5584 #5587 Remove set_rollback() from compat #5591 Fix request body/POST access #5590 Rename test to reference correct issue #5610 Documentation Fixes #5611 #5612 Remove references to unsupported Django versions in docs and code #5602 Test Serializer exclude for declared fields #5599 Fixed schema generation for filter backends #5613 Minor cleanup for ModelSerializer tests #5598 Reimplement request attribute access w/ __getattr__ #5617 Fixed SchemaJSRenderer renders invalid Javascript #5607 Make Django 2.0 support official/explicit #5619 Perform type check on passed request argument #5618 Fix AttributeError hiding on request authenticators #5600 Update test requirements #5626 Docs: Serializer._declared_fields enable modifying fields on a serializer #5629 Fix packaging #5624 Fix readme rendering for PyPI, add readme build to CI #5625 Update tutorial #5622 Non-required fields with allow_null=True should not imply a default value #5639 Docs: Add allow_null serialization output note #5641 Update to use the Django 2.0 release in tox.ini #5645 Fix Serializer.data for Browsable API rendering when provided invalid data #5646 Docs: Note AutoSchema limitations on bare APIView #5649 Add .basename and .reverse_action() to ViewSet #5648 Docs: Fix typos in serializers documentation #5652 Fix override_settings compat #5668 Add DEFAULT_SCHEMA_CLASS setting #5658 Add docs note re generated BooleanField being required=False #5665 Add 'dist' build #5656 Fix typo in docstring #5678 Docs: Add UNAUTHENTICATED_USER = None note #5679 Update OPTIONS example from \u201cDocumenting Your API\u201d #5680 Docs: Add note on object permissions for FBVs #5681 Docs: Add example to to_representation docs #5682 Add link to Classy DRF in docs #5683 Document ViewSet.action #5685 Fix schema docs typo #5687 Fix URL pattern parsing in schema generation #5689 Add example using source=\u2018*\u2019 to custom field docs. #5688 Fix format_suffix_patterns behavior with Django 2 path() routes #5691", - "title": "3.7.4" - }, - { - "location": "/community/release-notes/#373", - "text": "Date : 6th November 2017 Fix AppRegistryNotReady error from contrib.auth view imports #5567", - "title": "3.7.3" - }, - { - "location": "/community/release-notes/#372", - "text": "Date : 6th November 2017 Fixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. #5510 Add missing import for TextLexer. #5512 Adding examples and documentation for caching #5514 Include date and date-time format for schema generation #5511 Use triple backticks for markdown code blocks #5513 Interactive docs - make bottom sidebar items sticky #5516 Clarify pagination system check #5524 Stop JSONBoundField mangling invalid JSON #5527 Have JSONField render as textarea in Browsable API #5530 Schema: Exclude OPTIONS/HEAD for ViewSet actions #5532 Fix ordering for dotted sources #5533 Fix: Fields with allow_null=True should imply a default serialization value #5518 Ensure Location header is strictly a 'str', not subclass. #5544 Add import to example in api-guide/parsers #5547 Catch OverflowError for \"out of range\" datetimes #5546 Add djangorestframework-rapidjson to third party packages #5549 Increase test coverage for drf_create_token command #5550 Add trove classifier for Python 3.6 support. #5555 Add pip cache support to the Travis CI configuration #5556 Rename [ wheel ] section to [ bdist_wheel ] as the former is legacy #5557 Fix invalid escape sequence deprecation warnings #5560 Add interactive docs error template #5548 Add rounding parameter to DecimalField #5562 Fix all BytesWarning caught during tests #5561 Use dict and set literals instead of calls to dict() and set() #5559 Change ImageField validation pattern, use validators from DjangoImageField #5539 Fix processing unicode symbols in query_string by Python 2 #5552", - "title": "3.7.2" - }, - { - "location": "/community/release-notes/#371", - "text": "Date : 16th October 2017 Fix Interactive documentation always uses false for boolean fields in requests #5492 Improve compatibility with Django 2.0 alpha. #5500 #5503 Improved handling of schema naming collisions #5486 Added additional docs and tests around providing a default value for dotted source fields #5489", - "title": "3.7.1" - }, - { - "location": "/community/release-notes/#370", - "text": "Date : 6th October 2017 Fix DjangoModelPermissions to ensure user authentication before calling the view's get_queryset() method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. #5376 Deprecated exclude_from_schema on APIView and api_view decorator. Set schema = None or @schema(None) as appropriate. #5422 Timezone-aware DateTimeField s now respect active or default timezone during serialization, instead of always using UTC. #5435 Resolves inconsistency whereby instances were serialised with supplied datetime for create but UTC for retrieve . #3732 Possible backwards compatibility break if you were relying on datetime strings being UTC. Have client interpret datetimes or set default or active timezone (docs) to UTC if needed. Removed DjangoFilterBackend inline with deprecation policy. Use django_filters.rest_framework.FilterSet and/or django_filters.rest_framework.DjangoFilterBackend instead. #5273 Don't strip microseconds from time when encoding. Makes consistent with datetime .\n BC Change : Previously only milliseconds were encoded. #5440 Added STRICT_JSON setting (default True ) to raise exception for the extended float values ( nan , inf , -inf ) accepted by Python's json module.\n BC Change : Previously these values would converted to corresponding strings. Set STRICT_JSON to False to restore the previous behaviour. #5265 Add support for page_size parameter in CursorPaginator class #5250 Make DEFAULT_PAGINATION_CLASS None by default.\n BC Change : If your were just setting PAGE_SIZE to enable pagination you will need to add DEFAULT_PAGINATION_CLASS .\n The previous default was rest_framework.pagination.PageNumberPagination . There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. #5170 Catch APIException from get_serializer_fields in schema generation. #5443 Allow custom authentication and permission classes when using include_docs_urls #5448 Defer translated string evaluation on validators. #5452 Added default value for 'detail' param into 'ValidationError' exception #5342 Adjust schema get_filter_fields rules to match framework #5454 Updated test matrix to add Django 2.0 and drop Django 1.8 & 1.9\n BC Change : This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. #5457 Fixed a deprecation warning in serializers.ModelField #5058 Added a more explicit error message when get_queryset returned None #5348 Fix docs for Response data description #5361 Fix pycache /.pyc excludes when packaging #5373 Fix default value handling for dotted sources #5375 Ensure content_type is set when passing empty body to RequestFactory #5351 Fix ErrorDetail Documentation #5380 Allow optional content in the generic content form #5372 Updated supported values for the NullBooleanField #5387 Fix ModelSerializer custom named fields with source on model #5388 Fixed the MultipleFieldLookupMixin documentation example to properly check for object level permission #5398 Update get_object() example in permissions.md #5401 Fix authtoken management command #5415 Fix schema generation markdown #5421 Allow ChoiceField.choices to be set dynamically #5426 Add the project layout to the quickstart #5434 Reuse 'apply_markdown' function in 'render_markdown' templatetag #5469 Added links to drf-openapi package in docs #5470 Added docstrings code highlighting with pygments #5462 Fixed documentation rendering for views named data #5472 Docs: Clarified 'to_internal_value()' validation behavior #5466 Fix missing six.text_type() call on APIException. str #5476 Document documentation.py #5478 Fix naming collisions in Schema Generation #5464 Call Django's authenticate function with the request object #5295 Update coreapi JS to 0.1.1 #5479 Have is_list_view recognise RetrieveModel\u2026 views #5480 Remove Django 1.8 & 1.9 compatibility code #5481 Remove deprecated schema code from DefaultRouter #5482 Refactor schema generation to allow per-view customisation.\n BC Change : SchemaGenerator.get_serializer_fields has been refactored as AutoSchema.get_serializer_fields and drops the view argument [#5354][gh5354]", - "title": "3.7.0" - }, - { - "location": "/community/release-notes/#36x-series", - "text": "", - "title": "3.6.x series" - }, - { - "location": "/community/release-notes/#364", - "text": "Date : 21st August 2017 Ignore any invalidly formed query parameters for OrderingFilter. #5131 Improve memory footprint when reading large JSON requests. #5147 Fix schema generation for pagination. #5161 Fix exception when HTML_CUTOFF is set to None . #5174 Fix browsable API not supporting multipart/form-data correctly. #5176 Fixed test_hyperlinked_related_lookup_url_encoded_exists . #5179 Make sure max_length is in FileField kwargs. #5186 Fix list_route & detail_route with kwargs contains curly bracket in url_path #5187 Add Django manage command to create a DRF user Token. #5188 Ensure API documentation templates do not check for user authentication #5162 Fix special case where OneToOneField is also primary key. #5192 Added aria-label and a new region for accessibility purposes in base.html #5196 Quote nested API parameters in api.js. #5214 Set ViewSet args/kwargs/request before dispatch. #5229 Added unicode support to SlugField. #5231 Fix HiddenField appears in Raw Data form initial content. #5259 Raise validation error on invalid timezone parsing. #5261 Fix SearchFilter to-many behavior/performance. #5264 Simplified chained comparisons and minor code fixes. #5276 RemoteUserAuthentication, docs, and tests. #5306 Revert \"Cached the field's root and context property\" #5313 Fix introspection of list field in schema. #5326 Fix interactive docs for multiple nested and extra methods. #5334 Fix/remove undefined template var \"schema\" #5346", - "title": "3.6.4" - }, - { - "location": "/community/release-notes/#363", - "text": "Date : 12th May 2017 Raise 404 if a URL lookup results in ValidationError. ( #5126 ) Honor http_method_names on class based view, when generating API schemas. ( #5085 ) Allow overridden get_limit in LimitOffsetPagination to return all records. ( #4437 ) Fix partial update for the ListSerializer. ( #4222 ) Render JSONField control correctly in browsable API. ( #4999 , #5042 ) Raise validation errors for invalid datetime in given timezone. ( #4987 ) Support restricting doc & schema shortcuts to a subset of urls. ( #4979 ) Resolve SchemaGenerator error with paginators that have no page_size attribute. ( #5086 , #3692 ) Resolve HyperlinkedRelatedField exception on string with %20 instead of space. ( #4748 , #5078 ) Customizable schema generator classes. ( #5082 ) Update existing vary headers in response instead of overwriting them. ( #5047 ) Support passing .as_view() to view instance. ( #5053 ) Use correct exception handler when settings overridden on a view. ( #5055 , #5054 ) Update Boolean field to support 'yes' and 'no' values. ( #5038 ) Fix unique validator for ChoiceField. ( #5004 , #5026 , #5028 ) JavaScript cleanups in API Docs. ( #5001 ) Include URL path regexs in API schemas where valid. ( #5014 ) Correctly set scheme in coreapi TokenAuthentication. ( #5000 , #4994 ) HEAD requests on ViewSets should not return 405. ( #4705 , #4973 , #4864 ) Support usage of 'source' in extra_kwargs . ( #4688 ) Fix invalid content type for schema.js ( #4968 ) Fix DjangoFilterBackend inheritance issues. ( #5089 , #5117 )", - "title": "3.6.3" - }, - { - "location": "/community/release-notes/#362", - "text": "Date : 10th March 2017 Support for Safari & IE in API docs. ( #4959 , #4961 ) Add missing mark_safe in API docs template tags. ( #4952 , #4953 ) Add missing glyphicon fonts. ( #4950 , #4951 ) Fix One-to-one fields in API docs. ( #4955 , #4956 ) Test clean ups. ( #4949 )", - "title": "3.6.2" - }, - { - "location": "/community/release-notes/#361", - "text": "Date : 9th March 2017 Ensure markdown dependency is optional. ( #4947 )", - "title": "3.6.1" - }, - { - "location": "/community/release-notes/#360", - "text": "Date : 9th March 2017 See the release announcement .", - "title": "3.6.0" - }, - { - "location": "/community/release-notes/#35x-series", - "text": "", - "title": "3.5.x series" - }, - { - "location": "/community/release-notes/#354", - "text": "Date : 10th February 2017 Add max_length and min_length arguments for ListField. ( #4877 ) Add per-view custom exception handler support. ( #4753 ) Support disabling of declared fields on serializer subclasses. ( #4764 ) Support custom view names on @list_route and @detail_route endpoints. ( #4821 ) Correct labels for fields in login template when custom user model is used. ( #4841 ) Whitespace fixes for descriptions generated from docstrings. ( #4759 , #4869 , #4870 ) Better error reporting when schemas are returned by views without a schema renderer. ( #4790 ) Fix for returned response of PUT requests when prefetch_related is used. ( #4661 , #4668 ) Fix for breadcrumb view names. ( #4750 ) Fix for RequestsClient ensuring fully qualified URLs. ( #4678 ) Fix for incorrect behavior of writable-nested fields check in some cases. ( #4634 , #4669 ) Resolve Django deprecation warnings. ( #4712 ) Various cleanup of test cases.", - "title": "3.5.4" - }, - { - "location": "/community/release-notes/#353", - "text": "Date : 7th November 2016 Don't raise incorrect FilterSet deprecation warnings. ( #4660 , #4643 , #4644 ) Schema generation should not raise 404 when a view permission class does. ( #4645 , #4646 ) Add autofocus support for input controls. ( #4650 )", - "title": "3.5.3" - }, - { - "location": "/community/release-notes/#352", - "text": "Date : 1st November 2016 Restore exception tracebacks in Python 2.7. ( #4631 , #4638 ) Properly display dicts in the admin console. ( #4532 , #4636 ) Fix is_simple_callable with variable args, kwargs. ( #4622 , #4602 ) Support 'on'/'off' literals with BooleanField. ( #4640 , #4624 ) Enable cursor pagination of value querysets. ( #4569 ) Fix support of get_full_details() for Throttled exceptions. ( #4627 ) Fix FilterSet proxy. ( #4620 ) Make serializer fields import explicit. ( #4628 ) Drop redundant requests adapter. ( #4639 )", - "title": "3.5.2" - }, - { - "location": "/community/release-notes/#351", - "text": "Date : 21st October 2016 Make rest_framework/compat.py imports. ( #4612 , #4608 , #4601 ) Fix bug in schema base path generation. ( #4611 , #4605 ) Fix broken case of ListSerializer with single item. ( #4609 , #4606 ) Remove bare raise for Python 3.5 compat. ( #4600 )", - "title": "3.5.1" - }, - { - "location": "/community/release-notes/#350", - "text": "Date : 20th October 2016", - "title": "3.5.0" - }, - { - "location": "/community/release-notes/#34x-series", - "text": "", - "title": "3.4.x series" - }, - { - "location": "/community/release-notes/#347", - "text": "Date : 21st September 2016 Fallback behavior for request parsing when request.POST already accessed. ( #3951 , #4500 ) Fix regression of RegexField . ( #4489 , #4490 , #2617 ) Missing comma in admin.html causing CSRF error. ( #4472 , #4473 ) Fix response rendering with empty context. ( #4495 ) Fix indentation regression in API listing. ( #4493 ) Fixed an issue where the incorrect value is set to ResolverMatch.func_name of api_view decorated view. ( #4465 , #4462 ) Fix APIClient.get() when path contains unicode arguments ( #4458 )", - "title": "3.4.7" - }, - { - "location": "/community/release-notes/#346", - "text": "Date : 23rd August 2016 Fix malformed Javascript in browsable API. ( #4435 ) Skip HiddenField from Schema fields. ( #4425 , #4429 ) Improve Create to show the original exception traceback. ( #3508 ) Fix AdminRenderer display of PK only related fields. ( #4419 , #4423 )", - "title": "3.4.6" - }, - { - "location": "/community/release-notes/#345", - "text": "Date : 19th August 2016 Improve debug error handling. ( #4416 , #4409 ) Allow custom CSRF_HEADER_NAME setting. ( #4415 , #4410 ) Include .action attribute on viewsets when generating schemas. ( #4408 , #4398 ) Do not include request.FILES items in request.POST. ( #4407 ) Fix rendering of checkbox multiple. ( #4403 ) Fix docstring of Field.get_default. ( #4404 ) Replace utf8 character with its ascii counterpart in README. ( #4412 )", - "title": "3.4.5" - }, - { - "location": "/community/release-notes/#344", - "text": "Date : 12th August 2016 Ensure views are fully initialized when generating schemas. ( #4373 , #4382 , #4383 , #4279 , #4278 ) Add form field descriptions to schemas. ( #4387 ) Fix category generation for schema endpoints. ( #4391 , #4394 , #4390 , #4386 , #4376 , #4329 ) Don't strip empty query params when paginating. ( #4392 , #4393 , #4260 ) Do not re-run query for empty results with LimitOffsetPagination. ( #4201 , #4388 ) Stricter type validation for CharField. ( #4380 , #3394 ) RelatedField.choices should preserve non-string values. ( #4111 , #4379 , #3365 ) Test case for rendering checkboxes in vertical form style. ( #4378 , #3868 , #3868 ) Show error traceback HTML in browsable API ( #4042 , #4172 ) Fix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. #4370 Allow max_digits=None on DecimalField. ( #4377 , #4372 ) Limit queryset when rendering relational choices. ( #4375 , #4122 , #3329 , #3330 , #3877 ) Resolve form display with ChoiceField, MultipleChoiceField and non-string choices. ( #4374 , #4119 , #4121 , #4137 , #4120 ) Fix call to TemplateHTMLRenderer.resolve_context() fallback method. ( #4371 )", - "title": "3.4.4" - }, - { - "location": "/community/release-notes/#343", - "text": "Date : 5th August 2016 Include fallback for users of older TemplateHTMLRenderer internal API. ( #4361 )", - "title": "3.4.3" - }, - { - "location": "/community/release-notes/#342", - "text": "Date : 5th August 2016 Include kwargs passed to 'as_view' when generating schemas. ( #4359 , #4330 , #4331 ) Access request.user.is_authenticated as property not method, under Django 1.10+ ( #4358 , #4354 ) Filter HEAD out from schemas. ( #4357 ) extra_kwargs takes precedence over uniqueness kwargs. ( #4198 , #4199 , #4349 ) Correct descriptions when tabs are used in code indentation. ( #4345 , #4347 )* Change template context generation in TemplateHTMLRenderer. ( #4236 ) Serializer defaults should not be included in partial updates. ( #4346 , #3565 ) Consistent behavior & descriptive error from FileUploadParser when filename not included. ( #4340 , #3610 , #4292 , #4296 ) DecimalField quantizes incoming digitals. ( #4339 , #4318 ) Handle non-string input for IP fields. ( #4335 , #4336 , #4338 ) Fix leading slash handling when Schema generation includes a root URL. ( #4332 ) Test cases for DictField with allow_null options. ( #4348 ) Update tests from Django 1.10 beta to Django 1.10. ( #4344 )", - "title": "3.4.2" - }, - { - "location": "/community/release-notes/#341", - "text": "Date : 28th July 2016 Added root_renderers argument to DefaultRouter . ( #4323 , #4268 ) Added url and schema_url arguments. ( #4321 , #4308 , #4305 ) Unique together checks should apply to read-only fields which have a default. ( #4316 , #4294 ) Set view.format_kwarg in schema generator. ( #4293 , #4315 ) Fix schema generator for views with pagination_class = None . ( #4314 , #4289 ) Fix schema generator for views with no get_serializer_class . ( #4265 , #4285 ) Fixes for media type parameters in Accept and Content-Type headers. ( #4287 , #4313 , #4281 ) Use verbose_name instead of object_name in error messages. ( #4299 ) Minor version update to Twitter Bootstrap. ( #4307 ) SearchFilter raises error when using with related field. ( #4302 , #4303 , #4298 ) Adding support for RFC 4918 status codes. ( #4291 ) Add LICENSE.md to the built wheel. ( #4270 ) Serializing \"complex\" field returns None instead of the value since 3.4 ( #4272 , #4273 , #4288 )", - "title": "3.4.1" - }, - { - "location": "/community/release-notes/#340", - "text": "Date : 14th July 2016 Don't strip microseconds in JSON output. ( #4256 ) Two slightly different iso 8601 datetime serialization. ( #4255 ) Resolve incorrect inclusion of media type parameters. ( #4254 ) Response Content-Type potentially malformed. ( #4253 ) Fix setup.py error on some platforms. ( #4246 ) Move alternate formats in coreapi into separate packages. ( #4244 ) Add localize keyword argument to DecimalField . ( #4233 ) Fix issues with routers for custom list-route and detail-routes. ( #4229 ) Namespace versioning with nested namespaces. ( #4219 ) Robust uniqueness checks. ( #4217 ) Minor refactoring of must_call_distinct . ( #4215 ) Overridable offset cutoff in CursorPagination. ( #4212 ) Pass through strings as-in with date/time fields. ( #4196 ) Add test confirming that required=False is valid on a relational field. ( #4195 ) In LimitOffsetPagination limit=0 should revert to default limit. ( #4194 ) Exclude read_only=True fields from unique_together validation & add docs. ( #4192 ) Handle bytestrings in JSON. ( #4191 ) JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ( #4187 ) JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ( #4185 ) More robust form rendering in the browsable API. ( #4181 ) Empty cases of .validated_data and .errors as lists not dicts for ListSerializer. ( #4180 ) Schemas & client libraries. ( #4179 ) Removed AUTH_USER_MODEL compat property. ( #4176 ) Clean up existing deprecation warnings. ( #4166 ) Django 1.10 support. ( #4158 ) Updated jQuery version to 1.12.4. ( #4157 ) More robust default behavior on OrderingFilter. ( #4156 ) description.py codes and tests removal. ( #4153 ) Wrap guardian.VERSION in tuple. ( #4149 ) Refine validator for fields with kwargs. ( #4146 ) Fix None values representation in childs of ListField, DictField. ( #4118 ) Resolve TimeField representation for midnight value. ( #4107 ) Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. ( #4106 ) TimeField render returns None instead of 00:00:00. ( #4105 ) Fix incorrectly named zh-hans and zh-hant locale path. ( #4103 ) Prevent raising exception when limit is 0. ( #4098 ) TokenAuthentication: Allow custom keyword in the header. ( #4097 ) Handle incorrectly padded HTTP basic auth header. ( #4090 ) LimitOffset pagination crashes Browseable API when limit=0. ( #4079 ) Fixed DecimalField arbitrary precision support. ( #4075 ) Added support for custom CSRF cookie names. ( #4049 ) Fix regression introduced by #4035. ( #4041 ) No auth view failing permission should raise 403. ( #4040 ) Fix string_types / text_types confusion. ( #4025 ) Do not list related field choices in OPTIONS requests. ( #4021 ) Fix typo. ( #4008 ) Reorder initializing the view. ( #4006 ) Type error in DjangoObjectPermissionsFilter on Python 3.4. ( #4005 ) Fixed use of deprecated Query.aggregates. ( #4003 ) Fix blank lines around docstrings. ( #4002 ) Fixed admin pagination when limit is 0. ( #3990 ) OrderingFilter adjustments. ( #3983 ) Non-required serializer related fields. ( #3976 ) Using safer calling way of \"@api_view\" in tutorial. ( #3971 ) ListSerializer doesn't handle unique_together constraints. ( #3970 ) Add missing migration file. ( #3968 ) OrderingFilter should call get_serializer_class() to determine default fields. ( #3964 ) Remove old Django checks from tests and compat. ( #3953 ) Support callable as the value of initial for any serializer.Field . ( #3943 ) Prevented unnecessary distinct() call in SearchFilter. ( #3938 ) Fix None UUID ForeignKey serialization. ( #3936 ) Drop EOL Django 1.7. ( #3933 ) Add missing space in serializer error message. ( #3926 ) Fixed _force_text_recursive typo. ( #3908 ) Attempt to address Django 2.0 deprecate warnings related to field.rel . ( #3906 ) Fix parsing multipart data using a nested serializer with list. ( #3820 ) Resolving APIs URL to different namespaces. ( #3816 ) Do not HTML-escape help_text in Browsable API forms. ( #3812 ) OPTIONS fetches and shows all possible foreign keys in choices field. ( #3751 ) Django 1.9 deprecation warnings ( #3729 ) Test case for #3598 ( #3710 ) Adding support for multiple values for search filter. ( #3541 ) Use get_serializer_class in ordering filter. ( #3487 ) Serializers with many=True should return empty list rather than empty dict. ( #3476 ) LimitOffsetPagination limit=0 fix. ( #3444 ) Enable Validators to defer string evaluation and handle new string format. ( #3438 ) Unique validator is executed and breaks if field is invalid. ( #3381 ) Do not ignore overridden View.get_view_name() in breadcrumbs. ( #3273 ) Retry form rendering when rendering with serializer fails. ( #3164 ) Unique constraint prevents nested serializers from updating. ( #2996 ) Uniqueness validators should not be run for excluded (read_only) fields. ( #2848 ) UniqueValidator raises exception for nested objects. ( #2403 ) lookup_type is deprecated in favor of lookup_expr . ( #4259 )", - "title": "3.4.0" - }, - { - "location": "/community/release-notes/#33x-series", - "text": "", - "title": "3.3.x series" - }, - { - "location": "/community/release-notes/#333", - "text": "Date : 14th March 2016 . Remove version string from templates. Thanks to @blag for the report and fixes. ( #3878 , #3913 , #3912 ) Fixes vertical html layout for BooleanField . Thanks to Mikalai Radchuk for the fix. ( #3910 ) Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. ( #3903 ) Internationalization for authtoken. Thanks to Michael Nacharov for the fix. ( #3887 , #3968 ) Fix Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. ( #3860 , #3858 ) Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. ( #3604 , #3842 ) QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. ( #3833 ) Add an explicit on_delete on the models. Thanks to Mads Jensen for the fix. ( #3832 ) Fix DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. ( #3819 ) Fixed TimeField not handling string times. Thanks to Areski Belaid for the fix. ( #3809 ) Avoid updates of Meta.extra_kwargs . Thanks to Kevin Massey for the report and fix. ( #3805 , #3804 ) Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. ( #3801 ) Document how to avoid CSRF and missing button issues with django-crispy-forms . Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. ( #3787 , #3636 , #3637 ) Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. ( #3786 , #3815 ) Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. ( #3785 ) Fix Min/MaxValueValidator transfer from a model's DecimalField . Thanks to Kevin Brown for the fix. ( #3774 ) Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. ( #3769 ) Fix AutoFilterSet to inherit from default_filter_set . Thanks to Tom Linford for the fix. ( #3753 ) Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. ( #3739 ) DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. ( #3731 , #3726 ) Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. ( #3715 ) Add missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. ( #3703 ) Refactored _get_reverse_relationships() to use correct to_field . Thanks to Benjamin Phillips for the fix. ( #3696 ) Document the use of get_queryset for RelatedField . Thanks to Ryan Hiebert for the fix. ( #3605 ) Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix ( #3962 )", - "title": "3.3.3" - }, - { - "location": "/community/release-notes/#332", - "text": "Date : 14th December 2015 . ListField enforces input is a list. ( #3513 ) Fix regression hiding raw data form. ( #3600 , #3578 ) Fix Python 3.5 compatibility. ( #3534 , #3626 ) Allow setting a custom Django Paginator in pagination.PageNumberPagination . ( #3631 , #3684 ) Fix relational fields without to_fields attribute. ( #3635 , #3634 ) Fix template.render deprecation warnings for Django 1.9. ( #3654 ) Sort response headers in browsable API renderer. ( #3655 ) Use related_objects api for Django 1.9+. ( #3656 , #3252 ) Add confirm modal when deleting. ( #3228 , #3662 ) Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. ( #3668 ) Make DRF compatible with multi template engine in Django 1.8. ( #3672 ) Update NestedBoundField to also handle empty string when rendering its form. ( #3677 ) Fix UUID validation to properly catch invalid input types. ( #3687 , #3679 ) Fix caching issues. ( #3628 , #3701 ) Fix Admin and API browser for views without a filter_class. ( #3705 , #3596 , #3597 ) Add app_name to rest_framework.urls. ( #3714 ) Improve authtoken's views to support url versioning. ( #3718 , #3723 )", - "title": "3.3.2" - }, - { - "location": "/community/release-notes/#331", - "text": "Date : 4th November 2015 . Resolve parsing bug when accessing request.POST ( #3592 ) Correctly deal with to_field referring to primary key. ( #3593 ) Allow filter HTML to render when no filter_class is defined. ( #3560 ) Fix admin rendering issues. ( #3564 , #3556 ) Fix issue with DecimalValidator. ( #3568 )", - "title": "3.3.1" - }, - { - "location": "/community/release-notes/#330", - "text": "Date : 28th October 2015 . HTML controls for filters. ( #3315 ) Forms API. ( #3475 ) AJAX browsable API. ( #3410 ) Added JSONField. ( #3454 ) Correctly map to_field when creating ModelSerializer relational fields. ( #3526 ) Include keyword arguments when mapping FilePathField to a serializer field. ( #3536 ) Map appropriate model error_messages on ModelSerializer uniqueness constraints. ( #3435 ) Include max_length constraint for ModelSerializer fields mapped from TextField. ( #3509 ) Added support for Django 1.9. ( #3450 , #3525 ) Removed support for Django 1.5 & 1.6. ( #3421 , #3429 ) Removed 'south' migrations. ( #3495 )", - "title": "3.3.0" - }, - { - "location": "/community/release-notes/#32x-series", - "text": "", - "title": "3.2.x series" - }, - { - "location": "/community/release-notes/#325", - "text": "Date : 27th October 2015 . Escape username in optional logout tag. ( #3550 )", - "title": "3.2.5" - }, - { - "location": "/community/release-notes/#324", - "text": "Date : 21th September 2015 . Don't error on missing ViewSet.search_fields attribute. ( #3324 , #3323 ) Fix allow_empty not working on serializers with many=True . ( #3361 , #3364 ) Let DurationField accepts integers. ( #3359 ) Multi-level dictionaries not supported in multipart requests. ( #3314 ) Fix ListField truncation on HTTP PATCH ( #3415 , #2761 )", - "title": "3.2.4" - }, - { - "location": "/community/release-notes/#323", - "text": "Date : 24th August 2015 . Added html_cutoff and html_cutoff_text for limiting select dropdowns. ( #3313 ) Added regex style to SearchFilter . ( #3316 ) Resolve issues with setting blank HTML fields. ( #3318 ) ( #3321 ) Correctly display existing 'select multiple' values in browsable API forms. ( #3290 ) Resolve duplicated validation message for IPAddressField . ([#3249[gh3249]) ( #3250 ) Fix to ensure admin renderer continues to work when pagination is disabled. ( #3275 ) Resolve error with LimitOffsetPagination when count=0, offset=0. ( #3303 )", - "title": "3.2.3" - }, - { - "location": "/community/release-notes/#322", - "text": "Date : 13th August 2015 . Add display_value() method for use when displaying relational field select inputs. ( #3254 ) Fix issue with BooleanField checkboxes incorrectly displaying as checked. ( #3258 ) Ensure empty checkboxes properly set BooleanField to False in all cases. ( #2776 ) Allow WSGIRequest.FILES property without raising incorrect deprecated error. ( #3261 ) Resolve issue with rendering nested serializers in forms. ( #3260 ) Raise an error if user accidentally pass a serializer instance to a response, rather than data. ( #3241 )", - "title": "3.2.2" - }, - { - "location": "/community/release-notes/#321", - "text": "Date : 7th August 2015 . Fix for relational select widgets rendering without any choices. ( #3237 ) Fix for 1 , 0 rendering as true , false in the admin interface. #3227 ) Fix for ListFields with single value in HTML form input. ( #3238 ) Allow request.FILES for compat with Django's HTTPRequest class. ( #3239 )", - "title": "3.2.1" - }, - { - "location": "/community/release-notes/#320", - "text": "Date : 6th August 2015 . Add AdminRenderer . ( #2926 ) Add FilePathField . ( #1854 ) Add allow_empty to ListField . ( #2250 ) Support django-guardian 1.3. ( #3165 ) Support grouped choices. ( #3225 ) Support error forms in browsable API. ( #3024 ) Allow permission classes to customize the error message. ( #2539 ) Support source= on hyperlinked fields. ( #2690 ) ListField(allow_null=True) now allows null as the list value, not null items in the list. ( #2766 ) ManyToMany() maps to allow_empty=False , ManyToMany(blank=True) maps to allow_empty=True . ( #2804 ) Support custom serialization styles for primary key fields. ( #2789 ) OPTIONS requests support nested representations. ( #2915 ) Set view.action == \"metadata\" for viewsets with OPTIONS requests. ( #3115 ) Support allow_blank on UUIDField . ([#3130][gh#3130]) Do not display view docstrings with 401 or 403 response codes. ( #3216 ) Resolve Django 1.8 deprecation warnings. ( #2886 ) Fix for DecimalField validation. ( #3139 ) Fix behavior of allow_blank=False when used with trim_whitespace=True . ( #2712 ) Fix issue with some field combinations incorrectly mapping to an invalid allow_blank argument. ( #3011 ) Fix for output representations with prefetches and modified querysets. ( #2704 , #2727 ) Fix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920) gh2920 . Fix UnicodeDecodeError when invalid characters included in header with TokenAuthentication . ( #2928 ) Fix transaction rollbacks with @non_atomic_requests decorator. ( #3016 ) Fix duplicate results issue with Oracle databases using SearchFilter . ( #2935 ) Fix checkbox alignment and rendering in browsable API forms. ( #2783 ) Fix for unsaved file objects which should use \"url\": null in the representation. ( #2759 ) Fix field value rendering in browsable API. ( #2416 ) Fix HStoreField to include allow_blank=True in DictField mapping. ( #2659 ) Numerous other cleanups, improvements to error messaging, private API & minor fixes.", - "title": "3.2.0" - }, - { - "location": "/community/release-notes/#31x-series", - "text": "", - "title": "3.1.x series" - }, - { - "location": "/community/release-notes/#313", - "text": "Date : 4th June 2015 . Add DurationField . ( #2481 , #2989 ) Add format argument to UUIDField . ( #2788 , #3000 ) MultipleChoiceField empties incorrectly on a partial update using multipart/form-data ( #2993 , #2894 ) Fix a bug in options related to read-only RelatedField . ( #2981 , #2811 ) Fix nested serializers with unique_together relations. ( #2975 ) Allow unexpected values for ChoiceField / MultipleChoiceField representations. ( #2839 , #2940 ) Rollback the transaction on error if ATOMIC_REQUESTS is set. ( #2887 , #2034 ) Set the action on a view when override_method regardless of its None-ness. ( #2933 ) DecimalField accepts 2E+2 as 200 and validates decimal place correctly. ( #2948 , #2947 ) Support basic authentication with custom UserModel that change username . ( #2952 ) IPAddressField improvements. ( #2747 , #2618 , #3008 ) Improve DecimalField for easier subclassing. ( #2695 )", - "title": "3.1.3" - }, - { - "location": "/community/release-notes/#312", - "text": "Date : 13rd May 2015 . DateField.to_representation can handle str and empty values. ( #2656 , #2687 , #2869 ) Use default reason phrases from HTTP standard. ( #2764 , #2763 ) Raise error when ModelSerializer used with abstract model. ( #2757 , #2630 ) Handle reversal of non-API view_name in HyperLinkedRelatedField ( #2724 , #2711 ) Don't require pk strictly for related fields. ( #2745 , #2754 ) Metadata detects null boolean field type. ( #2762 ) Proper handling of depth in nested serializers. ( #2798 ) Display viewset without paginator. ( #2807 ) Don't check for deprecated .model attribute in permissions ( #2818 ) Restrict integer field to integers and strings. ( #2835 , #2836 ) Improve IntegerField to use compiled decimal regex. ( #2853 ) Prevent empty queryset to raise AssertionError. ( #2862 ) DjangoModelPermissions rely on get_queryset . ( #2863 ) Check AcceptHeaderVersioning with content negotiation in place. ( #2868 ) Allow DjangoObjectPermissions to use views that define get_queryset . ( #2905 )", - "title": "3.1.2" - }, - { - "location": "/community/release-notes/#311", - "text": "Date : 23rd March 2015 . Security fix : Escape tab switching cookie name in browsable API. Display input forms in browsable API if serializer_class is used, even when get_serializer method does not exist on the view. ( #2743 ) Use a password input for the AuthTokenSerializer. ( #2741 ) Fix missing anchor closing tag after next button. ( #2691 ) Fix lookup_url_kwarg handling in viewsets. ( #2685 , #2591 ) Fix problem with importing rest_framework.views in apps.py ( #2678 ) LimitOffsetPagination raises TypeError if PAGE_SIZE not set ( #2667 , #2700 ) German translation for min_value field error message references max_value . ( #2645 ) Remove MergeDict . ( #2640 ) Support serializing unsaved models with related fields. ( #2637 , #2641 ) Allow blank/null on radio.html choices. ( #2631 )", - "title": "3.1.1" - }, - { - "location": "/community/release-notes/#310", - "text": "Date : 5th March 2015 . For full details see the 3.1 release announcement .", - "title": "3.1.0" - }, - { - "location": "/community/release-notes/#30x-series", - "text": "", - "title": "3.0.x series" - }, - { - "location": "/community/release-notes/#305", - "text": "Date : 10th February 2015 . Fix a bug where _closable_objects breaks pickling. ( #1850 , #2492 ) Allow non-standard User models with Throttling . ( #2524 ) Support custom User.db_table in TokenAuthentication migration. ( #2479 ) Fix misleading AttributeError tracebacks on Request objects. ( #2530 , #2108 ) ManyRelatedField.get_value clearing field on partial update. ( #2475 ) Removed '.model' shortcut from code. ( #2486 ) Fix detail_route and list_route mutable argument. ( #2518 ) Prefetching the user object when getting the token in TokenAuthentication . ( #2519 )", - "title": "3.0.5" - }, - { - "location": "/community/release-notes/#304", - "text": "Date : 28th January 2015 . Django 1.8a1 support. ( #2425 , #2446 , #2441 ) Add DictField and support Django 1.8 HStoreField . ( #2451 , #2106 ) Add UUIDField and support Django 1.8 UUIDField . ( #2448 , #2433 , #2432 ) BaseRenderer.render now raises NotImplementedError . ( #2434 ) Fix timedelta JSON serialization on Python 2.6. ( #2430 ) ResultDict and ResultList now appear as standard dict/list. ( #2421 ) Fix visible HiddenField in the HTML form of the web browsable API page. ( #2410 ) Use OrderedDict for RelatedField.choices . ( #2408 ) Fix ident format when using HTTP_X_FORWARDED_FOR . ( #2401 ) Fix invalid key with memcached while using throttling. ( #2400 ) Fix FileUploadParser with version 3.x. ( #2399 ) Fix the serializer inheritance. ( #2388 ) Fix caching issues with ReturnDict . ( #2360 )", - "title": "3.0.4" - }, - { - "location": "/community/release-notes/#303", - "text": "Date : 8th January 2015 . Fix MinValueValidator on models.DateField . ( #2369 ) Fix serializer missing context when pagination is used. ( #2355 ) Namespaced router URLs are now supported by the DefaultRouter . ( #2351 ) required=False allows omission of value for output. ( #2342 ) Use textarea input for models.TextField . ( #2340 ) Use custom ListSerializer for pagination if required. ( #2331 , #2327 ) Better behavior with null and '' for blank HTML fields. ( #2330 ) Ensure fields in exclude are model fields. ( #2319 ) Fix IntegerField and max_length argument incompatibility. ( #2317 ) Fix the YAML encoder for 3.0 serializers. ( #2315 , #2283 ) Fix the behavior of empty HTML fields. ( #2311 , #1101 ) Fix Metaclass attribute depth ignoring fields attribute. ( #2287 ) Fix format_suffix_patterns to work with Django's i18n_patterns . ( #2278 ) Ability to customize router URLs for custom actions, using url_path . ( #2010 ) Don't install Django REST Framework as egg. ( #2386 )", - "title": "3.0.3" - }, - { - "location": "/community/release-notes/#302", - "text": "Date : 17th December 2014 . Ensure request.user is made available to response middleware. ( #2155 ) Client.logout() also cancels any existing force_authenticate . ( #2218 , #2259 ) Extra assertions and better checks to preventing incorrect serializer API use. ( #2228 , #2234 , #2262 , #2263 , #2266 , #2267 , #2289 , #2291 ) Fixed min_length message for CharField . ( #2255 ) Fix UnicodeDecodeError , which can occur on serializer repr . ( #2270 , #2279 ) Fix empty HTML values when a default is provided. ( #2280 , #2294 ) Fix SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. ( #2290 )", - "title": "3.0.2" - }, - { - "location": "/community/release-notes/#301", - "text": "Date : 11th December 2014 . More helpful error message when the default Serializer create() fails. ( #2013 ) Raise error when attempting to save serializer if data is not valid. ( #2098 ) Fix FileUploadParser breaks with empty file names and multiple upload handlers. ( #2109 ) Improve BindingDict to support standard dict-functions. ( #2135 , #2163 ) Add validate() to ListSerializer . ( #2168 , #2225 , #2232 ) Fix JSONP renderer failing to escape some characters. ( #2169 , #2195 ) Add missing default style for FileField . ( #2172 ) Actions are required when calling ViewSet.as_view() . ( #2175 ) Add allow_blank to ChoiceField . ( #2184 , #2239 ) Cosmetic fixes in the HTML renderer. ( #2187 ) Raise error if fields on serializer is not a list of strings. ( #2193 , #2213 ) Improve checks for nested creates and updates. ( #2194 , #2196 ) validated_attrs argument renamed to validated_data in Serializer create() / update() . ( #2197 ) Remove deprecated code to reflect the dropped Django versions. ( #2200 ) Better serializer errors for nested writes. ( #2202 , #2215 ) Fix pagination and custom permissions incompatibility. ( #2205 ) Raise error if fields on serializer is not a list of strings. ( #2213 ) Add missing translation markers for relational fields. ( #2231 ) Improve field lookup behavior for dicts/mappings. ( #2244 , #2243 ) Optimized hyperlinked PK. ( #2242 )", - "title": "3.0.1" - }, - { - "location": "/community/release-notes/#300", - "text": "Date : 1st December 2014 For full details see the 3.0 release announcement . For older release notes, please see the version 2.x documentation .", - "title": "3.0.0" - }, - { - "location": "/community/3.8-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.8\n\n\nThe 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying\nthe foundations for future changes.\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\nWe'd like to say thanks in particular our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, and \nRollbar\n.\n\n\n\n\nBreaking Changes\n\n\nAltered the behaviour of \nread_only\n plus \ndefault\n on Field.\n\n\n#5886\n \nread_only\n fields will now \nalways\n be excluded from writable fields.\n\n\nPreviously \nread_only\n fields when combined with a \ndefault\n value would use the \ndefault\n for create and update\noperations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted \nsource\n\nattributes on nullable relations.\n\n\nIn order to maintain the old behaviour you may need to pass the value of \nread_only\n fields when calling \nsave()\n in\nthe view:\n\n\ndef perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n\n\n\nAlternatively you may override \nsave()\n or \ncreate()\n or \nupdate()\n on the serializer as appropriate.\n\n\n\n\nDeprecations\n\n\naction\n decorator replaces \nlist_route\n and \ndetail_route\n\n\n#5705\n \nlist_route\n and \ndetail_route\n have been merge into a single \naction\n decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.\n\n\nBoth \nlist_route\n and \ndetail_route\n are now pending deprecation. They will be deprecated in 3.9 and removed entirely\nin 3.10.\n\n\nThe new \naction\n decorator takes a boolean \ndetail\n argument.\n\n\n\n\nReplace \ndetail_route\n uses with \n@action(detail=True)\n.\n\n\nReplace \nlist_route\n uses with \n@action(detail=False)\n.\n\n\n\n\nexclude_from_schema\n\n\nBoth \nAPIView.exclude_from_schema\n and the \nexclude_from_schema\n argument to the \n@api_view\n decorator are now deprecated. They will be removed entirely in 3.9.\n\n\nFor \nAPIView\n you should instead set a \nschema = None\n attribute on the view class.\n\n\nFor function based views the \n@schema\n decorator can be used to exclude the view from the schema, by using \n@schema(None)\n.\n\n\n\n\nMinor fixes and improvements\n\n\nThere are a large number of minor fixes and improvements in this release. See the \nrelease notes\n page\nfor a complete listing.\n\n\nWhat's next\n\n\nWe're currently working towards moving to using \nOpenAPI\n as our default schema output. We'll also be revisiting our API documentation generation and client libraries.\n\n\nWe're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the \ncoreapi\n and \ncoreschema\n libraries, and instead use \napistar\n for the API documentation generation, schema generation, and API client libraries.", - "title": "3.8 Announcement" - }, - { - "location": "/community/3.8-announcement/#django-rest-framework-38", - "text": "The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying\nthe foundations for future changes.", - "title": "Django REST framework 3.8" - }, - { - "location": "/community/3.8-announcement/#funding", - "text": "If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . We'd like to say thanks in particular our premium backers, Rover , Sentry , Stream , Machinalis , and Rollbar .", - "title": "Funding" - }, - { - "location": "/community/3.8-announcement/#breaking-changes", - "text": "", - "title": "Breaking Changes" - }, - { - "location": "/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field", - "text": "#5886 read_only fields will now always be excluded from writable fields. Previously read_only fields when combined with a default value would use the default for create and update\noperations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted source \nattributes on nullable relations. In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in\nthe view: def perform_create(self, serializer):\n serializer.save(owner=self.request.user) Alternatively you may override save() or create() or update() on the serializer as appropriate.", - "title": "Altered the behaviour of read_only plus default on Field." - }, - { - "location": "/community/3.8-announcement/#deprecations", - "text": "", - "title": "Deprecations" - }, - { - "location": "/community/3.8-announcement/#action-decorator-replaces-list_route-and-detail_route", - "text": "#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions. Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely\nin 3.10. The new action decorator takes a boolean detail argument. Replace detail_route uses with @action(detail=True) . Replace list_route uses with @action(detail=False) .", - "title": "action decorator replaces list_route and detail_route" - }, - { - "location": "/community/3.8-announcement/#exclude_from_schema", - "text": "Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator are now deprecated. They will be removed entirely in 3.9. For APIView you should instead set a schema = None attribute on the view class. For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None) .", - "title": "exclude_from_schema" - }, - { - "location": "/community/3.8-announcement/#minor-fixes-and-improvements", - "text": "There are a large number of minor fixes and improvements in this release. See the release notes page\nfor a complete listing.", - "title": "Minor fixes and improvements" - }, - { - "location": "/community/3.8-announcement/#whats-next", - "text": "We're currently working towards moving to using OpenAPI as our default schema output. We'll also be revisiting our API documentation generation and client libraries. We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the coreapi and coreschema libraries, and instead use apistar for the API documentation generation, schema generation, and API client libraries.", - "title": "What's next" - }, - { - "location": "/community/3.7-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.7\n\n\nThe 3.7 release focuses on improvements to schema generation and the interactive API documentation.\n\n\nThis release has been made possible by \nBayer\n who have sponsored the release.\n\n\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n\n\n\n\n\n\n\nAs well as our release sponsor, we'd like to say thanks in particular our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, and \nRollbar\n.\n\n\n\n\nCustomizing API docs & schema generation.\n\n\nThe schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.\n\n\nIn order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.\n\n\nLet's take a quick look at using the new functionality...\n\n\nThe \nAPIView\n class has a \nschema\n attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the \nAutoSchema\n class.\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior.\n\n\n\nWe can remove a view from the API schema and docs, like so:\n\n\nclass CustomView(APIView):\n schema = None\n\n\n\nIf we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...\n\n\nclass CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ])\n\n\n\nTo ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the \nManualSchema\n class instead...\n\n\nclass CustomView(APIView):\n schema = ManualSchema(fields=[...])\n\n\n\nFor more advanced behaviors you can subclass \nAutoSchema\n to provide for customized schema generation, and apply that to particular views.\n\n\nclass CustomView(APIView):\n schema = CustomizedSchemaGeneration()\n\n\n\nFor full details on the new functionality, please see the \nSchema Documentation\n.\n\n\n\n\nDjango 2.0 support\n\n\nREST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.\n\n\n\n\nMinor fixes and improvements\n\n\nThere are a large number of minor fixes and improvements in this release. See the \nrelease notes\n page for a complete listing.\n\n\nThe number of \nopen tickets against the project\n currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.\n\n\n\n\nDeprecations\n\n\nexclude_from_schema\n\n\nBoth \nAPIView.exclude_from_schema\n and the \nexclude_from_schema\n argument to the \n@api_view\n decorator and now \nPendingDeprecation\n. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.\n\n\nFor \nAPIView\n you should instead set a \nschema = None\n attribute on the view class.\n\n\nFor function based views the \n@schema\n decorator can be used to exclude the view from the schema, by using \n@schema(None)\n.\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.\n\n\nThe functionality remains fully available, but is instead provided in the \ndjango-filter\n package.\n\n\n\n\nWhat's next\n\n\nWe're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.\n\n\nThis will likely be timed so that any REST framework development here ties in with similar work on \nAPI Star\n.", - "title": "3.7 Announcement" - }, - { - "location": "/community/3.7-announcement/#django-rest-framework-37", - "text": "The 3.7 release focuses on improvements to schema generation and the interactive API documentation. This release has been made possible by Bayer who have sponsored the release.", - "title": "Django REST framework 3.7" - }, - { - "location": "/community/3.7-announcement/#funding", - "text": "If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis \n Rollbar As well as our release sponsor, we'd like to say thanks in particular our premium backers, Rover , Sentry , Stream , Machinalis , and Rollbar .", - "title": "Funding" - }, - { - "location": "/community/3.7-announcement/#customizing-api-docs-schema-generation", - "text": "The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view. In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features. Let's take a quick look at using the new functionality... The APIView class has a schema attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the AutoSchema class. from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior. We can remove a view from the API schema and docs, like so: class CustomView(APIView):\n schema = None If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily... class CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ]) To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the ManualSchema class instead... class CustomView(APIView):\n schema = ManualSchema(fields=[...]) For more advanced behaviors you can subclass AutoSchema to provide for customized schema generation, and apply that to particular views. class CustomView(APIView):\n schema = CustomizedSchemaGeneration() For full details on the new functionality, please see the Schema Documentation .", - "title": "Customizing API docs & schema generation." - }, - { - "location": "/community/3.7-announcement/#django-20-support", - "text": "REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.", - "title": "Django 2.0 support" - }, - { - "location": "/community/3.7-announcement/#minor-fixes-and-improvements", - "text": "There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing. The number of open tickets against the project currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.", - "title": "Minor fixes and improvements" - }, - { - "location": "/community/3.7-announcement/#deprecations", - "text": "", - "title": "Deprecations" - }, - { - "location": "/community/3.7-announcement/#exclude_from_schema", - "text": "Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator and now PendingDeprecation . They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9. For APIView you should instead set a schema = None attribute on the view class. For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None) .", - "title": "exclude_from_schema" - }, - { - "location": "/community/3.7-announcement/#djangofilterbackend", - "text": "The DjangoFilterBackend was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework. The functionality remains fully available, but is instead provided in the django-filter package.", - "title": "DjangoFilterBackend" - }, - { - "location": "/community/3.7-announcement/#whats-next", - "text": "We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints. This will likely be timed so that any REST framework development here ties in with similar work on API Star .", - "title": "What's next" - }, - { - "location": "/community/3.6-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.6\n\n\nThe 3.6 release adds two major new features to REST framework.\n\n\n\n\nBuilt-in interactive API documentation support.\n\n\nA new JavaScript client\u00a0library.\n\n\n\n\n\n\nAbove: The interactive API documentation.\n\n\n\n\nFunding\n\n\nThe 3.6 release would not have been possible without our \nbacking from Mozilla\n to the project, and our \ncollaborative funding\u00a0model\n.\n\n\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n \nMicroPyramid\n\n\n\n\n\n\n\n\nMany thanks to all our \nsponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, \nRollbar\n, and \nMicroPyramid\n.\n\n\n\n\nInteractive API documentation\n\n\nREST framework's new API documentation supports a number of features:\n\n\n\n\nLive API interaction.\n\n\nSupport for various authentication schemes.\n\n\nCode snippets for the Python, JavaScript, and Command Line clients.\n\n\n\n\nThe \ncoreapi\n library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The \npygments\n and \nmarkdown\n\nlibraries are optional but recommended.\n\n\nTo install the API documentation, you'll need to include it in your projects URLconf:\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n]\n\n\n\nOnce installed you should see something a little like this:\n\n\n\n\nWe'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations.\n\n\nFor more information on documenting your API endpoints see the \n\"Documenting your API\"\n section.\n\n\n\n\nJavaScript client library\n\n\nThe JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly.\n\n\nHere's a brief example that demonstrates:\n\n\n\n\nLoading the client library and schema.\n\n\nInstantiating an authenticated client.\n\n\nMaking an API request using the client.\n\n\n\n\nindex.html\n\n\n\n \n \n \n \n \n\n\n\n\nThe JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API.\n\n\nThe client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned.\n\n\nFor more details see the \nJavaScript client library documentation\n.\n\n\nAuthentication classes for the Python client library\n\n\nPrevious authentication support in the Python client library was limited to\nallowing users to provide explicit header values.\n\n\nWe now have better support for handling the details of authentication, with\nthe introduction of the \nBasicAuthentication\n, \nTokenAuthentication\n, and\n\nSessionAuthentication\n schemes.\n\n\nYou can include the authentication scheme when instantiating a new client.\n\n\nauth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth)\n\n\n\nFor more information see the \nPython client library documentation\n.\n\n\n\n\nDeprecations\n\n\nUpdating coreapi\n\n\nIf you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)\n\n\nGenerating schemas from Router\n\n\nThe 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as \nschema_title\n, \nschema_url\n and \nschema_renderers\n, have now been escalated to a\n\"deprecated\" warning.\n\n\nInstead of using \nDefaultRouter(schema_title='Example API')\n, you should use the \nget_schema_view()\n function, and include the view explicitly in your URL conf.\n\n\nDjangoFilterBackend\n\n\nThe 3.5 \"pending deprecation\" warning of the built-in \nDjangoFilterBackend\n has now\nbeen escalated to a \"deprecated\" warning.\n\n\nYou should change your imports and REST framework filter settings as follows:\n\n\n\n\nrest_framework.filters.DjangoFilterBackend\n becomes \ndjango_filters.rest_framework.DjangoFilterBackend\n.\n\n\nrest_framework.filters.FilterSet\n becomes \ndjango_filters.rest_framework.FilterSet\n.\n\n\n\n\n\n\nWhat's next\n\n\nThere are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following:\n\n\n\n\nSupport for private API docs, requiring login.\n\n\nFile upload and download support in the JavaScript client & API docs.\n\n\nComprehensive documentation for the JavaScript client library.\n\n\nAutomatically including authentication details in the API doc code snippets.\n\n\nAdding authentication support in the command line client.\n\n\nSupport for loading Swagger and other schemas in the JavaScript client.\n\n\nImproved support for documenting parameter schemas and response schemas.\n\n\nRefining the API documentation interaction modal.\n\n\n\n\nOnce work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", - "title": "3.6 Announcement" - }, - { - "location": "/community/3.6-announcement/#django-rest-framework-36", - "text": "The 3.6 release adds two major new features to REST framework. Built-in interactive API documentation support. A new JavaScript client\u00a0library. Above: The interactive API documentation.", - "title": "Django REST framework 3.6" - }, - { - "location": "/community/3.6-announcement/#funding", - "text": "The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding\u00a0model . If you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis \n Rollbar \n MicroPyramid Many thanks to all our sponsors , and in particular to our premium backers, Rover , Sentry , Stream , Machinalis , Rollbar , and MicroPyramid .", - "title": "Funding" - }, - { - "location": "/community/3.6-announcement/#interactive-api-documentation", - "text": "REST framework's new API documentation supports a number of features: Live API interaction. Support for various authentication schemes. Code snippets for the Python, JavaScript, and Command Line clients. The coreapi library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The pygments and markdown \nlibraries are optional but recommended. To install the API documentation, you'll need to include it in your projects URLconf: from rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n] Once installed you should see something a little like this: We'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations. For more information on documenting your API endpoints see the \"Documenting your API\" section.", - "title": "Interactive API documentation" - }, - { - "location": "/community/3.6-announcement/#javascript-client-library", - "text": "The JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly. Here's a brief example that demonstrates: Loading the client library and schema. Instantiating an authenticated client. Making an API request using the client. index.html \n \n \n \n \n \n The JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API. The client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned. For more details see the JavaScript client library documentation .", - "title": "JavaScript client library" - }, - { - "location": "/community/3.6-announcement/#authentication-classes-for-the-python-client-library", - "text": "Previous authentication support in the Python client library was limited to\nallowing users to provide explicit header values. We now have better support for handling the details of authentication, with\nthe introduction of the BasicAuthentication , TokenAuthentication , and SessionAuthentication schemes. You can include the authentication scheme when instantiating a new client. auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth) For more information see the Python client library documentation .", - "title": "Authentication classes for the Python client library" - }, - { - "location": "/community/3.6-announcement/#deprecations", - "text": "", - "title": "Deprecations" - }, - { - "location": "/community/3.6-announcement/#updating-coreapi", - "text": "If you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)", - "title": "Updating coreapi" - }, - { - "location": "/community/3.6-announcement/#generating-schemas-from-router", - "text": "The 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as schema_title , schema_url and schema_renderers , have now been escalated to a\n\"deprecated\" warning. Instead of using DefaultRouter(schema_title='Example API') , you should use the get_schema_view() function, and include the view explicitly in your URL conf.", - "title": "Generating schemas from Router" - }, - { - "location": "/community/3.6-announcement/#djangofilterbackend", - "text": "The 3.5 \"pending deprecation\" warning of the built-in DjangoFilterBackend has now\nbeen escalated to a \"deprecated\" warning. You should change your imports and REST framework filter settings as follows: rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend . rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet .", - "title": "DjangoFilterBackend" - }, - { - "location": "/community/3.6-announcement/#whats-next", - "text": "There are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following: Support for private API docs, requiring login. File upload and download support in the JavaScript client & API docs. Comprehensive documentation for the JavaScript client library. Automatically including authentication details in the API doc code snippets. Adding authentication support in the command line client. Support for loading Swagger and other schemas in the JavaScript client. Improved support for documenting parameter schemas and response schemas. Refining the API documentation interaction modal. Once work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", - "title": "What's next" - }, - { - "location": "/community/3.5-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.5\n\n\nThe 3.5 release is the second in a planned series that is addressing schema\ngeneration, hypermedia support, API client libraries, and finally realtime support.\n\n\n\n\nFunding\n\n\nThe 3.5 release would not have been possible without our \ncollaborative funding model\n.\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n\n\n\n\n\n\n\nMany thanks to all our \nsponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, and \nMachinalis\n.\n\n\n\n\nImproved schema generation\n\n\nDocstrings on views are now pulled through into schema definitions, allowing\nyou to \nuse the schema definition to document your\u00a0API\n.\n\n\nThere is now also a shortcut function, \nget_schema_view()\n, which makes it easier to\n\nadding schema views\n to your API.\n\n\nFor example, to include a swagger schema to your API, you would do the following:\n\n\n\n\n\n\nRun \npip install django-rest-swagger\n.\n\n\n\n\n\n\nAdd \n'rest_framework_swagger'\n to your \nINSTALLED_APPS\n setting.\n\n\n\n\n\n\nInclude the schema view in your URL conf:\n\n\n\n\n\n\nfrom rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title='Example API',\n renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [\n url(r'^swagger/$', schema_view),\n ...\n]\n\n\n\n\nThere have been a large number of fixes to the schema generation. These should\nresolve issues for anyone using the latest version of the \ndjango-rest-swagger\n\npackage.\n\n\nSome of these changes do affect the resulting schema structure,\nso if you're already using schema generation you should make sure to review\n\nthe deprecation notes\n, particularly if you're currently using\na dynamic client library to interact with your API.\n\n\nFinally, we're also now exposing the schema generation as a\n\npublicly documented API\n, allowing you to more easily\noverride the behaviour.\n\n\nRequests test client\n\n\nYou can now test your project using the \nrequests\n library.\n\n\nThis exposes exactly the same interface as if you were using a standard\nrequests session instance.\n\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n\n\n\nRather than sending any HTTP requests to the network, this interface will\ncoerce all outgoing requests into WSGI, and call into your application directly.\n\n\nCore API client\n\n\nYou can also now test your project by interacting with it using the \ncoreapi\n\nclient library.\n\n\n# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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\nAgain, this will call directly into the application using the WSGI interface,\nrather than making actual network calls.\n\n\nThis is a good option if you are planning for clients to mainly interact with\nyour API using the \ncoreapi\n client library, or some other auto-generated client.\n\n\nLive tests\n\n\nOne interesting aspect of both the \nrequests\n client and the \ncoreapi\n client\nis that they allow you to write tests in such a way that they can also be made\nto run against a live service.\n\n\nBy switching the WSGI based client instances to actual instances of \nrequests.Session\n\nor \ncoreapi.Client\n you can have the test cases make actual network calls.\n\n\nBeing able to write test cases that can exercise your staging or production\nenvironment is a powerful tool. However in order to do this, you'll need to pay\nclose attention to how you handle setup and teardown to ensure a strict isolation\nof test data from other live or staging data.\n\n\nRAML support\n\n\nWe now have preliminary support for \nRAML documentation generation\n.\n\n\n\n\nFurther work on the encoding and documentation generation is planned, in order to\nmake features such as the 'Try it now' support available at a later date.\n\n\nThis work also now means that you can use the Core API client libraries to interact\nwith APIs that expose a RAML specification. The \nRAML codec\n gives some examples of\ninteracting with the Spotify API in this way.\n\n\nValidation codes\n\n\nExceptions raised by REST framework now include short code identifiers.\nWhen used together with our customizable error handling, this now allows you to\nmodify the style of API error messages.\n\n\nAs an example, this allows for the following style of error responses:\n\n\n{\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n}\n\n\n\nThis is particularly useful with validation errors, which use appropriate\ncodes to identify differing kinds of failure...\n\n\n{\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}\n\n\n\nClient upload & download support\n\n\nThe Python \ncoreapi\n client library and the Core API command line tool both\nnow fully support file \nuploads\n and \ndownloads\n.\n\n\n\n\nDeprecations\n\n\nGenerating schemas from Router\n\n\nThe router arguments for generating a schema view, such as \nschema_title\n,\nare now pending deprecation.\n\n\nInstead of using \nDefaultRouter(schema_title='Example API')\n, you should use\nthe \nget_schema_view()\n function, and include the view in your URL conf.\n\n\nMake sure to include the view before your router urls. For example:\n\n\nfrom rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n url('^$', schema_view),\n url(r'^', include(router.urls)),\n]\n\n\n\nSchema path representations\n\n\nThe \n'pk'\n identifier in schema paths is now mapped onto the actually model field\nname by default. This will typically be \n'id'\n.\n\n\nThis gives a better external representation for schemas, with less implementation\ndetail being exposed. It also reflects the behaviour of using a ModelSerializer\nclass with \nfields = '__all__'\n.\n\n\nYou can revert to the previous behaviour by setting \n'SCHEMA_COERCE_PATH_PK': False\n\nin the REST framework settings.\n\n\nSchema action name representations\n\n\nThe internal \nretrieve()\n and \ndestroy()\n method names are now coerced to an\nexternal representation of \nread\n and \ndelete\n.\n\n\nYou can revert to the previous behaviour by setting \n'SCHEMA_COERCE_METHOD_NAMES': {}\n\nin the REST framework settings.\n\n\nDjangoFilterBackend\n\n\nThe functionality of the built-in \nDjangoFilterBackend\n is now completely\nincluded by the \ndjango-filter\n package.\n\n\nYou should change your imports and REST framework filter settings as follows:\n\n\n\n\nrest_framework.filters.DjangoFilterBackend\n becomes \ndjango_filters.rest_framework.DjangoFilterBackend\n.\n\n\nrest_framework.filters.FilterSet\n becomes \ndjango_filters.rest_framework.FilterSet\n.\n\n\n\n\nThe existing imports will continue to work but are now pending deprecation.\n\n\nCoreJSON media type\n\n\nThe media type for \nCoreJSON\n is now \napplication/json+coreapi\n, rather than\nthe previous \napplication/vnd.json+coreapi\n. This brings it more into line with\nother custom media types, such as those used by Swagger and RAML.\n\n\nThe clients currently accept either media type. The old style-media type will\nbe deprecated at a later date.\n\n\nModelSerializer 'fields' and 'exclude'\n\n\nModelSerializer and HyperlinkedModelSerializer must include either a fields\noption, or an exclude option. The \nfields = '__all__'\n shortcut may be used to\nexplicitly include all fields.\n\n\nFailing to set either \nfields\n or \nexclude\n raised a pending deprecation warning\nin version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.", - "title": "3.5 Announcement" - }, - { - "location": "/community/3.5-announcement/#django-rest-framework-35", - "text": "The 3.5 release is the second in a planned series that is addressing schema\ngeneration, hypermedia support, API client libraries, and finally realtime support.", - "title": "Django REST framework 3.5" - }, - { - "location": "/community/3.5-announcement/#funding", - "text": "The 3.5 release would not have been possible without our collaborative funding model .\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis Many thanks to all our sponsors , and in particular to our premium backers, Rover , Sentry , Stream , and Machinalis .", - "title": "Funding" - }, - { - "location": "/community/3.5-announcement/#improved-schema-generation", - "text": "Docstrings on views are now pulled through into schema definitions, allowing\nyou to use the schema definition to document your\u00a0API . There is now also a shortcut function, get_schema_view() , which makes it easier to adding schema views to your API. For example, to include a swagger schema to your API, you would do the following: Run pip install django-rest-swagger . Add 'rest_framework_swagger' to your INSTALLED_APPS setting. Include the schema view in your URL conf: from rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title='Example API',\n renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [\n url(r'^swagger/$', schema_view),\n ...\n] There have been a large number of fixes to the schema generation. These should\nresolve issues for anyone using the latest version of the django-rest-swagger \npackage. Some of these changes do affect the resulting schema structure,\nso if you're already using schema generation you should make sure to review the deprecation notes , particularly if you're currently using\na dynamic client library to interact with your API. Finally, we're also now exposing the schema generation as a publicly documented API , allowing you to more easily\noverride the behaviour.", - "title": "Improved schema generation" - }, - { - "location": "/community/3.5-announcement/#requests-test-client", - "text": "You can now test your project using the requests library. This exposes exactly the same interface as if you were using a standard\nrequests session instance. client = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200 Rather than sending any HTTP requests to the network, this interface will\ncoerce all outgoing requests into WSGI, and call into your application directly.", - "title": "Requests test client" - }, - { - "location": "/community/3.5-announcement/#core-api-client", - "text": "You can also now test your project by interacting with it using the coreapi \nclient library. # Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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'}]) Again, this will call directly into the application using the WSGI interface,\nrather than making actual network calls. This is a good option if you are planning for clients to mainly interact with\nyour API using the coreapi client library, or some other auto-generated client.", - "title": "Core API client" - }, - { - "location": "/community/3.5-announcement/#live-tests", - "text": "One interesting aspect of both the requests client and the coreapi client\nis that they allow you to write tests in such a way that they can also be made\nto run against a live service. By switching the WSGI based client instances to actual instances of requests.Session \nor coreapi.Client you can have the test cases make actual network calls. Being able to write test cases that can exercise your staging or production\nenvironment is a powerful tool. However in order to do this, you'll need to pay\nclose attention to how you handle setup and teardown to ensure a strict isolation\nof test data from other live or staging data.", - "title": "Live tests" - }, - { - "location": "/community/3.5-announcement/#raml-support", - "text": "We now have preliminary support for RAML documentation generation . Further work on the encoding and documentation generation is planned, in order to\nmake features such as the 'Try it now' support available at a later date. This work also now means that you can use the Core API client libraries to interact\nwith APIs that expose a RAML specification. The RAML codec gives some examples of\ninteracting with the Spotify API in this way.", - "title": "RAML support" - }, - { - "location": "/community/3.5-announcement/#validation-codes", - "text": "Exceptions raised by REST framework now include short code identifiers.\nWhen used together with our customizable error handling, this now allows you to\nmodify the style of API error messages. As an example, this allows for the following style of error responses: {\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n} This is particularly useful with validation errors, which use appropriate\ncodes to identify differing kinds of failure... {\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}", - "title": "Validation codes" - }, - { - "location": "/community/3.5-announcement/#client-upload-download-support", - "text": "The Python coreapi client library and the Core API command line tool both\nnow fully support file uploads and downloads .", - "title": "Client upload & download support" - }, - { - "location": "/community/3.5-announcement/#deprecations", - "text": "", - "title": "Deprecations" - }, - { - "location": "/community/3.5-announcement/#generating-schemas-from-router", - "text": "The router arguments for generating a schema view, such as schema_title ,\nare now pending deprecation. Instead of using DefaultRouter(schema_title='Example API') , you should use\nthe get_schema_view() function, and include the view in your URL conf. Make sure to include the view before your router urls. For example: from rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n url('^$', schema_view),\n url(r'^', include(router.urls)),\n]", - "title": "Generating schemas from Router" - }, - { - "location": "/community/3.5-announcement/#schema-path-representations", - "text": "The 'pk' identifier in schema paths is now mapped onto the actually model field\nname by default. This will typically be 'id' . This gives a better external representation for schemas, with less implementation\ndetail being exposed. It also reflects the behaviour of using a ModelSerializer\nclass with fields = '__all__' . You can revert to the previous behaviour by setting 'SCHEMA_COERCE_PATH_PK': False \nin the REST framework settings.", - "title": "Schema path representations" - }, - { - "location": "/community/3.5-announcement/#schema-action-name-representations", - "text": "The internal retrieve() and destroy() method names are now coerced to an\nexternal representation of read and delete . You can revert to the previous behaviour by setting 'SCHEMA_COERCE_METHOD_NAMES': {} \nin the REST framework settings.", - "title": "Schema action name representations" - }, - { - "location": "/community/3.5-announcement/#djangofilterbackend", - "text": "The functionality of the built-in DjangoFilterBackend is now completely\nincluded by the django-filter package. You should change your imports and REST framework filter settings as follows: rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend . rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet . The existing imports will continue to work but are now pending deprecation.", - "title": "DjangoFilterBackend" - }, - { - "location": "/community/3.5-announcement/#corejson-media-type", - "text": "The media type for CoreJSON is now application/json+coreapi , rather than\nthe previous application/vnd.json+coreapi . This brings it more into line with\nother custom media types, such as those used by Swagger and RAML. The clients currently accept either media type. The old style-media type will\nbe deprecated at a later date.", - "title": "CoreJSON media type" - }, - { - "location": "/community/3.5-announcement/#modelserializer-fields-and-exclude", - "text": "ModelSerializer and HyperlinkedModelSerializer must include either a fields\noption, or an exclude option. The fields = '__all__' shortcut may be used to\nexplicitly include all fields. Failing to set either fields or exclude raised a pending deprecation warning\nin version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.", - "title": "ModelSerializer 'fields' and 'exclude'" - }, - { - "location": "/community/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 & 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 & client support.\n\n\nBuilt-in support in \ncoreapi\n.\n\n\n\n\n\n\nSwagger / OpenAPI\n\n\nSchema generation & client support.\n\n\nThe \nopenapi-codec\n package.\n\n\n\n\n\n\nJSON Hyper-Schema\n\n\nCurrently 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 & 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" - }, - { - "location": "/community/3.4-announcement/#django-rest-framework-34", - "text": "The 3.4 release is the first in a planned series that will be addressing schema\ngeneration, hypermedia support, API clients, and finally realtime support.", - "title": "Django REST framework 3.4" - }, - { - "location": "/community/3.4-announcement/#funding", - "text": "The 3.4 release has been made possible a recent Mozilla grant , and by our collaborative funding model . 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 signing up for a paid plan . The 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. Every single sign-up makes a significant impact. \n Rover.com \n Sentry \n Stream Many thanks to all our awesome sponsors , and in particular to our premium backers, Rover , Sentry , and Stream .", - "title": "Funding" - }, - { - "location": "/community/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 Currently 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" - }, - { - "location": "/community/3.4-announcement/#supported-versions", - "text": "The 3.4.0 release adds support for Django 1.10. The following versions of Python and Django are now supported: Django versions 1.8, 1.9, and 1.10. Python versions 2.7, 3.2(*), 3.3(*), 3.4, 3.5. (*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.", - "title": "Supported versions" - }, - { - "location": "/community/3.4-announcement/#deprecations-and-changes", - "text": "The 3.4 release includes very limited deprecation or behavioral changes, and\nshould present a straightforward upgrade.", - "title": "Deprecations and changes" - }, - { - "location": "/community/3.4-announcement/#use-fields-or-exclude-on-serializer-classes", - "text": "The 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: ModelSerializer and HyperlinkedModelSerializer should include either a fields \noption, or an exclude option. The fields = '__all__' shortcut may be used\nto explicitly include all fields.", - "title": "Use fields or exclude on serializer classes." - }, - { - "location": "/community/3.4-announcement/#microsecond-precision-when-returning-time-or-datetime", - "text": "Using the default JSON renderer and directly returning a datetime or time \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 serializers.DateTimeField and serializers.TimeField . This change does not affect the default behavior when using serializers ,\nwhich is to serialize datetime and time instances into strings with\nmicrosecond precision. The serializer behavior can be modified if needed, using the DATETIME_FORMAT \nand TIME_FORMAT settings. The renderer behavior can be modified by setting a custom encoder_class \nattribute on a JSONRenderer subclass.", - "title": "Microsecond precision when returning time or datetime." - }, - { - "location": "/community/3.4-announcement/#relational-choices-no-longer-displayed-in-options-requests", - "text": "Making an OPTIONS request to views that have a serializer choice field\nwill result in a list of the available choices being returned in the response. In 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. In order to minimise exposed information the behavior now is to not return\nchoices information for relational fields. If you want to override this new behavior you'll need to implement a custom\nmetadata class . See issue #3751 for more information on this behavioral change.", - "title": "Relational choices no longer displayed in OPTIONS requests." - }, - { - "location": "/community/3.4-announcement/#other-improvements", - "text": "This release includes further work from a huge number of pull requests and issues . Many 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. The full set of itemized release notes are available here .", - "title": "Other improvements" - }, - { - "location": "/community/3.3-announcement/", - "text": "Django REST framework 3.3\n\n\nThe 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding \nthank you\n to all our wonderful sponsors and supporters.\n\n\nThe amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.\n\n\nIn order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow \n@_tomchristie\n to keep up to date with these announcements, and be among the first set of sign ups.\n\n\nWe strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.\n\n\n\n\nRelease notes\n\n\nSignificant new functionality in the 3.3 release includes:\n\n\n\n\nFilters presented as HTML controls in the browsable API.\n\n\nA \nforms API\n, allowing serializers to be rendered as HTML forms.\n\n\nDjango 1.9 support.\n\n\nA \nJSONField\n serializer field\n, corresponding to Django 1.9's Postgres \nJSONField\n model field.\n\n\nBrowsable API support \nvia AJAX\n, rather than server side request overloading.\n\n\n\n\n\n\nExample of the new filter controls\n\n\n\n\nSupported versions\n\n\nThis release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.\n\n\nThis brings our supported versions into line with Django's \ncurrently supported versions\n\n\nDeprecations\n\n\nThe AJAX based support for the browsable API means that there are a number of internal cleanups in the \nrequest\n class. For the vast majority of developers this should largely remain transparent:\n\n\n\n\nTo support form based \nPUT\n and \nDELETE\n, or to support form content types such as JSON, you should now use the \nAJAX forms\n javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.\n\n\nThe \naccept\n query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to \nuse a custom content negotiation class\n.\n\n\nThe custom \nHTTP_X_HTTP_METHOD_OVERRIDE\n header is no longer supported by default. If you require it then you'll need to \nuse custom middleware\n.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nThe \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes should now include either a \nfields\n or \nexclude\n option, although the \nfields = '__all__'\n shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings \nModelSerializer\n more closely in line with Django's \nModelForm\n behavior.", - "title": "3.3 Announcement" - }, - { - "location": "/community/3.3-announcement/#django-rest-framework-33", - "text": "The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding thank you to all our wonderful sponsors and supporters. The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project. In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow @_tomchristie to keep up to date with these announcements, and be among the first set of sign ups. We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.", - "title": "Django REST framework 3.3" - }, - { - "location": "/community/3.3-announcement/#release-notes", - "text": "Significant new functionality in the 3.3 release includes: Filters presented as HTML controls in the browsable API. A forms API , allowing serializers to be rendered as HTML forms. Django 1.9 support. A JSONField serializer field , corresponding to Django 1.9's Postgres JSONField model field. Browsable API support via AJAX , rather than server side request overloading. Example of the new filter controls", - "title": "Release notes" - }, - { - "location": "/community/3.3-announcement/#supported-versions", - "text": "This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required. This brings our supported versions into line with Django's currently supported versions", - "title": "Supported versions" - }, - { - "location": "/community/3.3-announcement/#deprecations", - "text": "The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent: To support form based PUT and DELETE , or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. The accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class . The custom HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware . The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. view.paginate_by - Use paginator.page_size instead. view.page_query_param - Use paginator.page_query_param instead. view.paginate_by_param - Use paginator.page_size_query_param instead. view.max_paginate_by - Use paginator.max_page_size instead. settings.PAGINATE_BY - Use paginator.page_size instead. settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead. settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead. The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.", - "title": "Deprecations" - }, - { - "location": "/community/3.2-announcement/", - "text": "Django REST framework 3.2\n\n\nThe 3.2 release is the first version to include an admin interface for the browsable API.\n\n\n\n\nThis interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing \nBrowsableAPIRenderer\n, or used together with it, allowing you to switch between the two styles as required.\n\n\nWe've also fixed a huge number of issues, and made numerous cleanups and improvements.\n\n\nOver the course of the 3.1.x series we've \nresolved nearly 600 tickets\n on our GitHub issue tracker. This means we're currently running at a rate of \nclosing around 100 issues or pull requests per month\n.\n\n\nNone of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking \na look through our sponsors\n and finding out who's hiring.\n\n\nAdminRenderer\n\n\nTo include \nAdminRenderer\n simply add it to your settings:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n\n\n\nThere are some limitations to the \nAdminRenderer\n, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.\n\n\nAlso note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.\n\n\nThe idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.\n\n\nSupported versions\n\n\nThis release drops support for Django 1.4.\n\n\nOur supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.\n\n\nDeprecations\n\n\nThere are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.\n\n\n\n\nrequest.DATA\n was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of \nrequest.data\n instead.\n\n\nrequest.QUERY_PARAMS\n was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of \nrequest.query_params\n instead.\n\n\nThe following \nModelSerializer.Meta\n options have now been removed: \nwrite_only_fields\n, \nview_name\n, \nlookup_field\n. Use the more general \nextra_kwargs\n option instead.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nModifications to list behaviors\n\n\nThere are a couple of bug fixes that are worth calling out as they introduce differing behavior.\n\n\nThese are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.\n\n\nManyToMany fields and blank=True\n\n\nWe've now added an \nallow_empty\n argument, which can be used with \nListSerializer\n, or with \nmany=True\n relationships. This is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nAs a follow-up to this we are now able to properly mirror the behavior of Django's \nModelForm\n with respect to how many-to-many fields are validated.\n\n\nPreviously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has \nblank=True\n set.\n\n\nHere's what the mapping looks like in practice:\n\n\n\n\nmodels.ManyToManyField()\n \u2192 \nserializers.PrimaryKeyRelatedField(many=True, allow_empty=False)\n\n\nmodels.ManyToManyField(blank=True)\n \u2192 \nserializers.PrimaryKeyRelatedField(many=True)\n\n\n\n\nThe upshot is this: If you have many to many fields in your models, then make sure you've included the argument \nblank=True\n if you want to allow empty inputs in the equivalent \nModelSerializer\n fields.\n\n\nList fields and allow_null\n\n\nWhen using \nallow_null\n with \nListField\n or a nested \nmany=True\n serializer the previous behavior was to allow \nnull\n values as items in the list. The behavior is now to allow \nnull\n values instead of the list.\n\n\nFor example, take the following field:\n\n\nNestedSerializer(many=True, allow_null=True)\n\n\n\nPreviously the validation behavior would be:\n\n\n\n\n[{\u2026}, null, {\u2026}]\n is \nvalid\n.\n\n\nnull\n is \ninvalid\n.\n\n\n\n\nOur validation behavior as of 3.2.0 is now:\n\n\n\n\n[{\u2026}, null, {\u2026}]\n is \ninvalid\n.\n\n\nnull\n is \nvalid\n.\n\n\n\n\nIf you want to allow \nnull\n child items, you'll need to instead specify \nallow_null\n on the child class, using an explicit \nListField\n instead of \nmany=True\n. For example:\n\n\nListField(child=NestedSerializer(allow_null=True))\n\n\n\nWhat's next?\n\n\nThe 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.\n\n\nThis release is planned to include:\n\n\n\n\nSearch and filtering controls in the browsable API and admin interface.\n\n\nImprovements and public API for the admin interface.\n\n\nImprovements and public API for our templated HTML forms and fields.\n\n\nNested object and list support in HTML forms.\n\n\n\n\nThanks once again to all our sponsors and supporters.", - "title": "3.2 Announcement" - }, - { - "location": "/community/3.2-announcement/#django-rest-framework-32", - "text": "The 3.2 release is the first version to include an admin interface for the browsable API. This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing BrowsableAPIRenderer , or used together with it, allowing you to switch between the two styles as required. We've also fixed a huge number of issues, and made numerous cleanups and improvements. Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month . None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.", - "title": "Django REST framework 3.2" - }, - { - "location": "/community/3.2-announcement/#adminrenderer", - "text": "To include AdminRenderer simply add it to your settings: REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n} There are some limitations to the AdminRenderer , in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those. Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates. The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.", - "title": "AdminRenderer" - }, - { - "location": "/community/3.2-announcement/#supported-versions", - "text": "This release drops support for Django 1.4. Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.", - "title": "Supported versions" - }, - { - "location": "/community/3.2-announcement/#deprecations", - "text": "There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy. request.DATA was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.data instead. request.QUERY_PARAMS was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.query_params instead. The following ModelSerializer.Meta options have now been removed: write_only_fields , view_name , lookup_field . Use the more general extra_kwargs option instead. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors. view.paginate_by - Use paginator.page_size instead. view.page_query_param - Use paginator.page_query_param instead. view.paginate_by_param - Use paginator.page_size_query_param instead. view.max_paginate_by - Use paginator.max_page_size instead. settings.PAGINATE_BY - Use paginator.page_size instead. settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead. settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.", - "title": "Deprecations" - }, - { - "location": "/community/3.2-announcement/#modifications-to-list-behaviors", - "text": "There are a couple of bug fixes that are worth calling out as they introduce differing behavior. These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.", - "title": "Modifications to list behaviors" - }, - { - "location": "/community/3.2-announcement/#manytomany-fields-and-blanktrue", - "text": "We've now added an allow_empty argument, which can be used with ListSerializer , or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input. As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated. Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set. Here's what the mapping looks like in practice: models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False) models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True) The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.", - "title": "ManyToMany fields and blank=True" - }, - { - "location": "/community/3.2-announcement/#list-fields-and-allow_null", - "text": "When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list. For example, take the following field: NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: [{\u2026}, null, {\u2026}] is valid . null is invalid . Our validation behavior as of 3.2.0 is now: [{\u2026}, null, {\u2026}] is invalid . null is valid . If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True . For example: ListField(child=NestedSerializer(allow_null=True))", - "title": "List fields and allow_null" - }, - { - "location": "/community/3.2-announcement/#whats-next", - "text": "The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release. This release is planned to include: Search and filtering controls in the browsable API and admin interface. Improvements and public API for the admin interface. Improvements and public API for our templated HTML forms and fields. Nested object and list support in HTML forms. Thanks once again to all our sponsors and supporters.", - "title": "What's next?" - }, - { - "location": "/community/3.1-announcement/", - "text": "Django REST framework 3.1\n\n\nThe 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.\n\n\nSome highlights include:\n\n\n\n\nA super-smart cursor pagination scheme.\n\n\nAn improved pagination API, supporting header or in-body pagination styles.\n\n\nPagination controls rendering in the browsable API.\n\n\nBetter support for API versioning.\n\n\nBuilt-in internationalization support.\n\n\nSupport for Django 1.8's \nHStoreField\n and \nArrayField\n.\n\n\n\n\n\n\nPagination\n\n\nThe pagination API has been improved, making it both easier to use, and more powerful.\n\n\nA guide to the headline features follows. For full details, see \nthe pagination documentation\n.\n\n\nNote that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.\n\n\n\n\nThe \nPAGINATE_BY\n settings key will continue to work but is now pending deprecation. The more obviously named \nPAGE_SIZE\n settings key should now be used instead.\n\n\nThe \nPAGINATE_BY_PARAM\n, \nMAX_PAGINATE_BY\n settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.\n\n\nThe \npaginate_by\n, \npage_query_param\n, \npaginate_by_param\n and \nmax_paginate_by\n generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.\n\n\nThe \npagination_serializer_class\n view attribute and \nDEFAULT_PAGINATION_SERIALIZER_CLASS\n settings key \nare no longer valid\n. The pagination API does not use serializers to determine the output format, and you'll need to instead override the \nget_paginated_response\n method on a pagination class in order to specify how the output format is controlled.\n\n\n\n\nNew pagination schemes.\n\n\nUntil now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.\n\n\nThe cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for \nthis blog post\n on the subject.\n\n\nPagination controls in the browsable API.\n\n\nPaginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:\n\n\n\n\nThe cursor based pagination renders a more simple style of control:\n\n\n\n\nSupport for header-based pagination.\n\n\nThe pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the \nLink\n or \nContent-Range\n headers.\n\n\nFor more information, see the \ncustom pagination styles\n documentation.\n\n\n\n\nVersioning\n\n\nWe've made it \neasier to build versioned APIs\n. Built-in schemes for versioning include both URL based and Accept header based variations.\n\n\nWhen using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.\n\n\nFor example, when using \nNamespaceVersioning\n, and the following hyperlinked serializer:\n\n\nclass AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ('account_name', 'users')\n\n\n\nThe output representation would match the version used on the incoming request. Like so:\n\n\nGET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}\n\n\n\n\n\nInternationalization\n\n\nREST framework now includes a built-in set of translations, and \nsupports internationalized error responses\n. This allows you to either change the default language, or to allow clients to specify the language via the \nAccept-Language\n header.\n\n\nYou can change the default language by using the standard Django \nLANGUAGE_CODE\n setting:\n\n\nLANGUAGE_CODE = \"es-es\"\n\n\n\nYou can turn on per-request language requests by adding \nLocalMiddleware\n to your \nMIDDLEWARE_CLASSES\n setting:\n\n\nMIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n\n\n\nWhen per-request internationalization is enabled, client requests will respect the \nAccept-Language\n header where possible. For example, let's make a request for an unsupported media type:\n\n\nRequest\n\n\nGET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n\n\n\nResponse\n\n\nHTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n}\n\n\n\nNote that the structure of the error responses is still the same. We still have a \ndetail\n key in the response. If needed you can modify this behavior too, by using a \ncustom exception handler\n.\n\n\nWe include built-in translations both for standard exception cases, and for serializer validation errors.\n\n\nThe full list of supported languages can be found on our \nTransifex project page\n.\n\n\nIf you only wish to support a subset of the supported languages, use Django's standard \nLANGUAGES\n setting:\n\n\nLANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n\n\n\nFor more details, see the \ninternationalization documentation\n.\n\n\nMany thanks to \nCraig Blaszczyk\n for helping push this through.\n\n\n\n\nNew field types\n\n\nDjango 1.8's new \nArrayField\n, \nHStoreField\n and \nUUIDField\n are now all fully supported.\n\n\nThis work also means that we now have both \nserializers.DictField()\n, and \nserializers.ListField()\n types, allowing you to express and validate a wider set of representations.\n\n\nIf you're building a new 1.8 project, then you should probably consider using \nUUIDField\n as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:\n\n\nhttp://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d\n\n\n\n\n\nModelSerializer API\n\n\nThe serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.\n\n\nFor more information, see the documentation on \ncustomizing field mappings\n for ModelSerializer classes.\n\n\n\n\nMoving packages out of core\n\n\nWe've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to \npip install\n the new packages, and change any import paths.\n\n\nWe're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.\n\n\nThe change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained \nDjango OAuth toolkit\n has now been promoted as our recommended option for integrating OAuth support.\n\n\nThe following packages are now moved out of core and should be separately installed:\n\n\n\n\nOAuth - \ndjangorestframework-oauth\n\n\nXML - \ndjangorestframework-xml\n\n\nYAML - \ndjangorestframework-yaml\n\n\nJSONP - \ndjangorestframework-jsonp\n\n\n\n\nIt's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:\n\n\npip install djangorestframework-xml\n\n\n\nAnd modify your settings, like so:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n}\n\n\n\nThanks go to the latest member of our maintenance team, \nJos\u00e9 Padilla\n, for handling this work and taking on ownership of these packages.\n\n\n\n\nDeprecations\n\n\nThe \nrequest.DATA\n, \nrequest.FILES\n and \nrequest.QUERY_PARAMS\n attributes move from pending deprecation, to deprecated. Use \nrequest.data\n and \nrequest.query_params\n instead, as discussed in the 3.0 release notes.\n\n\nThe ModelSerializer Meta options for \nwrite_only_fields\n, \nview_name\n and \nlookup_field\n are also moved from pending deprecation, to deprecated. Use \nextra_kwargs\n instead, as discussed in the 3.0 release notes.\n\n\nAll these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.\n\n\n\n\nWhat's next?\n\n\nThe next focus will be on HTML renderings of API output and will include:\n\n\n\n\nHTML form rendering of serializers.\n\n\nFiltering controls built-in to the browsable API.\n\n\nAn alternative admin-style interface.\n\n\n\n\nThis will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.", - "title": "3.1 Announcement" - }, - { - "location": "/community/3.1-announcement/#django-rest-framework-31", - "text": "The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality. Some highlights include: A super-smart cursor pagination scheme. An improved pagination API, supporting header or in-body pagination styles. Pagination controls rendering in the browsable API. Better support for API versioning. Built-in internationalization support. Support for Django 1.8's HStoreField and ArrayField .", - "title": "Django REST framework 3.1" - }, - { - "location": "/community/3.1-announcement/#pagination", - "text": "The pagination API has been improved, making it both easier to use, and more powerful. A guide to the headline features follows. For full details, see the pagination documentation . Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes. The PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead. The PAGINATE_BY_PARAM , MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The paginate_by , page_query_param , paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid . The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.", - "title": "Pagination" - }, - { - "location": "/community/3.1-announcement/#new-pagination-schemes", - "text": "Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.", - "title": "New pagination schemes." - }, - { - "location": "/community/3.1-announcement/#pagination-controls-in-the-browsable-api", - "text": "Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API: The cursor based pagination renders a more simple style of control:", - "title": "Pagination controls in the browsable API." - }, - { - "location": "/community/3.1-announcement/#support-for-header-based-pagination", - "text": "The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers. For more information, see the custom pagination styles documentation.", - "title": "Support for header-based pagination." - }, - { - "location": "/community/3.1-announcement/#versioning", - "text": "We've made it easier to build versioned APIs . Built-in schemes for versioning include both URL based and Accept header based variations. When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request. For example, when using NamespaceVersioning , and the following hyperlinked serializer: class AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ('account_name', 'users') The output representation would match the version used on the incoming request. Like so: GET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}", - "title": "Versioning" - }, - { - "location": "/community/3.1-announcement/#internationalization", - "text": "REST framework now includes a built-in set of translations, and supports internationalized error responses . This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header. You can change the default language by using the standard Django LANGUAGE_CODE setting: LANGUAGE_CODE = \"es-es\" You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting: MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n] When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type: Request GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org Response HTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n} Note that the structure of the error responses is still the same. We still have a detail key in the response. If needed you can modify this behavior too, by using a custom exception handler . We include built-in translations both for standard exception cases, and for serializer validation errors. The full list of supported languages can be found on our Transifex project page . If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES setting: LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n] For more details, see the internationalization documentation . Many thanks to Craig Blaszczyk for helping push this through.", - "title": "Internationalization" - }, - { - "location": "/community/3.1-announcement/#new-field-types", - "text": "Django 1.8's new ArrayField , HStoreField and UUIDField are now all fully supported. This work also means that we now have both serializers.DictField() , and serializers.ListField() types, allowing you to express and validate a wider set of representations. If you're building a new 1.8 project, then you should probably consider using UUIDField as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style: http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d", - "title": "New field types" - }, - { - "location": "/community/3.1-announcement/#modelserializer-api", - "text": "The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships. For more information, see the documentation on customizing field mappings for ModelSerializer classes.", - "title": "ModelSerializer API" - }, - { - "location": "/community/3.1-announcement/#moving-packages-out-of-core", - "text": "We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install the new packages, and change any import paths. We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework. The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained Django OAuth toolkit has now been promoted as our recommended option for integrating OAuth support. The following packages are now moved out of core and should be separately installed: OAuth - djangorestframework-oauth XML - djangorestframework-xml YAML - djangorestframework-yaml JSONP - djangorestframework-jsonp It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do: pip install djangorestframework-xml And modify your settings, like so: REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n} Thanks go to the latest member of our maintenance team, Jos\u00e9 Padilla , for handling this work and taking on ownership of these packages.", - "title": "Moving packages out of core" - }, - { - "location": "/community/3.1-announcement/#deprecations", - "text": "The request.DATA , request.FILES and request.QUERY_PARAMS attributes move from pending deprecation, to deprecated. Use request.data and request.query_params instead, as discussed in the 3.0 release notes. The ModelSerializer Meta options for write_only_fields , view_name and lookup_field are also moved from pending deprecation, to deprecated. Use extra_kwargs instead, as discussed in the 3.0 release notes. All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.", - "title": "Deprecations" - }, - { - "location": "/community/3.1-announcement/#whats-next", - "text": "The next focus will be on HTML renderings of API output and will include: HTML form rendering of serializers. Filtering controls built-in to the browsable API. An alternative admin-style interface. This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.", - "title": "What's next?" - }, - { - "location": "/community/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\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_\n.\n\n\nThe \nvalidate_\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_\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_\n.\n\n\nThe under-used \ntransform_\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_\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_` 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>>> class Meta:\n>>> model = Profile\n>>> fields = ('address', 'phone')\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ('username', 'email', 'profile')\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\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>>> 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>>> 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) > 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=\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_\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-8601 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-8601'\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 & 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" - }, - { - "location": "/community/3.0-announcement/#django-rest-framework-30", - "text": "The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward. The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier. 3.0 is the first of three releases that have been funded by our recent Kickstarter campaign . As ever, a huge thank you to our many wonderful sponsors . 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.", - "title": "Django REST framework 3.0" - }, - { - "location": "/community/3.0-announcement/#new-features", - "text": "Notable features of this new release include: Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit ModelSerializer class and the explicit Serializer class. A new BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. A cleaner fields API including new classes such as ListField and MultipleChoiceField . Super simple default implementations for the generic views. Support for overriding how validation errors are handled by your API. A metadata API that allows you to customize how OPTIONS requests are handled by your API. A more compact JSON output with unicode style encoding turned on by default. Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"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.", - "title": "New features" - }, - { - "location": "/community/3.0-announcement/#rest-framework-under-the-hood", - "text": "This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. Below is an in-depth guide to the API changes and migration notes for 3.0.", - "title": "REST framework: Under the hood." - }, - { - "location": "/community/3.0-announcement/#request-objects", - "text": "", - "title": "Request objects" - }, - { - "location": "/community/3.0-announcement/#the-data-and-query_params-properties", - "text": "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: # Do this...\nExampleSerializer(data=request.data) Instead of passing the files argument separately: # Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES) The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params .", - "title": "The .data and .query_params properties." - }, - { - "location": "/community/3.0-announcement/#serializers", - "text": "", - "title": "Serializers" - }, - { - "location": "/community/3.0-announcement/#single-step-object-creation", - "text": "Previously the serializers used a two-step object creation, as follows: Validating the data would create an object instance. This instance would be available as serializer.object . Calling serializer.save() would then save the object instance to the database. This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons: Some 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 .save() is called. Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. ExampleModel.objects.create(...) . Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. The 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? We now use single-step object creation, like so: Validating the data makes the cleaned data available as serializer.validated_data . Calling serializer.save() then saves and returns the new object instance. The resulting API changes are further detailed below.", - "title": "Single-step object creation." - }, - { - "location": "/community/3.0-announcement/#the-create-and-update-methods", - "text": "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. The following example from the tutorial previously used restore_object() to handle both creating and updating object instances. def 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) This would now be split out into two separate methods. def 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) Note that these methods should return the newly created object instance.", - "title": "The .create() and .update() methods." - }, - { - "location": "/community/3.0-announcement/#use-validated_data-instead-of-object", - "text": "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():\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() Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments. The corresponding code would now look like this: if 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.", - "title": "Use .validated_data instead of .object." - }, - { - "location": "/community/3.0-announcement/#using-is_validraise_exceptiontrue", - "text": "The .is_valid() method now takes an optional boolean flag, raise_exception . Calling .is_valid(raise_exception=True) will cause a ValidationError 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. The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key. This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.", - "title": "Using .is_valid(raise_exception=True)" - }, - { - "location": "/community/3.0-announcement/#using-serializersvalidationerror", - "text": "Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError . This has now been altered so that it inherits from the standard APIException base class. The reason behind this is that Django's ValidationError 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. For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the serializers.ValidationError exception class, and not Django's built-in exception. We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.", - "title": "Using serializers.ValidationError." - }, - { - "location": "/community/3.0-announcement/#change-to-validate_field_name", - "text": "The validate_ 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: def 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 This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual. Because .validate_ 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 .validate() instead. You can either return non_field_errors from the validate method by raising a simple ValidationError def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error') Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError , like so: def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'}) This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.", - "title": "Change to validate_<field_name>." - }, - { - "location": "/community/3.0-announcement/#removal-of-transform_field_name", - "text": "The under-used transform_ on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style. For example: def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret Dropping 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. If you absolutely need to preserve transform_ 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: class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_` 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", - "title": "Removal of transform_<field_name>." - }, - { - "location": "/community/3.0-announcement/#differences-between-modelserializer-validation-and-modelform", - "text": "This change also means that we no longer use the .full_clean() 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 ModelSerializer classes that can't also be easily replicated on regular Serializer classes. For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different. The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm . Use the serializer .validate() method to perform a final validation step on incoming data where required. There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate() . You can do so by explicitly instantiating a model instance in the .validate() method. def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.", - "title": "Differences between ModelSerializer validation and ModelForm." - }, - { - "location": "/community/3.0-announcement/#writable-nested-serialization", - "text": "REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: There can be complex dependencies involved in order of saving multiple related model instances. It's unclear what behavior the user should expect when related models are passed None data. It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. Using the depth option on ModelSerializer will now create read-only nested serializers by default. If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example: >>> class ProfileSerializer(serializers.ModelSerializer):\n>>> class Meta:\n>>> model = Profile\n>>> fields = ('address', 'phone')\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ('username', 'email', 'profile')\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\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. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly. class 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 The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.", - "title": "Writable nested serialization." - }, - { - "location": "/community/3.0-announcement/#printable-serializer-representations", - "text": "Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. For instance, given the following example model: class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User) Let's create a simple ModelSerializer class corresponding to the LocationRating model. class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating We can now inspect the serializer representation in the Django shell, using python manage.py shell ... >>> serializer = LocationRatingSerializer()\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())", - "title": "Printable serializer representations." - }, - { - "location": "/community/3.0-announcement/#the-extra_kwargs-option", - "text": "The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs . class 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 } Alternatively, specify the field explicitly on the serializer class: class 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') The read_only_fields option remains as a convenient shortcut for the more common case.", - "title": "The extra_kwargs option." - }, - { - "location": "/community/3.0-announcement/#changes-to-hyperlinkedmodelserializer", - "text": "The view_name and lookup_field options have been moved to PendingDeprecation . They are no longer required, as you can use the extra_kwargs argument instead: class 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 } Alternatively, specify the field explicitly on the serializer class: class 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')", - "title": "Changes to HyperlinkedModelSerializer." - }, - { - "location": "/community/3.0-announcement/#fields-for-model-methods-and-properties", - "text": "With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model: class 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) You can include expiry_date as a field option on a ModelSerializer class. class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date') These fields will be mapped to serializers.ReadOnlyField() instances. >>> serializer = InvitationSerializer()\n>>> print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()", - "title": "Fields for model methods and properties." - }, - { - "location": "/community/3.0-announcement/#the-listserializer-class", - "text": "The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer):\n child = UserSerializer() You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior. See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid() , .data , .save() and so on.", - "title": "The ListSerializer class." - }, - { - "location": "/community/3.0-announcement/#the-baseserializer-class", - "text": "REST framework now includes a simple BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns an errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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.", - "title": "The BaseSerializer class." - }, - { - "location": "/community/3.0-announcement/#read-only-baseserializer-classes", - "text": "To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @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)", - "title": "Read-only BaseSerializer classes." - }, - { - "location": "/community/3.0-announcement/#read-write-baseserializer-classes", - "text": "To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class 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) > 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)", - "title": "Read-write BaseSerializer classes." - }, - { - "location": "/community/3.0-announcement/#creating-new-generic-serializers-with-baseserializer", - "text": "The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class 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)", - "title": "Creating new generic serializers with BaseSerializer." - }, - { - "location": "/community/3.0-announcement/#serializer-fields", - "text": "", - "title": "Serializer fields" - }, - { - "location": "/community/3.0-announcement/#the-field-and-readonly-field-classes", - "text": "There are some minor tweaks to the field base classes. Previously we had these two base classes: Field as the base class for read-only fields. A default implementation was included for serializing data. WritableField as the base class for read-write fields. We now use the following: 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.", - "title": "The Field and ReadOnly field classes." - }, - { - "location": "/community/3.0-announcement/#the-required-allow_null-allow_blank-and-default-arguments", - "text": "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. The following set of arguments are used to control validation of empty values: required=False : The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen. default= : The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen. allow_null=True : None is a valid input. allow_blank=True : '' is valid input. For CharField and subclasses only. Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required. The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.", - "title": "The required, allow_null, allow_blank and default arguments." - }, - { - "location": "/community/3.0-announcement/#coercing-output-types", - "text": "The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField 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.", - "title": "Coercing output types." - }, - { - "location": "/community/3.0-announcement/#removal-of-validate", - "text": "The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value() . class 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 Previously validation errors could be raised in either .to_native() or .validate() , making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.", - "title": "Removal of .validate()." - }, - { - "location": "/community/3.0-announcement/#the-listfield-class", - "text": "The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) You can also use a declarative style to create new subclasses of ListField , like this: class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100) We can now use the ScoresField class inside another serializer: scores = ScoresField() See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid() , .data , .save() and so on.", - "title": "The ListField class." - }, - { - "location": "/community/3.0-announcement/#the-choicefield-class-may-now-accept-a-flat-list", - "text": "The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value) . The following is now valid: color = ChoiceField(choices=['red', 'green', 'blue'])", - "title": "The ChoiceField class may now accept a flat list." - }, - { - "location": "/community/3.0-announcement/#the-multiplechoicefield-class", - "text": "The MultipleChoiceField class has been added. This field acts like ChoiceField , but returns a set, which may include none, one or many of the valid choices.", - "title": "The MultipleChoiceField class." - }, - { - "location": "/community/3.0-announcement/#changes-to-the-custom-field-api", - "text": "The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value) . The field_from_native() and field_to_native() 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... def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__ Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation() . Use get_value to modify the data value passed to_internal_value() . For example: def 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__", - "title": "Changes to the custom field API." - }, - { - "location": "/community/3.0-announcement/#explicit-queryset-required-on-relational-fields", - "text": "Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a ModelSerializer . This code would be valid in 2.4.3 : class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account However this code would not be valid in 3.0 : # Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ... The 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 ModelSerializer classes and explicit Serializer classes. class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True .", - "title": "Explicit queryset required on relational fields." - }, - { - "location": "/community/3.0-announcement/#optional-argument-to-serializermethodfield", - "text": "The argument to SerializerMethodField is now optional, and defaults to get_ . For example the following is valid: class 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) In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code will raise an error : billing_details = serializers.SerializerMethodField('get_billing_details')", - "title": "Optional argument to SerializerMethodField." - }, - { - "location": "/community/3.0-announcement/#enforcing-consistent-source-usage", - "text": "I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required. The following usage will now raise an error : email = serializers.EmailField(source='email')", - "title": "Enforcing consistent source usage." - }, - { - "location": "/community/3.0-announcement/#the-uniquevalidator-and-uniquetogethervalidator-classes", - "text": "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\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 ) The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names. class 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 )]", - "title": "The UniqueValidator and UniqueTogetherValidator classes." - }, - { - "location": "/community/3.0-announcement/#the-uniquefordatevalidator-classes", - "text": "REST framework also now includes explicit validator classes for validating the unique_for_date , unique_for_month , and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean() . These classes are documented in the Validators section of the documentation.", - "title": "The UniqueForDateValidator classes." - }, - { - "location": "/community/3.0-announcement/#generic-views", - "text": "", - "title": "Generic views" - }, - { - "location": "/community/3.0-announcement/#simplification-of-view-logic", - "text": "The view logic for the default method handlers has been significantly simplified, due to the new serializers API.", - "title": "Simplification of view logic." - }, - { - "location": "/community/3.0-announcement/#changes-to-prepost-save-hooks", - "text": "The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer) . These methods should save the object instance by calling serializer.save() , adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: def 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) The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance) , which should delete the instance and perform any custom actions. def 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()", - "title": "Changes to pre/post save hooks." - }, - { - "location": "/community/3.0-announcement/#removal-of-view-attributes", - "text": "The .object and .object_list 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. I would personally recommend that developers treat view instances as immutable objects in their application code.", - "title": "Removal of view attributes." - }, - { - "location": "/community/3.0-announcement/#put-as-create", - "text": "Allowing PUT 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 404 responses. Both styles \" PUT as 404\" and \" PUT 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. If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.", - "title": "PUT as create." - }, - { - "location": "/community/3.0-announcement/#customizing-error-responses", - "text": "The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly. This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.", - "title": "Customizing error responses." - }, - { - "location": "/community/3.0-announcement/#the-metadata-api", - "text": "Behavior for dealing with OPTIONS 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. This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.", - "title": "The metadata API" - }, - { - "location": "/community/3.0-announcement/#serializers-as-html-forms", - "text": "REST framework 3.0 includes templated HTML form rendering for serializers. This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release. Significant changes that you do need to be aware of include: Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API. Nested lists of HTML forms are not yet supported, but are planned for 3.1. Because we now use templated HTML form generation, the widget option is no longer available for serializer fields . You can instead control the template that is used for a given field, by using the style dictionary.", - "title": "Serializers as HTML forms" - }, - { - "location": "/community/3.0-announcement/#the-style-keyword-argument-for-serializer-fields", - "text": "The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with. For example, to use a textarea control instead of the default input control, you would use the following\u2026 additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n) Similarly, to use a radio button control instead of the default select control, you would use the following\u2026 color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n) This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.", - "title": "The style keyword argument for serializer fields." - }, - { - "location": "/community/3.0-announcement/#api-style", - "text": "There are some improvements in the default style we use in our API responses.", - "title": "API style" - }, - { - "location": "/community/3.0-announcement/#unicode-json-by-default", - "text": "Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting: REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}", - "title": "Unicode JSON by default." - }, - { - "location": "/community/3.0-announcement/#compact-json-by-default", - "text": "We now output compact JSON in responses by default. For example, we return: {\"email\":\"amy@example.com\",\"is_admin\":true} Instead of the following: {\"email\": \"amy@example.com\", \"is_admin\": true} The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed: REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}", - "title": "Compact JSON by default." - }, - { - "location": "/community/3.0-announcement/#file-fields-as-urls", - "text": "The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files . You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key: REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n} You can also modify serializer fields individually, using the use_url argument: uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the request 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 https://example.com/url_path/filename.txt . For example: context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data) If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt .", - "title": "File fields as URLs" - }, - { - "location": "/community/3.0-announcement/#throttle-headers-using-retry-after", - "text": "The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.", - "title": "Throttle headers using Retry-After." - }, - { - "location": "/community/3.0-announcement/#date-and-time-objects-as-iso-8601-strings-in-serializer-data", - "text": "Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date , Time and DateTime objects, and later coerced to strings by the renderer. You can modify this behavior globally by settings the existing DATE_FORMAT , DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8601' will result in native objects being returned in serializer data. REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n} You can also modify serializer fields individually, using the date_format , time_format and datetime_format arguments: # Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)", - "title": "Date and time objects as ISO-8601 strings in serializer data." - }, - { - "location": "/community/3.0-announcement/#decimals-as-strings-in-serializer-data", - "text": "Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer. You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key. REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n} Or modify it on an individual serializer field, using the coerce_to_string keyword argument. # 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) The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.", - "title": "Decimals as strings in serializer data." - }, - { - "location": "/community/3.0-announcement/#miscellaneous-notes", - "text": "The serializer ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1. Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party \"autocomplete\" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand. Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still create language files with Django if you wish to localize them. APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string . If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.", - "title": "Miscellaneous notes" - }, - { - "location": "/community/3.0-announcement/#whats-coming-next", - "text": "3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes. The 3.1 release is planned to address improvements in the following components: Public API for using serializers as HTML forms. Request parsing, mediatypes & the implementation of the browsable API. Introduction of a new pagination API. Better support for API versioning. The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API. You can follow development on the GitHub site, where we use milestones to indicate planning timescales .", - "title": "What's coming next" - }, - { - "location": "/community/kickstarter-announcement/", - "text": "Kickstarting Django REST framework 3\n\n\n\n\n \n\n\n\n\n\nIn order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.\n\n\nProject details\n\n\nThis new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:\n\n\n\n\nFaster, simpler and easier-to-use serializers.\n\n\nAn alternative admin-style interface for the browsable API.\n\n\nSearch and filtering controls made accessible in the browsable API.\n\n\nAlternative API pagination styles.\n\n\nDocumentation around API versioning.\n\n\nTriage of outstanding tickets.\n\n\nImproving the ongoing quality and maintainability of the project.\n\n\n\n\nFull details are available now on the \nproject page\n.\n\n\nIf you're interested in helping make sustainable open source development a reality please \nvisit the Kickstarter page\n and consider funding the project.\n\n\nI can't wait to see where this takes us!\n\n\nMany thanks to everyone for your support so far,\n\n\nTom Christie :)\n\n\n\n\nSponsors\n\n\nWe've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.\n\n\n\n\nPlatinum sponsors\n\n\nOur platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.\n\n\n\n\nEventbrite\n\n\n\n\n\n\n\nDivio\n\n\nLulu\n\n\nPotato\n\n\nWiredrive\n\n\nCyan\n\n\nRunscope\n\n\nSimple Energy\n\n\nVOKAL Interactive\n\n\nPurple Bit\n\n\nKuwaitNET\n\n\n\n\n\n\n\n\n\n\nGold sponsors\n\n\nOur gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.\n\n\n\n\nLaterPay\n\n\nSchuberg Philis\n\n\nProReNata AB\n\n\nSGA Websites\n\n\nSirono\n\n\nVinta Software Studio\n\n\nRapasso\n\n\nMirus Research\n\n\nHipo\n\n\nByte\n\n\nLightning Kite\n\n\nOpbeat\n\n\nKoordinates\n\n\nPulsecode Inc.\n\n\nSinging Horse Studio Ltd.\n\n\nHeroku\n\n\nRheinwerk Verlag\n\n\nSecurity Compass\n\n\nDjango Software Foundation\n\n\nHipflask\n\n\nCrate\n\n\nCryptico Corp\n\n\nNextHub\n\n\nCompile\n\n\nWusaWork\n\n\nEnvision Linux\n\n\n\n\n\n\n\n\n\n\nSilver sponsors\n\n\nThe serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level.\n\n\n\n\nIMT Computer Services\n\n\nWildfish\n\n\nThermondo GmbH\n\n\nProvidenz\n\n\nalwaysdata.com\n\n\nTriggered Messaging\n\n\nPushPull Technology Ltd\n\n\nTranscode\n\n\nGarfo\n\n\nShippo\n\n\nGizmag\n\n\nTivix\n\n\nSafari\n\n\nBright Loop\n\n\nABA Systems\n\n\nbeefarm.ru\n\n\nVzzual.com\n\n\nInfinite Code\n\n\nCrossword Tracker\n\n\nPkgFarm\n\n\nLife. The Game.\n\n\nBlimp\n\n\nPathwright\n\n\nFluxility\n\n\nTeonite\n\n\nTrackMaven\n\n\nPhurba\n\n\nNephila\n\n\nAditium\n\n\nOpenEye Scientific Software\n\n\nHolvi\n\n\nCantemo\n\n\nMakeSpace\n\n\nAX Semantics\n\n\nISL\n\n\n\n\n\n\n\n\nIndividual backers\n: Paul Hallett, \nPaul Whipp\n, Dylan Roy, Jannis Leidel, \nXavier Ordoquy\n, \nJohannes Spielmann\n, \nRob Spectre\n, \nChris Heisel\n, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.\n\n\n\n\nAdvocates\n\n\nThe following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!\n\n\nIndividual backers\n: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.\n\n\nCorporate backers\n: Savannah Informatics, Prism Skylabs, Musical Operating Devices.\n\n\n\n\nSupporters\n\n\nThere were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!", - "title": "Kickstarter Announcement" - }, - { - "location": "/community/kickstarter-announcement/#kickstarting-django-rest-framework-3", - "text": "In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.", - "title": "Kickstarting Django REST framework 3" - }, - { - "location": "/community/kickstarter-announcement/#project-details", - "text": "This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following: Faster, simpler and easier-to-use serializers. An alternative admin-style interface for the browsable API. Search and filtering controls made accessible in the browsable API. Alternative API pagination styles. Documentation around API versioning. Triage of outstanding tickets. Improving the ongoing quality and maintainability of the project. Full details are available now on the project page . If you're interested in helping make sustainable open source development a reality please visit the Kickstarter page and consider funding the project. I can't wait to see where this takes us! Many thanks to everyone for your support so far, Tom Christie :)", - "title": "Project details" - }, - { - "location": "/community/kickstarter-announcement/#sponsors", - "text": "We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.", - "title": "Sponsors" - }, - { - "location": "/community/kickstarter-announcement/#platinum-sponsors", - "text": "Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough. Eventbrite Divio Lulu Potato Wiredrive Cyan Runscope Simple Energy VOKAL Interactive Purple Bit KuwaitNET", - "title": "Platinum sponsors" - }, - { - "location": "/community/kickstarter-announcement/#gold-sponsors", - "text": "Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development. LaterPay Schuberg Philis ProReNata AB SGA Websites Sirono Vinta Software Studio Rapasso Mirus Research Hipo Byte Lightning Kite Opbeat Koordinates Pulsecode Inc. Singing Horse Studio Ltd. Heroku Rheinwerk Verlag Security Compass Django Software Foundation Hipflask Crate Cryptico Corp NextHub Compile WusaWork Envision Linux", - "title": "Gold sponsors" - }, - { - "location": "/community/kickstarter-announcement/#silver-sponsors", - "text": "The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level. IMT Computer Services Wildfish Thermondo GmbH Providenz alwaysdata.com Triggered Messaging PushPull Technology Ltd Transcode Garfo Shippo Gizmag Tivix Safari Bright Loop ABA Systems beefarm.ru Vzzual.com Infinite Code Crossword Tracker PkgFarm Life. The Game. Blimp Pathwright Fluxility Teonite TrackMaven Phurba Nephila Aditium OpenEye Scientific Software Holvi Cantemo MakeSpace AX Semantics ISL Individual backers : Paul Hallett, Paul Whipp , Dylan Roy, Jannis Leidel, Xavier Ordoquy , Johannes Spielmann , Rob Spectre , Chris Heisel , Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.", - "title": "Silver sponsors" - }, - { - "location": "/community/kickstarter-announcement/#advocates", - "text": "The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you! Individual backers : Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel. Corporate backers : Savannah Informatics, Prism Skylabs, Musical Operating Devices.", - "title": "Advocates" - }, - { - "location": "/community/kickstarter-announcement/#supporters", - "text": "There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!", - "title": "Supporters" - }, - { - "location": "/community/mozilla-grant/", - "text": "Mozilla Grant\n\n\nWe have recently been \nawarded a Mozilla grant\n, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.\n\n\nAdditionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.\n\n\nThe \nCore API\n project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with \nany\n API that exposes a supported schema or hypermedia format.\n\n\nSpecifically, the work includes:\n\n\nClient libraries\n\n\nThis work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.\n\n\n\n\nClient library support in REST framework.\n\n\nSchema & hypermedia support for REST framework APIs.\n\n\nA test client, allowing you to write tests that emulate a client library interacting with your API.\n\n\nNew tutorial sections on using client libraries to interact with REST framework APIs.\n\n\nPython client library.\n\n\nJavaScript client library.\n\n\nCommand line client.\n\n\n\n\nRealtime APIs\n\n\nThe next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.\n\n\n\n\nSupport for API subscription endpoints, using REST framework and Django Channels.\n\n\nNew tutorial section on building realtime API endpoints with REST framework.\n\n\nRealtime support in the Python & Javascript client libraries.\n\n\n\n\nAccountability\n\n\nIn order to ensure that I can be fully focused on trying to secure a sustainable\n& well-funded open source business I will be leaving my current role at \nDabApps\n\nat the end of May 2016.\n\n\nI have formed a UK limited company, \nEncode\n, which will\nact as the business entity behind REST framework. I will be issuing monthly reports\nfrom Encode on progress both towards the Mozilla grant, and for development time\nfunded via the \nREST framework paid plans\n.\n\n\n\n\n\n\n\n\n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /\n\n\n\n\n\n\n \n\n \nStay up to date, with our monthly progress reports...\n\n\n\n \nEmail Address \n\n \n\n\n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n\n\n\n\n\n\n(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);", - "title": "Mozilla Grant" - }, - { - "location": "/community/mozilla-grant/#mozilla-grant", - "text": "We have recently been awarded a Mozilla grant , in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with. Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications. The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format. Specifically, the work includes:", - "title": "Mozilla Grant" - }, - { - "location": "/community/mozilla-grant/#client-libraries", - "text": "This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation. Client library support in REST framework. Schema & hypermedia support for REST framework APIs. A test client, allowing you to write tests that emulate a client library interacting with your API. New tutorial sections on using client libraries to interact with REST framework APIs. Python client library. JavaScript client library. Command line client.", - "title": "Client libraries" - }, - { - "location": "/community/mozilla-grant/#realtime-apis", - "text": "The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints. Support for API subscription endpoints, using REST framework and Django Channels. New tutorial section on building realtime API endpoints with REST framework. Realtime support in the Python & Javascript client libraries.", - "title": "Realtime APIs" - }, - { - "location": "/community/mozilla-grant/#accountability", - "text": "In order to ensure that I can be fully focused on trying to secure a sustainable\n& well-funded open source business I will be leaving my current role at DabApps \nat the end of May 2016. I have formed a UK limited company, Encode , which will\nact as the business entity behind REST framework. I will be issuing monthly reports\nfrom Encode on progress both towards the Mozilla grant, and for development time\nfunded via the REST framework paid plans . \n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /", - "title": "Accountability" - }, - { - "location": "/community/funding/", - "text": "// Imperfect, but easier to fit in with the existing docs build.\n// Hyperlinks should point directly to the \"fund.\" subdomain, but this'll\n// handle the nav bar links without requiring any docs build changes for the moment.\nif (window.location.hostname == \"www.django-rest-framework.org\") {\n window.location.replace(\"https://fund.django-rest-framework.org/topics/funding/\");\n}\n\n\n\n\n\n.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.chart {\n background-color: #e3e3e3;\n background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);\n border: 1px solid #E6E6E6;\n border-radius: 5px;\n box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);\n padding: 40px 0px 5px;\n position: relative;\n text-align: center;\n width: 97%;\n min-height: 255px;\n position: relative;\n top: 37px;\n margin-bottom: 20px\n}\n.quantity {\n text-align: center\n}\n.dollar {\n font-size: 19px;\n position: relative;\n top: -18px;\n}\n.price {\n font-size: 49px;\n}\n.period {\n font-size: 17px;\n position: relative;\n top: -8px;\n margin-left: 4px;\n}\n.plan-name {\n text-align: center;\n font-size: 20px;\n font-weight: 400;\n color: #777;\n border-bottom: 1px solid #d5d5d5;\n padding-bottom: 15px;\n width: 90%;\n margin: 0 auto;\n margin-top: 8px;\n}\n.specs {\n margin-top: 20px;\n min-height: 130px;\n}\n.specs.freelancer {\n min-height: 0px;\n}\n.spec {\n font-size: 15px;\n color: #474747;\n text-align: center;\n font-weight: 300;\n margin-bottom: 13px;\n}\n.variable {\n color: #1FBEE7;\n font-weight: 400;\n}\nform.signup {\n margin-top: 35px\n}\n.clear-promo {\n padding-top: 30px\n}\n#main-content h1:first-of-type {\n margin: 0 0 50px;\n font-size: 60px;\n font-weight: 200;\n text-align: center\n}\n#main-content {\n padding-top: 10px; line-height: 23px\n}\n#main-content li {\n line-height: 23px\n}\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.\n\n\nWe believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.\n\n\nSigning up for a paid plan will:\n\n\n\n\nDirectly contribute to faster releases, more features, and higher quality software.\n\n\nAllow more time to be invested in documentation, issue triage, and community support.\n\n\nSafeguard the future development of REST framework.\n\n\n\n\nREST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.\n\n\n\n\nWhat funding has enabled so far\n\n\n\n\nThe \n3.4\n and \n3.5\n releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.\n\n\nThe \n3.6\n release, including JavaScript client library, and API documentation, complete with auto-generated code samples.\n\n\nThe \n3.7 release\n, made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.\n\n\nThe recent \n3.8 release\n.\n\n\nTom Christie, the creator of Django REST framework, working on the project full-time.\n\n\nAround 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.\n\n\nA community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.\n\n\nContracting development time for the work on the JavaScript client library and API documentation tooling.\n\n\n\n\n\n\nWhat future funding will enable\n\n\n\n\nRealtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.\n\n\nBetter authentication defaults, possibly bringing JWT & CORs support into the core package.\n\n\nSecuring the community & operations manager position long-term.\n\n\nOpening up and securing a part-time position to focus on ticket triage and resolution.\n\n\nPaying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.\n\n\n\n\nSign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.\n\n\n\n\nWhat our sponsors and users say\n\n\n\n\nAs a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.\n\n\n\u2014 Jos\u00e9 Padilla, Django REST framework contributor\n\n\n\n\n\u00a0\n\n\n\n\nThe number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.\n\n\n\u2014 Filipe Ximenes, Vinta Software\n\n\n\n\n\u00a0\n\n\n\n\nIt's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.\nDRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.\n\n\n\u2014 Andrew Conti, Django REST framework user\n\n\n\n\n\n\nIndividual plan\n\n\nThis subscription is recommended for individuals with an interest in seeing REST framework continue to\u00a0improve.\n\n\nIf you are using REST framework as a full-time employee, consider recommending that your company takes out a \ncorporate\u00a0plan\n.\n\n\n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.personal1 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nIndividual\n\n \n\n \n\n Support ongoing development\n \n\n \n\n Credited on the site\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n\n\n\n\n\nBilling is monthly and you can cancel at any time.\n\n\n\n\nCorporate plans\n\n\nThese subscriptions are recommended for companies and organizations using REST framework either publicly or privately.\n\n\nIn exchange for funding you'll also receive advertising space on our site, allowing you to \npromote your company or product to many tens of thousands of developers worldwide\n.\n\n\nOur professional and premium plans also include \npriority support\n. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.\n\n\n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate1 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nBasic\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nFunding page\n ad placement\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate2 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nProfessional\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nSidebar\n ad placement\n \n\n \n\n \nPriority support\n for your engineers\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate3 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nPremium\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nHomepage\n ad placement\n \n\n \n\n \nSidebar\n ad placement\n \n\n \n\n \nPriority support\n for your engineers\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n\n\n\n\n\nBilling is monthly and you can cancel at any time.\n\n\nOnce you've signed up, we will contact you via email and arrange your ad placements on the site.\n\n\nFor further enquires please contact \nfunding@django-rest-framework.org\n.\n\n\n\n\nAccountability\n\n\nIn an effort to keep the project as transparent as possible, we are releasing \nmonthly progress reports\n and regularly include financial reports and cost breakdowns.\n\n\n\n\n\n\n\n\n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /\n\n\n\n\n\n\n \n\n \nStay up to date, with our monthly progress reports...\n\n\n\n \nEmail Address \n\n \n\n\n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n\n\n\n\n\n\n(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);\n\n\n\n\n\n\nFrequently asked questions\n\n\nQ: Can you issue monthly invoices?\n\nA: Yes, we are happy to issue monthly invoices. Please just \nemail us\n and let us know who to issue the invoice to (name and address) and which email address to send it to each month.\n\n\nQ: Does sponsorship include VAT?\n\nA: Sponsorship is VAT exempt.\n\n\nQ: Do I have to sign up for a certain time period?\n\nA: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.\n\n\nQ: Can I pay yearly? Can I pay upfront fox X amount of months at a time?\n\nA: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.\n\n\nQ: Are you only looking for corporate sponsors?\n\nA: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.\n\n\n\n\nOur sponsors", - "title": "Funding" - }, - { - "location": "/community/funding/#funding", - "text": "If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan. We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development. Signing up for a paid plan will: Directly contribute to faster releases, more features, and higher quality software. Allow more time to be invested in documentation, issue triage, and community support. Safeguard the future development of REST framework. REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.", - "title": "Funding" - }, - { - "location": "/community/funding/#what-funding-has-enabled-so-far", - "text": "The 3.4 and 3.5 releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. The 3.6 release, including JavaScript client library, and API documentation, complete with auto-generated code samples. The 3.7 release , made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. The recent 3.8 release . Tom Christie, the creator of Django REST framework, working on the project full-time. Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time. A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship. Contracting development time for the work on the JavaScript client library and API documentation tooling.", - "title": "What funding has enabled so far" - }, - { - "location": "/community/funding/#what-future-funding-will-enable", - "text": "Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries. Better authentication defaults, possibly bringing JWT & CORs support into the core package. Securing the community & operations manager position long-term. Opening up and securing a part-time position to focus on ticket triage and resolution. Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation. Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.", - "title": "What future funding will enable" - }, - { - "location": "/community/funding/#what-our-sponsors-and-users-say", - "text": "As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem. \u2014 Jos\u00e9 Padilla, Django REST framework contributor \u00a0 The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it. \u2014 Filipe Ximenes, Vinta Software \u00a0 It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.\nDRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large. \u2014 Andrew Conti, Django REST framework user", - "title": "What our sponsors and users say" - }, - { - "location": "/community/funding/#individual-plan", - "text": "This subscription is recommended for individuals with an interest in seeing REST framework continue to\u00a0improve. If you are using REST framework as a full-time employee, consider recommending that your company takes out a corporate\u00a0plan . \n \n \n \n {{ symbol }} \n {{ rates.personal1 }} \n /month{% if vat %} +VAT{% endif %} \n \n Individual \n \n \n Support ongoing development\n \n \n Credited on the site\n \n \n \n \n \n \n \n Billing is monthly and you can cancel at any time.", - "title": "Individual plan" - }, - { - "location": "/community/funding/#corporate-plans", - "text": "These subscriptions are recommended for companies and organizations using REST framework either publicly or privately. In exchange for funding you'll also receive advertising space on our site, allowing you to promote your company or product to many tens of thousands of developers worldwide . Our professional and premium plans also include priority support . At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day. \n \n \n \n {{ symbol }} \n {{ rates.corporate1 }} \n /month{% if vat %} +VAT{% endif %} \n \n Basic \n \n \n Support ongoing development\n \n \n Funding page ad placement\n \n \n \n \n \n \n \n \n \n \n {{ symbol }} \n {{ rates.corporate2 }} \n /month{% if vat %} +VAT{% endif %} \n \n Professional \n \n \n Support ongoing development\n \n \n Sidebar ad placement\n \n \n Priority support for your engineers\n \n \n \n \n \n \n \n \n \n \n {{ symbol }} \n {{ rates.corporate3 }} \n /month{% if vat %} +VAT{% endif %} \n \n Premium \n \n \n Support ongoing development\n \n \n Homepage ad placement\n \n \n Sidebar ad placement\n \n \n Priority support for your engineers\n \n \n \n \n \n \n \n Billing is monthly and you can cancel at any time. Once you've signed up, we will contact you via email and arrange your ad placements on the site. For further enquires please contact funding@django-rest-framework.org .", - "title": "Corporate plans" - }, - { - "location": "/community/funding/#accountability", - "text": "In an effort to keep the project as transparent as possible, we are releasing monthly progress reports and regularly include financial reports and cost breakdowns. \n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /", - "title": "Accountability" - }, - { - "location": "/community/funding/#frequently-asked-questions", - "text": "Q: Can you issue monthly invoices? \nA: Yes, we are happy to issue monthly invoices. Please just email us and let us know who to issue the invoice to (name and address) and which email address to send it to each month. Q: Does sponsorship include VAT? \nA: Sponsorship is VAT exempt. Q: Do I have to sign up for a certain time period? \nA: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime. Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time? \nA: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution. Q: Are you only looking for corporate sponsors? \nA: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.", - "title": "Frequently asked questions" - }, - { - "location": "/community/funding/#our-sponsors", - "text": "", - "title": "Our sponsors" - }, - { - "location": "/community/jobs/", + "location": "/topics/jobs/", "text": "Jobs\n\n\nLooking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of \nour sponsors are hiring\n.\n\n\nPlaces to look for Django REST Framework Jobs\n\n\n\n\nhttps://www.djangoproject.com/community/jobs/\n\n\nhttps://www.python.org/jobs/\n\n\nhttps://djangogigs.com\n\n\nhttps://djangojobs.net/jobs/\n\n\nhttp://djangojobbers.com\n\n\nhttps://www.indeed.com/q-Django-jobs.html\n\n\nhttps://stackoverflow.com/jobs/developer-jobs-using-django\n\n\nhttps://www.upwork.com/o/jobs/browse/skill/django-framework/\n\n\nhttps://www.technojobs.co.uk/django-jobs\n\n\nhttps://remoteok.io/remote-django-jobs\n\n\nhttps://www.remotepython.com/jobs/\n\n\nhttps://weworkcontract.com/python-contract-jobs\n\n\n\n\nKnow of any other great resources for Django REST Framework jobs that are missing in our list? Please \nsubmit a pull request\n or \nemail us\n.\n\n\nWonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for \nREST Framework sponsorship\n yet.", "title": "Jobs" }, { - "location": "/community/jobs/#jobs", + "location": "/topics/jobs/#jobs", "text": "Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring .", "title": "Jobs" }, { - "location": "/community/jobs/#places-to-look-for-django-rest-framework-jobs", + "location": "/topics/jobs/#places-to-look-for-django-rest-framework-jobs", "text": "https://www.djangoproject.com/community/jobs/ https://www.python.org/jobs/ https://djangogigs.com https://djangojobs.net/jobs/ http://djangojobbers.com https://www.indeed.com/q-Django-jobs.html https://stackoverflow.com/jobs/developer-jobs-using-django https://www.upwork.com/o/jobs/browse/skill/django-framework/ https://www.technojobs.co.uk/django-jobs https://remoteok.io/remote-django-jobs https://www.remotepython.com/jobs/ https://weworkcontract.com/python-contract-jobs Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us . Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.", "title": "Places to look for Django REST Framework Jobs" + }, + { + "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_\n.\n\n\nThe \nvalidate_\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_\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_\n.\n\n\nThe under-used \ntransform_\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_\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_` 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>>> class Meta:\n>>> model = Profile\n>>> fields = ('address', 'phone')\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ('username', 'email', 'profile')\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\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>>> 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>>> 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) > 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=\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_\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-8601 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-8601'\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 & 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" + }, + { + "location": "/topics/3.0-announcement/#django-rest-framework-30", + "text": "The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward. The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier. 3.0 is the first of three releases that have been funded by our recent Kickstarter campaign . As ever, a huge thank you to our many wonderful sponsors . 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.", + "title": "Django REST framework 3.0" + }, + { + "location": "/topics/3.0-announcement/#new-features", + "text": "Notable features of this new release include: Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit ModelSerializer class and the explicit Serializer class. A new BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. A cleaner fields API including new classes such as ListField and MultipleChoiceField . Super simple default implementations for the generic views. Support for overriding how validation errors are handled by your API. A metadata API that allows you to customize how OPTIONS requests are handled by your API. A more compact JSON output with unicode style encoding turned on by default. Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"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.", + "title": "New features" + }, + { + "location": "/topics/3.0-announcement/#rest-framework-under-the-hood", + "text": "This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. Below is an in-depth guide to the API changes and migration notes for 3.0.", + "title": "REST framework: Under the hood." + }, + { + "location": "/topics/3.0-announcement/#request-objects", + "text": "", + "title": "Request objects" + }, + { + "location": "/topics/3.0-announcement/#the-data-and-query_params-properties", + "text": "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: # Do this...\nExampleSerializer(data=request.data) Instead of passing the files argument separately: # Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES) The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params .", + "title": "The .data and .query_params properties." + }, + { + "location": "/topics/3.0-announcement/#serializers", + "text": "", + "title": "Serializers" + }, + { + "location": "/topics/3.0-announcement/#single-step-object-creation", + "text": "Previously the serializers used a two-step object creation, as follows: Validating the data would create an object instance. This instance would be available as serializer.object . Calling serializer.save() would then save the object instance to the database. This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons: Some 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 .save() is called. Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. ExampleModel.objects.create(...) . Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. The 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? We now use single-step object creation, like so: Validating the data makes the cleaned data available as serializer.validated_data . Calling serializer.save() then saves and returns the new object instance. The resulting API changes are further detailed below.", + "title": "Single-step object creation." + }, + { + "location": "/topics/3.0-announcement/#the-create-and-update-methods", + "text": "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. The following example from the tutorial previously used restore_object() to handle both creating and updating object instances. def 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) This would now be split out into two separate methods. def 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) Note that these methods should return the newly created object instance.", + "title": "The .create() and .update() methods." + }, + { + "location": "/topics/3.0-announcement/#use-validated_data-instead-of-object", + "text": "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():\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() Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments. The corresponding code would now look like this: if 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.", + "title": "Use .validated_data instead of .object." + }, + { + "location": "/topics/3.0-announcement/#using-is_validraise_exceptiontrue", + "text": "The .is_valid() method now takes an optional boolean flag, raise_exception . Calling .is_valid(raise_exception=True) will cause a ValidationError 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. The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key. This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.", + "title": "Using .is_valid(raise_exception=True)" + }, + { + "location": "/topics/3.0-announcement/#using-serializersvalidationerror", + "text": "Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError . This has now been altered so that it inherits from the standard APIException base class. The reason behind this is that Django's ValidationError 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. For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the serializers.ValidationError exception class, and not Django's built-in exception. We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.", + "title": "Using serializers.ValidationError." + }, + { + "location": "/topics/3.0-announcement/#change-to-validate_field_name", + "text": "The validate_ 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: def 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 This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual. Because .validate_ 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 .validate() instead. You can either return non_field_errors from the validate method by raising a simple ValidationError def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error') Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError , like so: def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'}) This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.", + "title": "Change to validate_<field_name>." + }, + { + "location": "/topics/3.0-announcement/#removal-of-transform_field_name", + "text": "The under-used transform_ on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style. For example: def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret Dropping 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. If you absolutely need to preserve transform_ 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: class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_` 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", + "title": "Removal of transform_<field_name>." + }, + { + "location": "/topics/3.0-announcement/#differences-between-modelserializer-validation-and-modelform", + "text": "This change also means that we no longer use the .full_clean() 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 ModelSerializer classes that can't also be easily replicated on regular Serializer classes. For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different. The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm . Use the serializer .validate() method to perform a final validation step on incoming data where required. There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate() . You can do so by explicitly instantiating a model instance in the .validate() method. def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.", + "title": "Differences between ModelSerializer validation and ModelForm." + }, + { + "location": "/topics/3.0-announcement/#writable-nested-serialization", + "text": "REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: There can be complex dependencies involved in order of saving multiple related model instances. It's unclear what behavior the user should expect when related models are passed None data. It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. Using the depth option on ModelSerializer will now create read-only nested serializers by default. If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example: >>> class ProfileSerializer(serializers.ModelSerializer):\n>>> class Meta:\n>>> model = Profile\n>>> fields = ('address', 'phone')\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ('username', 'email', 'profile')\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\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. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly. class 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 The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.", + "title": "Writable nested serialization." + }, + { + "location": "/topics/3.0-announcement/#printable-serializer-representations", + "text": "Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. For instance, given the following example model: class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User) Let's create a simple ModelSerializer class corresponding to the LocationRating model. class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating We can now inspect the serializer representation in the Django shell, using python manage.py shell ... >>> serializer = LocationRatingSerializer()\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())", + "title": "Printable serializer representations." + }, + { + "location": "/topics/3.0-announcement/#the-extra_kwargs-option", + "text": "The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs . class 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 } Alternatively, specify the field explicitly on the serializer class: class 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') The read_only_fields option remains as a convenient shortcut for the more common case.", + "title": "The extra_kwargs option." + }, + { + "location": "/topics/3.0-announcement/#changes-to-hyperlinkedmodelserializer", + "text": "The view_name and lookup_field options have been moved to PendingDeprecation . They are no longer required, as you can use the extra_kwargs argument instead: class 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 } Alternatively, specify the field explicitly on the serializer class: class 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')", + "title": "Changes to HyperlinkedModelSerializer." + }, + { + "location": "/topics/3.0-announcement/#fields-for-model-methods-and-properties", + "text": "With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model: class 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) You can include expiry_date as a field option on a ModelSerializer class. class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date') These fields will be mapped to serializers.ReadOnlyField() instances. >>> serializer = InvitationSerializer()\n>>> print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()", + "title": "Fields for model methods and properties." + }, + { + "location": "/topics/3.0-announcement/#the-listserializer-class", + "text": "The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer):\n child = UserSerializer() You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior. See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid() , .data , .save() and so on.", + "title": "The ListSerializer class." + }, + { + "location": "/topics/3.0-announcement/#the-baseserializer-class", + "text": "REST framework now includes a simple BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns an errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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.", + "title": "The BaseSerializer class." + }, + { + "location": "/topics/3.0-announcement/#read-only-baseserializer-classes", + "text": "To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @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)", + "title": "Read-only BaseSerializer classes." + }, + { + "location": "/topics/3.0-announcement/#read-write-baseserializer-classes", + "text": "To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class 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) > 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)", + "title": "Read-write BaseSerializer classes." + }, + { + "location": "/topics/3.0-announcement/#creating-new-generic-serializers-with-baseserializer", + "text": "The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class 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)", + "title": "Creating new generic serializers with BaseSerializer." + }, + { + "location": "/topics/3.0-announcement/#serializer-fields", + "text": "", + "title": "Serializer fields" + }, + { + "location": "/topics/3.0-announcement/#the-field-and-readonly-field-classes", + "text": "There are some minor tweaks to the field base classes. Previously we had these two base classes: Field as the base class for read-only fields. A default implementation was included for serializing data. WritableField as the base class for read-write fields. We now use the following: 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.", + "title": "The Field and ReadOnly field classes." + }, + { + "location": "/topics/3.0-announcement/#the-required-allow_null-allow_blank-and-default-arguments", + "text": "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. The following set of arguments are used to control validation of empty values: required=False : The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen. default= : The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen. allow_null=True : None is a valid input. allow_blank=True : '' is valid input. For CharField and subclasses only. Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required. The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.", + "title": "The required, allow_null, allow_blank and default arguments." + }, + { + "location": "/topics/3.0-announcement/#coercing-output-types", + "text": "The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField 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.", + "title": "Coercing output types." + }, + { + "location": "/topics/3.0-announcement/#removal-of-validate", + "text": "The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value() . class 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 Previously validation errors could be raised in either .to_native() or .validate() , making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.", + "title": "Removal of .validate()." + }, + { + "location": "/topics/3.0-announcement/#the-listfield-class", + "text": "The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) You can also use a declarative style to create new subclasses of ListField , like this: class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100) We can now use the ScoresField class inside another serializer: scores = ScoresField() See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid() , .data , .save() and so on.", + "title": "The ListField class." + }, + { + "location": "/topics/3.0-announcement/#the-choicefield-class-may-now-accept-a-flat-list", + "text": "The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value) . The following is now valid: color = ChoiceField(choices=['red', 'green', 'blue'])", + "title": "The ChoiceField class may now accept a flat list." + }, + { + "location": "/topics/3.0-announcement/#the-multiplechoicefield-class", + "text": "The MultipleChoiceField class has been added. This field acts like ChoiceField , but returns a set, which may include none, one or many of the valid choices.", + "title": "The MultipleChoiceField class." + }, + { + "location": "/topics/3.0-announcement/#changes-to-the-custom-field-api", + "text": "The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value) . The field_from_native() and field_to_native() 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... def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__ Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation() . Use get_value to modify the data value passed to_internal_value() . For example: def 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__", + "title": "Changes to the custom field API." + }, + { + "location": "/topics/3.0-announcement/#explicit-queryset-required-on-relational-fields", + "text": "Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a ModelSerializer . This code would be valid in 2.4.3 : class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account However this code would not be valid in 3.0 : # Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ... The 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 ModelSerializer classes and explicit Serializer classes. class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True .", + "title": "Explicit queryset required on relational fields." + }, + { + "location": "/topics/3.0-announcement/#optional-argument-to-serializermethodfield", + "text": "The argument to SerializerMethodField is now optional, and defaults to get_ . For example the following is valid: class 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) In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code will raise an error : billing_details = serializers.SerializerMethodField('get_billing_details')", + "title": "Optional argument to SerializerMethodField." + }, + { + "location": "/topics/3.0-announcement/#enforcing-consistent-source-usage", + "text": "I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required. The following usage will now raise an error : email = serializers.EmailField(source='email')", + "title": "Enforcing consistent source usage." + }, + { + "location": "/topics/3.0-announcement/#the-uniquevalidator-and-uniquetogethervalidator-classes", + "text": "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\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 ) The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names. class 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 )]", + "title": "The UniqueValidator and UniqueTogetherValidator classes." + }, + { + "location": "/topics/3.0-announcement/#the-uniquefordatevalidator-classes", + "text": "REST framework also now includes explicit validator classes for validating the unique_for_date , unique_for_month , and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean() . These classes are documented in the Validators section of the documentation.", + "title": "The UniqueForDateValidator classes." + }, + { + "location": "/topics/3.0-announcement/#generic-views", + "text": "", + "title": "Generic views" + }, + { + "location": "/topics/3.0-announcement/#simplification-of-view-logic", + "text": "The view logic for the default method handlers has been significantly simplified, due to the new serializers API.", + "title": "Simplification of view logic." + }, + { + "location": "/topics/3.0-announcement/#changes-to-prepost-save-hooks", + "text": "The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer) . These methods should save the object instance by calling serializer.save() , adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: def 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) The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance) , which should delete the instance and perform any custom actions. def 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()", + "title": "Changes to pre/post save hooks." + }, + { + "location": "/topics/3.0-announcement/#removal-of-view-attributes", + "text": "The .object and .object_list 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. I would personally recommend that developers treat view instances as immutable objects in their application code.", + "title": "Removal of view attributes." + }, + { + "location": "/topics/3.0-announcement/#put-as-create", + "text": "Allowing PUT 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 404 responses. Both styles \" PUT as 404\" and \" PUT 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. If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.", + "title": "PUT as create." + }, + { + "location": "/topics/3.0-announcement/#customizing-error-responses", + "text": "The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly. This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.", + "title": "Customizing error responses." + }, + { + "location": "/topics/3.0-announcement/#the-metadata-api", + "text": "Behavior for dealing with OPTIONS 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. This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.", + "title": "The metadata API" + }, + { + "location": "/topics/3.0-announcement/#serializers-as-html-forms", + "text": "REST framework 3.0 includes templated HTML form rendering for serializers. This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release. Significant changes that you do need to be aware of include: Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API. Nested lists of HTML forms are not yet supported, but are planned for 3.1. Because we now use templated HTML form generation, the widget option is no longer available for serializer fields . You can instead control the template that is used for a given field, by using the style dictionary.", + "title": "Serializers as HTML forms" + }, + { + "location": "/topics/3.0-announcement/#the-style-keyword-argument-for-serializer-fields", + "text": "The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with. For example, to use a textarea control instead of the default input control, you would use the following\u2026 additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n) Similarly, to use a radio button control instead of the default select control, you would use the following\u2026 color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n) This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.", + "title": "The style keyword argument for serializer fields." + }, + { + "location": "/topics/3.0-announcement/#api-style", + "text": "There are some improvements in the default style we use in our API responses.", + "title": "API style" + }, + { + "location": "/topics/3.0-announcement/#unicode-json-by-default", + "text": "Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting: REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}", + "title": "Unicode JSON by default." + }, + { + "location": "/topics/3.0-announcement/#compact-json-by-default", + "text": "We now output compact JSON in responses by default. For example, we return: {\"email\":\"amy@example.com\",\"is_admin\":true} Instead of the following: {\"email\": \"amy@example.com\", \"is_admin\": true} The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed: REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}", + "title": "Compact JSON by default." + }, + { + "location": "/topics/3.0-announcement/#file-fields-as-urls", + "text": "The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files . You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key: REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n} You can also modify serializer fields individually, using the use_url argument: uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the request 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 https://example.com/url_path/filename.txt . For example: context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data) If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt .", + "title": "File fields as URLs" + }, + { + "location": "/topics/3.0-announcement/#throttle-headers-using-retry-after", + "text": "The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.", + "title": "Throttle headers using Retry-After." + }, + { + "location": "/topics/3.0-announcement/#date-and-time-objects-as-iso-8601-strings-in-serializer-data", + "text": "Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date , Time and DateTime objects, and later coerced to strings by the renderer. You can modify this behavior globally by settings the existing DATE_FORMAT , DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8601' will result in native objects being returned in serializer data. REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n} You can also modify serializer fields individually, using the date_format , time_format and datetime_format arguments: # Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)", + "title": "Date and time objects as ISO-8601 strings in serializer data." + }, + { + "location": "/topics/3.0-announcement/#decimals-as-strings-in-serializer-data", + "text": "Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer. You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key. REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n} Or modify it on an individual serializer field, using the coerce_to_string keyword argument. # 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) The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.", + "title": "Decimals as strings in serializer data." + }, + { + "location": "/topics/3.0-announcement/#miscellaneous-notes", + "text": "The serializer ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1. Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party \"autocomplete\" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand. Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still create language files with Django if you wish to localize them. APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string . If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.", + "title": "Miscellaneous notes" + }, + { + "location": "/topics/3.0-announcement/#whats-coming-next", + "text": "3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes. The 3.1 release is planned to address improvements in the following components: Public API for using serializers as HTML forms. Request parsing, mediatypes & the implementation of the browsable API. Introduction of a new pagination API. Better support for API versioning. The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API. You can follow development on the GitHub site, where we use milestones to indicate planning timescales .", + "title": "What's coming next" + }, + { + "location": "/topics/3.1-announcement/", + "text": "Django REST framework 3.1\n\n\nThe 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.\n\n\nSome highlights include:\n\n\n\n\nA super-smart cursor pagination scheme.\n\n\nAn improved pagination API, supporting header or in-body pagination styles.\n\n\nPagination controls rendering in the browsable API.\n\n\nBetter support for API versioning.\n\n\nBuilt-in internationalization support.\n\n\nSupport for Django 1.8's \nHStoreField\n and \nArrayField\n.\n\n\n\n\n\n\nPagination\n\n\nThe pagination API has been improved, making it both easier to use, and more powerful.\n\n\nA guide to the headline features follows. For full details, see \nthe pagination documentation\n.\n\n\nNote that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.\n\n\n\n\nThe \nPAGINATE_BY\n settings key will continue to work but is now pending deprecation. The more obviously named \nPAGE_SIZE\n settings key should now be used instead.\n\n\nThe \nPAGINATE_BY_PARAM\n, \nMAX_PAGINATE_BY\n settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.\n\n\nThe \npaginate_by\n, \npage_query_param\n, \npaginate_by_param\n and \nmax_paginate_by\n generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.\n\n\nThe \npagination_serializer_class\n view attribute and \nDEFAULT_PAGINATION_SERIALIZER_CLASS\n settings key \nare no longer valid\n. The pagination API does not use serializers to determine the output format, and you'll need to instead override the \nget_paginated_response\n method on a pagination class in order to specify how the output format is controlled.\n\n\n\n\nNew pagination schemes.\n\n\nUntil now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.\n\n\nThe cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for \nthis blog post\n on the subject.\n\n\nPagination controls in the browsable API.\n\n\nPaginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:\n\n\n\n\nThe cursor based pagination renders a more simple style of control:\n\n\n\n\nSupport for header-based pagination.\n\n\nThe pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the \nLink\n or \nContent-Range\n headers.\n\n\nFor more information, see the \ncustom pagination styles\n documentation.\n\n\n\n\nVersioning\n\n\nWe've made it \neasier to build versioned APIs\n. Built-in schemes for versioning include both URL based and Accept header based variations.\n\n\nWhen using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.\n\n\nFor example, when using \nNamespaceVersioning\n, and the following hyperlinked serializer:\n\n\nclass AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ('account_name', 'users')\n\n\n\nThe output representation would match the version used on the incoming request. Like so:\n\n\nGET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}\n\n\n\n\n\nInternationalization\n\n\nREST framework now includes a built-in set of translations, and \nsupports internationalized error responses\n. This allows you to either change the default language, or to allow clients to specify the language via the \nAccept-Language\n header.\n\n\nYou can change the default language by using the standard Django \nLANGUAGE_CODE\n setting:\n\n\nLANGUAGE_CODE = \"es-es\"\n\n\n\nYou can turn on per-request language requests by adding \nLocalMiddleware\n to your \nMIDDLEWARE_CLASSES\n setting:\n\n\nMIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n\n\n\nWhen per-request internationalization is enabled, client requests will respect the \nAccept-Language\n header where possible. For example, let's make a request for an unsupported media type:\n\n\nRequest\n\n\nGET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n\n\n\nResponse\n\n\nHTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n}\n\n\n\nNote that the structure of the error responses is still the same. We still have a \ndetail\n key in the response. If needed you can modify this behavior too, by using a \ncustom exception handler\n.\n\n\nWe include built-in translations both for standard exception cases, and for serializer validation errors.\n\n\nThe full list of supported languages can be found on our \nTransifex project page\n.\n\n\nIf you only wish to support a subset of the supported languages, use Django's standard \nLANGUAGES\n setting:\n\n\nLANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n\n\n\nFor more details, see the \ninternationalization documentation\n.\n\n\nMany thanks to \nCraig Blaszczyk\n for helping push this through.\n\n\n\n\nNew field types\n\n\nDjango 1.8's new \nArrayField\n, \nHStoreField\n and \nUUIDField\n are now all fully supported.\n\n\nThis work also means that we now have both \nserializers.DictField()\n, and \nserializers.ListField()\n types, allowing you to express and validate a wider set of representations.\n\n\nIf you're building a new 1.8 project, then you should probably consider using \nUUIDField\n as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:\n\n\nhttp://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d\n\n\n\n\n\nModelSerializer API\n\n\nThe serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.\n\n\nFor more information, see the documentation on \ncustomizing field mappings\n for ModelSerializer classes.\n\n\n\n\nMoving packages out of core\n\n\nWe've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to \npip install\n the new packages, and change any import paths.\n\n\nWe're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.\n\n\nThe change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained \nDjango OAuth toolkit\n has now been promoted as our recommended option for integrating OAuth support.\n\n\nThe following packages are now moved out of core and should be separately installed:\n\n\n\n\nOAuth - \ndjangorestframework-oauth\n\n\nXML - \ndjangorestframework-xml\n\n\nYAML - \ndjangorestframework-yaml\n\n\nJSONP - \ndjangorestframework-jsonp\n\n\n\n\nIt's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:\n\n\npip install djangorestframework-xml\n\n\n\nAnd modify your settings, like so:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n}\n\n\n\nThanks go to the latest member of our maintenance team, \nJos\u00e9 Padilla\n, for handling this work and taking on ownership of these packages.\n\n\n\n\nDeprecations\n\n\nThe \nrequest.DATA\n, \nrequest.FILES\n and \nrequest.QUERY_PARAMS\n attributes move from pending deprecation, to deprecated. Use \nrequest.data\n and \nrequest.query_params\n instead, as discussed in the 3.0 release notes.\n\n\nThe ModelSerializer Meta options for \nwrite_only_fields\n, \nview_name\n and \nlookup_field\n are also moved from pending deprecation, to deprecated. Use \nextra_kwargs\n instead, as discussed in the 3.0 release notes.\n\n\nAll these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.\n\n\n\n\nWhat's next?\n\n\nThe next focus will be on HTML renderings of API output and will include:\n\n\n\n\nHTML form rendering of serializers.\n\n\nFiltering controls built-in to the browsable API.\n\n\nAn alternative admin-style interface.\n\n\n\n\nThis will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.", + "title": "3.1 Announcement" + }, + { + "location": "/topics/3.1-announcement/#django-rest-framework-31", + "text": "The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality. Some highlights include: A super-smart cursor pagination scheme. An improved pagination API, supporting header or in-body pagination styles. Pagination controls rendering in the browsable API. Better support for API versioning. Built-in internationalization support. Support for Django 1.8's HStoreField and ArrayField .", + "title": "Django REST framework 3.1" + }, + { + "location": "/topics/3.1-announcement/#pagination", + "text": "The pagination API has been improved, making it both easier to use, and more powerful. A guide to the headline features follows. For full details, see the pagination documentation . Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes. The PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead. The PAGINATE_BY_PARAM , MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The paginate_by , page_query_param , paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid . The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.", + "title": "Pagination" + }, + { + "location": "/topics/3.1-announcement/#new-pagination-schemes", + "text": "Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.", + "title": "New pagination schemes." + }, + { + "location": "/topics/3.1-announcement/#pagination-controls-in-the-browsable-api", + "text": "Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API: The cursor based pagination renders a more simple style of control:", + "title": "Pagination controls in the browsable API." + }, + { + "location": "/topics/3.1-announcement/#support-for-header-based-pagination", + "text": "The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers. For more information, see the custom pagination styles documentation.", + "title": "Support for header-based pagination." + }, + { + "location": "/topics/3.1-announcement/#versioning", + "text": "We've made it easier to build versioned APIs . Built-in schemes for versioning include both URL based and Accept header based variations. When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request. For example, when using NamespaceVersioning , and the following hyperlinked serializer: class AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ('account_name', 'users') The output representation would match the version used on the incoming request. Like so: GET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}", + "title": "Versioning" + }, + { + "location": "/topics/3.1-announcement/#internationalization", + "text": "REST framework now includes a built-in set of translations, and supports internationalized error responses . This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header. You can change the default language by using the standard Django LANGUAGE_CODE setting: LANGUAGE_CODE = \"es-es\" You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting: MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n] When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type: Request GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org Response HTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n} Note that the structure of the error responses is still the same. We still have a detail key in the response. If needed you can modify this behavior too, by using a custom exception handler . We include built-in translations both for standard exception cases, and for serializer validation errors. The full list of supported languages can be found on our Transifex project page . If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES setting: LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n] For more details, see the internationalization documentation . Many thanks to Craig Blaszczyk for helping push this through.", + "title": "Internationalization" + }, + { + "location": "/topics/3.1-announcement/#new-field-types", + "text": "Django 1.8's new ArrayField , HStoreField and UUIDField are now all fully supported. This work also means that we now have both serializers.DictField() , and serializers.ListField() types, allowing you to express and validate a wider set of representations. If you're building a new 1.8 project, then you should probably consider using UUIDField as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style: http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d", + "title": "New field types" + }, + { + "location": "/topics/3.1-announcement/#modelserializer-api", + "text": "The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships. For more information, see the documentation on customizing field mappings for ModelSerializer classes.", + "title": "ModelSerializer API" + }, + { + "location": "/topics/3.1-announcement/#moving-packages-out-of-core", + "text": "We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install the new packages, and change any import paths. We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework. The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained Django OAuth toolkit has now been promoted as our recommended option for integrating OAuth support. The following packages are now moved out of core and should be separately installed: OAuth - djangorestframework-oauth XML - djangorestframework-xml YAML - djangorestframework-yaml JSONP - djangorestframework-jsonp It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do: pip install djangorestframework-xml And modify your settings, like so: REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n} Thanks go to the latest member of our maintenance team, Jos\u00e9 Padilla , for handling this work and taking on ownership of these packages.", + "title": "Moving packages out of core" + }, + { + "location": "/topics/3.1-announcement/#deprecations", + "text": "The request.DATA , request.FILES and request.QUERY_PARAMS attributes move from pending deprecation, to deprecated. Use request.data and request.query_params instead, as discussed in the 3.0 release notes. The ModelSerializer Meta options for write_only_fields , view_name and lookup_field are also moved from pending deprecation, to deprecated. Use extra_kwargs instead, as discussed in the 3.0 release notes. All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.", + "title": "Deprecations" + }, + { + "location": "/topics/3.1-announcement/#whats-next", + "text": "The next focus will be on HTML renderings of API output and will include: HTML form rendering of serializers. Filtering controls built-in to the browsable API. An alternative admin-style interface. This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.", + "title": "What's next?" + }, + { + "location": "/topics/3.2-announcement/", + "text": "Django REST framework 3.2\n\n\nThe 3.2 release is the first version to include an admin interface for the browsable API.\n\n\n\n\nThis interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing \nBrowsableAPIRenderer\n, or used together with it, allowing you to switch between the two styles as required.\n\n\nWe've also fixed a huge number of issues, and made numerous cleanups and improvements.\n\n\nOver the course of the 3.1.x series we've \nresolved nearly 600 tickets\n on our GitHub issue tracker. This means we're currently running at a rate of \nclosing around 100 issues or pull requests per month\n.\n\n\nNone of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking \na look through our sponsors\n and finding out who's hiring.\n\n\nAdminRenderer\n\n\nTo include \nAdminRenderer\n simply add it to your settings:\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n\n\n\nThere are some limitations to the \nAdminRenderer\n, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.\n\n\nAlso note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.\n\n\nThe idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.\n\n\nSupported versions\n\n\nThis release drops support for Django 1.4.\n\n\nOur supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.\n\n\nDeprecations\n\n\nThere are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.\n\n\n\n\nrequest.DATA\n was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of \nrequest.data\n instead.\n\n\nrequest.QUERY_PARAMS\n was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of \nrequest.query_params\n instead.\n\n\nThe following \nModelSerializer.Meta\n options have now been removed: \nwrite_only_fields\n, \nview_name\n, \nlookup_field\n. Use the more general \nextra_kwargs\n option instead.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nModifications to list behaviors\n\n\nThere are a couple of bug fixes that are worth calling out as they introduce differing behavior.\n\n\nThese are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.\n\n\nManyToMany fields and blank=True\n\n\nWe've now added an \nallow_empty\n argument, which can be used with \nListSerializer\n, or with \nmany=True\n relationships. This is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nAs a follow-up to this we are now able to properly mirror the behavior of Django's \nModelForm\n with respect to how many-to-many fields are validated.\n\n\nPreviously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has \nblank=True\n set.\n\n\nHere's what the mapping looks like in practice:\n\n\n\n\nmodels.ManyToManyField()\n \u2192 \nserializers.PrimaryKeyRelatedField(many=True, allow_empty=False)\n\n\nmodels.ManyToManyField(blank=True)\n \u2192 \nserializers.PrimaryKeyRelatedField(many=True)\n\n\n\n\nThe upshot is this: If you have many to many fields in your models, then make sure you've included the argument \nblank=True\n if you want to allow empty inputs in the equivalent \nModelSerializer\n fields.\n\n\nList fields and allow_null\n\n\nWhen using \nallow_null\n with \nListField\n or a nested \nmany=True\n serializer the previous behavior was to allow \nnull\n values as items in the list. The behavior is now to allow \nnull\n values instead of the list.\n\n\nFor example, take the following field:\n\n\nNestedSerializer(many=True, allow_null=True)\n\n\n\nPreviously the validation behavior would be:\n\n\n\n\n[{\u2026}, null, {\u2026}]\n is \nvalid\n.\n\n\nnull\n is \ninvalid\n.\n\n\n\n\nOur validation behavior as of 3.2.0 is now:\n\n\n\n\n[{\u2026}, null, {\u2026}]\n is \ninvalid\n.\n\n\nnull\n is \nvalid\n.\n\n\n\n\nIf you want to allow \nnull\n child items, you'll need to instead specify \nallow_null\n on the child class, using an explicit \nListField\n instead of \nmany=True\n. For example:\n\n\nListField(child=NestedSerializer(allow_null=True))\n\n\n\nWhat's next?\n\n\nThe 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.\n\n\nThis release is planned to include:\n\n\n\n\nSearch and filtering controls in the browsable API and admin interface.\n\n\nImprovements and public API for the admin interface.\n\n\nImprovements and public API for our templated HTML forms and fields.\n\n\nNested object and list support in HTML forms.\n\n\n\n\nThanks once again to all our sponsors and supporters.", + "title": "3.2 Announcement" + }, + { + "location": "/topics/3.2-announcement/#django-rest-framework-32", + "text": "The 3.2 release is the first version to include an admin interface for the browsable API. This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing BrowsableAPIRenderer , or used together with it, allowing you to switch between the two styles as required. We've also fixed a huge number of issues, and made numerous cleanups and improvements. Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month . None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.", + "title": "Django REST framework 3.2" + }, + { + "location": "/topics/3.2-announcement/#adminrenderer", + "text": "To include AdminRenderer simply add it to your settings: REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n} There are some limitations to the AdminRenderer , in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those. Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates. The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.", + "title": "AdminRenderer" + }, + { + "location": "/topics/3.2-announcement/#supported-versions", + "text": "This release drops support for Django 1.4. Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.", + "title": "Supported versions" + }, + { + "location": "/topics/3.2-announcement/#deprecations", + "text": "There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy. request.DATA was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.data instead. request.QUERY_PARAMS was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.query_params instead. The following ModelSerializer.Meta options have now been removed: write_only_fields , view_name , lookup_field . Use the more general extra_kwargs option instead. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors. view.paginate_by - Use paginator.page_size instead. view.page_query_param - Use paginator.page_query_param instead. view.paginate_by_param - Use paginator.page_size_query_param instead. view.max_paginate_by - Use paginator.max_page_size instead. settings.PAGINATE_BY - Use paginator.page_size instead. settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead. settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.", + "title": "Deprecations" + }, + { + "location": "/topics/3.2-announcement/#modifications-to-list-behaviors", + "text": "There are a couple of bug fixes that are worth calling out as they introduce differing behavior. These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.", + "title": "Modifications to list behaviors" + }, + { + "location": "/topics/3.2-announcement/#manytomany-fields-and-blanktrue", + "text": "We've now added an allow_empty argument, which can be used with ListSerializer , or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input. As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated. Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set. Here's what the mapping looks like in practice: models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False) models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True) The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.", + "title": "ManyToMany fields and blank=True" + }, + { + "location": "/topics/3.2-announcement/#list-fields-and-allow_null", + "text": "When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list. For example, take the following field: NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: [{\u2026}, null, {\u2026}] is valid . null is invalid . Our validation behavior as of 3.2.0 is now: [{\u2026}, null, {\u2026}] is invalid . null is valid . If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True . For example: ListField(child=NestedSerializer(allow_null=True))", + "title": "List fields and allow_null" + }, + { + "location": "/topics/3.2-announcement/#whats-next", + "text": "The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release. This release is planned to include: Search and filtering controls in the browsable API and admin interface. Improvements and public API for the admin interface. Improvements and public API for our templated HTML forms and fields. Nested object and list support in HTML forms. Thanks once again to all our sponsors and supporters.", + "title": "What's next?" + }, + { + "location": "/topics/3.3-announcement/", + "text": "Django REST framework 3.3\n\n\nThe 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding \nthank you\n to all our wonderful sponsors and supporters.\n\n\nThe amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.\n\n\nIn order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow \n@_tomchristie\n to keep up to date with these announcements, and be among the first set of sign ups.\n\n\nWe strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.\n\n\n\n\nRelease notes\n\n\nSignificant new functionality in the 3.3 release includes:\n\n\n\n\nFilters presented as HTML controls in the browsable API.\n\n\nA \nforms API\n, allowing serializers to be rendered as HTML forms.\n\n\nDjango 1.9 support.\n\n\nA \nJSONField\n serializer field\n, corresponding to Django 1.9's Postgres \nJSONField\n model field.\n\n\nBrowsable API support \nvia AJAX\n, rather than server side request overloading.\n\n\n\n\n\n\nExample of the new filter controls\n\n\n\n\nSupported versions\n\n\nThis release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.\n\n\nThis brings our supported versions into line with Django's \ncurrently supported versions\n\n\nDeprecations\n\n\nThe AJAX based support for the browsable API means that there are a number of internal cleanups in the \nrequest\n class. For the vast majority of developers this should largely remain transparent:\n\n\n\n\nTo support form based \nPUT\n and \nDELETE\n, or to support form content types such as JSON, you should now use the \nAJAX forms\n javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.\n\n\nThe \naccept\n query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to \nuse a custom content negotiation class\n.\n\n\nThe custom \nHTTP_X_HTTP_METHOD_OVERRIDE\n header is no longer supported by default. If you require it then you'll need to \nuse custom middleware\n.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nThe \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes should now include either a \nfields\n or \nexclude\n option, although the \nfields = '__all__'\n shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings \nModelSerializer\n more closely in line with Django's \nModelForm\n behavior.", + "title": "3.3 Announcement" + }, + { + "location": "/topics/3.3-announcement/#django-rest-framework-33", + "text": "The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding thank you to all our wonderful sponsors and supporters. The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project. In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow @_tomchristie to keep up to date with these announcements, and be among the first set of sign ups. We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.", + "title": "Django REST framework 3.3" + }, + { + "location": "/topics/3.3-announcement/#release-notes", + "text": "Significant new functionality in the 3.3 release includes: Filters presented as HTML controls in the browsable API. A forms API , allowing serializers to be rendered as HTML forms. Django 1.9 support. A JSONField serializer field , corresponding to Django 1.9's Postgres JSONField model field. Browsable API support via AJAX , rather than server side request overloading. Example of the new filter controls", + "title": "Release notes" + }, + { + "location": "/topics/3.3-announcement/#supported-versions", + "text": "This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required. This brings our supported versions into line with Django's currently supported versions", + "title": "Supported versions" + }, + { + "location": "/topics/3.3-announcement/#deprecations", + "text": "The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent: To support form based PUT and DELETE , or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. The accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class . The custom HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware . The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. view.paginate_by - Use paginator.page_size instead. view.page_query_param - Use paginator.page_query_param instead. view.paginate_by_param - Use paginator.page_size_query_param instead. view.max_paginate_by - Use paginator.max_page_size instead. settings.PAGINATE_BY - Use paginator.page_size instead. settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead. settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead. The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.", + "title": "Deprecations" + }, + { + "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 & 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 & client support.\n\n\nBuilt-in support in \ncoreapi\n\n\n\n\n\n\nSwagger / OpenAPI\n\n\nSchema generation & client support.\n\n\nThe \nopenapi-codec\npackage.\n\n\n\n\n\n\nJSON Hyper-Schema\n\n\nCurrently 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 & 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" + }, + { + "location": "/topics/3.4-announcement/#django-rest-framework-34", + "text": "The 3.4 release is the first in a planned series that will be addressing schema\ngeneration, hypermedia support, API clients, and finally realtime support.", + "title": "Django REST framework 3.4" + }, + { + "location": "/topics/3.4-announcement/#funding", + "text": "The 3.4 release has been made possible a recent Mozilla grant , and by our collaborative funding model . 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 signing up for a paid plan . The 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. Every single sign-up makes a significant impact. \n Rover.com \n Sentry \n Stream Many thanks to all our awesome sponsors , and in particular to our premium backers, Rover , Sentry , and Stream .", + "title": "Funding" + }, + { + "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 Currently 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" + }, + { + "location": "/topics/3.4-announcement/#supported-versions", + "text": "The 3.4.0 release adds support for Django 1.10. The following versions of Python and Django are now supported: Django versions 1.8, 1.9, and 1.10. Python versions 2.7, 3.2(*), 3.3(*), 3.4, 3.5. (*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.", + "title": "Supported versions" + }, + { + "location": "/topics/3.4-announcement/#deprecations-and-changes", + "text": "The 3.4 release includes very limited deprecation or behavioral changes, and\nshould present a straightforward upgrade.", + "title": "Deprecations and changes" + }, + { + "location": "/topics/3.4-announcement/#use-fields-or-exclude-on-serializer-classes", + "text": "The 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: ModelSerializer and HyperlinkedModelSerializer should include either a fields \noption, or an exclude option. The fields = '__all__' shortcut may be used\nto explicitly include all fields.", + "title": "Use fields or exclude on serializer classes." + }, + { + "location": "/topics/3.4-announcement/#microsecond-precision-when-returning-time-or-datetime", + "text": "Using the default JSON renderer and directly returning a datetime or time \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 serializers.DateTimeField and serializers.TimeField . This change does not affect the default behavior when using serializers ,\nwhich is to serialize datetime and time instances into strings with\nmicrosecond precision. The serializer behavior can be modified if needed, using the DATETIME_FORMAT \nand TIME_FORMAT settings. The renderer behavior can be modified by setting a custom encoder_class \nattribute on a JSONRenderer subclass.", + "title": "Microsecond precision when returning time or datetime." + }, + { + "location": "/topics/3.4-announcement/#relational-choices-no-longer-displayed-in-options-requests", + "text": "Making an OPTIONS request to views that have a serializer choice field\nwill result in a list of the available choices being returned in the response. In 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. In order to minimise exposed information the behavior now is to not return\nchoices information for relational fields. If you want to override this new behavior you'll need to implement a custom\nmetadata class . See issue #3751 for more information on this behavioral change.", + "title": "Relational choices no longer displayed in OPTIONS requests." + }, + { + "location": "/topics/3.4-announcement/#other-improvements", + "text": "This release includes further work from a huge number of pull requests and issues . Many 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. The full set of itemized release notes are available here .", + "title": "Other improvements" + }, + { + "location": "/topics/3.5-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.5\n\n\nThe 3.5 release is the second in a planned series that is addressing schema\ngeneration, hypermedia support, API client libraries, and finally realtime support.\n\n\n\n\nFunding\n\n\nThe 3.5 release would not have been possible without our \ncollaborative funding model\n.\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n\n\n\n\n\n\n\nMany thanks to all our \nsponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, and \nMachinalis\n.\n\n\n\n\nImproved schema generation\n\n\nDocstrings on views are now pulled through into schema definitions, allowing\nyou to \nuse the schema definition to document your\u00a0API\n.\n\n\nThere is now also a shortcut function, \nget_schema_view()\n, which makes it easier to\n\nadding schema views\n to your API.\n\n\nFor example, to include a swagger schema to your API, you would do the following:\n\n\n\n\n\n\nRun \npip install django-rest-swagger\n.\n\n\n\n\n\n\nAdd \n'rest_framework_swagger'\n to your \nINSTALLED_APPS\n setting.\n\n\n\n\n\n\nInclude the schema view in your URL conf:\n\n\n\n\n\n\nfrom rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title='Example API',\n renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [\n url(r'^swagger/$', schema_view),\n ...\n]\n\n\n\n\nThere have been a large number of fixes to the schema generation. These should\nresolve issues for anyone using the latest version of the \ndjango-rest-swagger\n\npackage.\n\n\nSome of these changes do affect the resulting schema structure,\nso if you're already using schema generation you should make sure to review\n\nthe deprecation notes\n, particularly if you're currently using\na dynamic client library to interact with your API.\n\n\nFinally, we're also now exposing the schema generation as a\n\npublicly documented API\n, allowing you to more easily\noverride the behaviour.\n\n\nRequests test client\n\n\nYou can now test your project using the \nrequests\n library.\n\n\nThis exposes exactly the same interface as if you were using a standard\nrequests session instance.\n\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n\n\n\nRather than sending any HTTP requests to the network, this interface will\ncoerce all outgoing requests into WSGI, and call into your application directly.\n\n\nCore API client\n\n\nYou can also now test your project by interacting with it using the \ncoreapi\n\nclient library.\n\n\n# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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\nAgain, this will call directly into the application using the WSGI interface,\nrather than making actual network calls.\n\n\nThis is a good option if you are planning for clients to mainly interact with\nyour API using the \ncoreapi\n client library, or some other auto-generated client.\n\n\nLive tests\n\n\nOne interesting aspect of both the \nrequests\n client and the \ncoreapi\n client\nis that they allow you to write tests in such a way that they can also be made\nto run against a live service.\n\n\nBy switching the WSGI based client instances to actual instances of \nrequests.Session\n\nor \ncoreapi.Client\n you can have the test cases make actual network calls.\n\n\nBeing able to write test cases that can exercise your staging or production\nenvironment is a powerful tool. However in order to do this, you'll need to pay\nclose attention to how you handle setup and teardown to ensure a strict isolation\nof test data from other live or staging data.\n\n\nRAML support\n\n\nWe now have preliminary support for \nRAML documentation generation\n.\n\n\n\n\nFurther work on the encoding and documentation generation is planned, in order to\nmake features such as the 'Try it now' support available at a later date.\n\n\nThis work also now means that you can use the Core API client libraries to interact\nwith APIs that expose a RAML specification. The \nRAML codec\n gives some examples of\ninteracting with the Spotify API in this way.\n\n\nValidation codes\n\n\nExceptions raised by REST framework now include short code identifiers.\nWhen used together with our customizable error handling, this now allows you to\nmodify the style of API error messages.\n\n\nAs an example, this allows for the following style of error responses:\n\n\n{\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n}\n\n\n\nThis is particularly useful with validation errors, which use appropriate\ncodes to identify differing kinds of failure...\n\n\n{\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}\n\n\n\nClient upload & download support\n\n\nThe Python \ncoreapi\n client library and the Core API command line tool both\nnow fully support file \nuploads\n and \ndownloads\n.\n\n\n\n\nDeprecations\n\n\nGenerating schemas from Router\n\n\nThe router arguments for generating a schema view, such as \nschema_title\n,\nare now pending deprecation.\n\n\nInstead of using \nDefaultRouter(schema_title='Example API')\n, you should use\nthe \nget_schema_view()\n function, and include the view in your URL conf.\n\n\nMake sure to include the view before your router urls. For example:\n\n\nfrom rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n url('^$', schema_view),\n url(r'^', include(router.urls)),\n]\n\n\n\nSchema path representations\n\n\nThe \n'pk'\n identifier in schema paths is now mapped onto the actually model field\nname by default. This will typically be \n'id'\n.\n\n\nThis gives a better external representation for schemas, with less implementation\ndetail being exposed. It also reflects the behaviour of using a ModelSerializer\nclass with \nfields = '__all__'\n.\n\n\nYou can revert to the previous behaviour by setting \n'SCHEMA_COERCE_PATH_PK': False\n\nin the REST framework settings.\n\n\nSchema action name representations\n\n\nThe internal \nretrieve()\n and \ndestroy()\n method names are now coerced to an\nexternal representation of \nread\n and \ndelete\n.\n\n\nYou can revert to the previous behaviour by setting \n'SCHEMA_COERCE_METHOD_NAMES': {}\n\nin the REST framework settings.\n\n\nDjangoFilterBackend\n\n\nThe functionality of the built-in \nDjangoFilterBackend\n is now completely\nincluded by the \ndjango-filter\n package.\n\n\nYou should change your imports and REST framework filter settings as follows:\n\n\n\n\nrest_framework.filters.DjangoFilterBackend\n becomes \ndjango_filters.rest_framework.DjangoFilterBackend\n.\n\n\nrest_framework.filters.FilterSet\n becomes \ndjango_filters.rest_framework.FilterSet\n.\n\n\n\n\nThe existing imports will continue to work but are now pending deprecation.\n\n\nCoreJSON media type\n\n\nThe media type for \nCoreJSON\n is now \napplication/json+coreapi\n, rather than\nthe previous \napplication/vnd.json+coreapi\n. This brings it more into line with\nother custom media types, such as those used by Swagger and RAML.\n\n\nThe clients currently accept either media type. The old style-media type will\nbe deprecated at a later date.\n\n\nModelSerializer 'fields' and 'exclude'\n\n\nModelSerializer and HyperlinkedModelSerializer must include either a fields\noption, or an exclude option. The \nfields = '__all__'\n shortcut may be used to\nexplicitly include all fields.\n\n\nFailing to set either \nfields\n or \nexclude\n raised a pending deprecation warning\nin version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.", + "title": "3.5 Announcement" + }, + { + "location": "/topics/3.5-announcement/#django-rest-framework-35", + "text": "The 3.5 release is the second in a planned series that is addressing schema\ngeneration, hypermedia support, API client libraries, and finally realtime support.", + "title": "Django REST framework 3.5" + }, + { + "location": "/topics/3.5-announcement/#funding", + "text": "The 3.5 release would not have been possible without our collaborative funding model .\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis Many thanks to all our sponsors , and in particular to our premium backers, Rover , Sentry , Stream , and Machinalis .", + "title": "Funding" + }, + { + "location": "/topics/3.5-announcement/#improved-schema-generation", + "text": "Docstrings on views are now pulled through into schema definitions, allowing\nyou to use the schema definition to document your\u00a0API . There is now also a shortcut function, get_schema_view() , which makes it easier to adding schema views to your API. For example, to include a swagger schema to your API, you would do the following: Run pip install django-rest-swagger . Add 'rest_framework_swagger' to your INSTALLED_APPS setting. Include the schema view in your URL conf: from rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title='Example API',\n renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [\n url(r'^swagger/$', schema_view),\n ...\n] There have been a large number of fixes to the schema generation. These should\nresolve issues for anyone using the latest version of the django-rest-swagger \npackage. Some of these changes do affect the resulting schema structure,\nso if you're already using schema generation you should make sure to review the deprecation notes , particularly if you're currently using\na dynamic client library to interact with your API. Finally, we're also now exposing the schema generation as a publicly documented API , allowing you to more easily\noverride the behaviour.", + "title": "Improved schema generation" + }, + { + "location": "/topics/3.5-announcement/#requests-test-client", + "text": "You can now test your project using the requests library. This exposes exactly the same interface as if you were using a standard\nrequests session instance. client = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200 Rather than sending any HTTP requests to the network, this interface will\ncoerce all outgoing requests into WSGI, and call into your application directly.", + "title": "Requests test client" + }, + { + "location": "/topics/3.5-announcement/#core-api-client", + "text": "You can also now test your project by interacting with it using the coreapi \nclient library. # Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\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'}]) Again, this will call directly into the application using the WSGI interface,\nrather than making actual network calls. This is a good option if you are planning for clients to mainly interact with\nyour API using the coreapi client library, or some other auto-generated client.", + "title": "Core API client" + }, + { + "location": "/topics/3.5-announcement/#live-tests", + "text": "One interesting aspect of both the requests client and the coreapi client\nis that they allow you to write tests in such a way that they can also be made\nto run against a live service. By switching the WSGI based client instances to actual instances of requests.Session \nor coreapi.Client you can have the test cases make actual network calls. Being able to write test cases that can exercise your staging or production\nenvironment is a powerful tool. However in order to do this, you'll need to pay\nclose attention to how you handle setup and teardown to ensure a strict isolation\nof test data from other live or staging data.", + "title": "Live tests" + }, + { + "location": "/topics/3.5-announcement/#raml-support", + "text": "We now have preliminary support for RAML documentation generation . Further work on the encoding and documentation generation is planned, in order to\nmake features such as the 'Try it now' support available at a later date. This work also now means that you can use the Core API client libraries to interact\nwith APIs that expose a RAML specification. The RAML codec gives some examples of\ninteracting with the Spotify API in this way.", + "title": "RAML support" + }, + { + "location": "/topics/3.5-announcement/#validation-codes", + "text": "Exceptions raised by REST framework now include short code identifiers.\nWhen used together with our customizable error handling, this now allows you to\nmodify the style of API error messages. As an example, this allows for the following style of error responses: {\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n} This is particularly useful with validation errors, which use appropriate\ncodes to identify differing kinds of failure... {\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}", + "title": "Validation codes" + }, + { + "location": "/topics/3.5-announcement/#client-upload-download-support", + "text": "The Python coreapi client library and the Core API command line tool both\nnow fully support file uploads and downloads .", + "title": "Client upload & download support" + }, + { + "location": "/topics/3.5-announcement/#deprecations", + "text": "", + "title": "Deprecations" + }, + { + "location": "/topics/3.5-announcement/#generating-schemas-from-router", + "text": "The router arguments for generating a schema view, such as schema_title ,\nare now pending deprecation. Instead of using DefaultRouter(schema_title='Example API') , you should use\nthe get_schema_view() function, and include the view in your URL conf. Make sure to include the view before your router urls. For example: from rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n url('^$', schema_view),\n url(r'^', include(router.urls)),\n]", + "title": "Generating schemas from Router" + }, + { + "location": "/topics/3.5-announcement/#schema-path-representations", + "text": "The 'pk' identifier in schema paths is now mapped onto the actually model field\nname by default. This will typically be 'id' . This gives a better external representation for schemas, with less implementation\ndetail being exposed. It also reflects the behaviour of using a ModelSerializer\nclass with fields = '__all__' . You can revert to the previous behaviour by setting 'SCHEMA_COERCE_PATH_PK': False \nin the REST framework settings.", + "title": "Schema path representations" + }, + { + "location": "/topics/3.5-announcement/#schema-action-name-representations", + "text": "The internal retrieve() and destroy() method names are now coerced to an\nexternal representation of read and delete . You can revert to the previous behaviour by setting 'SCHEMA_COERCE_METHOD_NAMES': {} \nin the REST framework settings.", + "title": "Schema action name representations" + }, + { + "location": "/topics/3.5-announcement/#djangofilterbackend", + "text": "The functionality of the built-in DjangoFilterBackend is now completely\nincluded by the django-filter package. You should change your imports and REST framework filter settings as follows: rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend . rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet . The existing imports will continue to work but are now pending deprecation.", + "title": "DjangoFilterBackend" + }, + { + "location": "/topics/3.5-announcement/#corejson-media-type", + "text": "The media type for CoreJSON is now application/json+coreapi , rather than\nthe previous application/vnd.json+coreapi . This brings it more into line with\nother custom media types, such as those used by Swagger and RAML. The clients currently accept either media type. The old style-media type will\nbe deprecated at a later date.", + "title": "CoreJSON media type" + }, + { + "location": "/topics/3.5-announcement/#modelserializer-fields-and-exclude", + "text": "ModelSerializer and HyperlinkedModelSerializer must include either a fields\noption, or an exclude option. The fields = '__all__' shortcut may be used to\nexplicitly include all fields. Failing to set either fields or exclude raised a pending deprecation warning\nin version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.", + "title": "ModelSerializer 'fields' and 'exclude'" + }, + { + "location": "/topics/3.6-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.6\n\n\nThe 3.6 release adds two major new features to REST framework.\n\n\n\n\nBuilt-in interactive API documentation support.\n\n\nA new JavaScript client\u00a0library.\n\n\n\n\n\n\nAbove: The interactive API documentation.\n\n\n\n\nFunding\n\n\nThe 3.6 release would not have been possible without our \nbacking from Mozilla\n to the project, and our \ncollaborative funding\u00a0model\n.\n\n\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n \nMicroPyramid\n\n\n\n\n\n\n\n\nMany thanks to all our \nsponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, \nRollbar\n, and \nMicroPyramid\n.\n\n\n\n\nInteractive API documentation\n\n\nREST framework's new API documentation supports a number of features:\n\n\n\n\nLive API interaction.\n\n\nSupport for various authentication schemes.\n\n\nCode snippets for the Python, JavaScript, and Command Line clients.\n\n\n\n\nThe \ncoreapi\n library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The \npygments\n and \nmarkdown\n\nlibraries are optional but recommended.\n\n\nTo install the API documentation, you'll need to include it in your projects URLconf:\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n]\n\n\n\nOnce installed you should see something a little like this:\n\n\n\n\nWe'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations.\n\n\nFor more information on documenting your API endpoints see the \n\"Documenting your API\"\n section.\n\n\n\n\nJavaScript client library\n\n\nThe JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly.\n\n\nHere's a brief example that demonstrates:\n\n\n\n\nLoading the client library and schema.\n\n\nInstantiating an authenticated client.\n\n\nMaking an API request using the client.\n\n\n\n\nindex.html\n\n\n\n \n \n \n \n \n\n\n\n\nThe JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API.\n\n\nThe client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned.\n\n\nFor more details see the \nJavaScript client library documentation\n.\n\n\nAuthentication classes for the Python client library\n\n\nPrevious authentication support in the Python client library was limited to\nallowing users to provide explicit header values.\n\n\nWe now have better support for handling the details of authentication, with\nthe introduction of the \nBasicAuthentication\n, \nTokenAuthentication\n, and\n\nSessionAuthentication\n schemes.\n\n\nYou can include the authentication scheme when instantiating a new client.\n\n\nauth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth)\n\n\n\nFor more information see the \nPython client library documentation\n.\n\n\n\n\nDeprecations\n\n\nUpdating coreapi\n\n\nIf you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)\n\n\nGenerating schemas from Router\n\n\nThe 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as \nschema_title\n, \nschema_url\n and \nschema_renderers\n, have now been escalated to a\n\"deprecated\" warning.\n\n\nInstead of using \nDefaultRouter(schema_title='Example API')\n, you should use the \nget_schema_view()\n function, and include the view explicitly in your URL conf.\n\n\nDjangoFilterBackend\n\n\nThe 3.5 \"pending deprecation\" warning of the built-in \nDjangoFilterBackend\n has now\nbeen escalated to a \"deprecated\" warning.\n\n\nYou should change your imports and REST framework filter settings as follows:\n\n\n\n\nrest_framework.filters.DjangoFilterBackend\n becomes \ndjango_filters.rest_framework.DjangoFilterBackend\n.\n\n\nrest_framework.filters.FilterSet\n becomes \ndjango_filters.rest_framework.FilterSet\n.\n\n\n\n\n\n\nWhat's next\n\n\nThere are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following:\n\n\n\n\nSupport for private API docs, requiring login.\n\n\nFile upload and download support in the JavaScript client & API docs.\n\n\nComprehensive documentation for the JavaScript client library.\n\n\nAutomatically including authentication details in the API doc code snippets.\n\n\nAdding authentication support in the command line client.\n\n\nSupport for loading Swagger and other schemas in the JavaScript client.\n\n\nImproved support for documenting parameter schemas and response schemas.\n\n\nRefining the API documentation interaction modal.\n\n\n\n\nOnce work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", + "title": "3.6 Announcement" + }, + { + "location": "/topics/3.6-announcement/#django-rest-framework-36", + "text": "The 3.6 release adds two major new features to REST framework. Built-in interactive API documentation support. A new JavaScript client\u00a0library. Above: The interactive API documentation.", + "title": "Django REST framework 3.6" + }, + { + "location": "/topics/3.6-announcement/#funding", + "text": "The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding\u00a0model . If you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis \n Rollbar \n MicroPyramid Many thanks to all our sponsors , and in particular to our premium backers, Rover , Sentry , Stream , Machinalis , Rollbar , and MicroPyramid .", + "title": "Funding" + }, + { + "location": "/topics/3.6-announcement/#interactive-api-documentation", + "text": "REST framework's new API documentation supports a number of features: Live API interaction. Support for various authentication schemes. Code snippets for the Python, JavaScript, and Command Line clients. The coreapi library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The pygments and markdown \nlibraries are optional but recommended. To install the API documentation, you'll need to include it in your projects URLconf: from rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n] Once installed you should see something a little like this: We'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations. For more information on documenting your API endpoints see the \"Documenting your API\" section.", + "title": "Interactive API documentation" + }, + { + "location": "/topics/3.6-announcement/#javascript-client-library", + "text": "The JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly. Here's a brief example that demonstrates: Loading the client library and schema. Instantiating an authenticated client. Making an API request using the client. index.html \n \n \n \n \n \n The JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API. The client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned. For more details see the JavaScript client library documentation .", + "title": "JavaScript client library" + }, + { + "location": "/topics/3.6-announcement/#authentication-classes-for-the-python-client-library", + "text": "Previous authentication support in the Python client library was limited to\nallowing users to provide explicit header values. We now have better support for handling the details of authentication, with\nthe introduction of the BasicAuthentication , TokenAuthentication , and SessionAuthentication schemes. You can include the authentication scheme when instantiating a new client. auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth) For more information see the Python client library documentation .", + "title": "Authentication classes for the Python client library" + }, + { + "location": "/topics/3.6-announcement/#deprecations", + "text": "", + "title": "Deprecations" + }, + { + "location": "/topics/3.6-announcement/#updating-coreapi", + "text": "If you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)", + "title": "Updating coreapi" + }, + { + "location": "/topics/3.6-announcement/#generating-schemas-from-router", + "text": "The 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as schema_title , schema_url and schema_renderers , have now been escalated to a\n\"deprecated\" warning. Instead of using DefaultRouter(schema_title='Example API') , you should use the get_schema_view() function, and include the view explicitly in your URL conf.", + "title": "Generating schemas from Router" + }, + { + "location": "/topics/3.6-announcement/#djangofilterbackend", + "text": "The 3.5 \"pending deprecation\" warning of the built-in DjangoFilterBackend has now\nbeen escalated to a \"deprecated\" warning. You should change your imports and REST framework filter settings as follows: rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend . rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet .", + "title": "DjangoFilterBackend" + }, + { + "location": "/topics/3.6-announcement/#whats-next", + "text": "There are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following: Support for private API docs, requiring login. File upload and download support in the JavaScript client & API docs. Comprehensive documentation for the JavaScript client library. Automatically including authentication details in the API doc code snippets. Adding authentication support in the command line client. Support for loading Swagger and other schemas in the JavaScript client. Improved support for documenting parameter schemas and response schemas. Refining the API documentation interaction modal. Once work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", + "title": "What's next" + }, + { + "location": "/topics/3.7-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.7\n\n\nThe 3.7 release focuses on improvements to schema generation and the interactive API documentation.\n\n\nThis release has been made possible by \nBayer\n who have sponsored the release.\n\n\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n\n\n\n\n\n\n\nAs well as our release sponsor, we'd like to say thanks in particular our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, and \nRollbar\n.\n\n\n\n\nCustomizing API docs & schema generation.\n\n\nThe schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.\n\n\nIn order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.\n\n\nLet's take a quick look at using the new functionality...\n\n\nThe \nAPIView\n class has a \nschema\n attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the \nAutoSchema\n class.\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior.\n\n\n\nWe can remove a view from the API schema and docs, like so:\n\n\nclass CustomView(APIView):\n schema = None\n\n\n\nIf we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...\n\n\nclass CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ])\n\n\n\nTo ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the \nManualSchema\n class instead...\n\n\nclass CustomView(APIView):\n schema = ManualSchema(fields=[...])\n\n\n\nFor more advanced behaviors you can subclass \nAutoSchema\n to provide for customized schema generation, and apply that to particular views.\n\n\nclass CustomView(APIView):\n schema = CustomizedSchemaGeneration()\n\n\n\nFor full details on the new functionality, please see the \nSchema Documentation\n.\n\n\n\n\nDjango 2.0 support\n\n\nREST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.\n\n\n\n\nMinor fixes and improvements\n\n\nThere are a large number of minor fixes and improvements in this release. See the \nrelease notes\n page for a complete listing.\n\n\nThe number of \nopen tickets against the project\n currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.\n\n\n\n\nDeprecations\n\n\nexclude_from_schema\n\n\nBoth \nAPIView.exclude_from_schema\n and the \nexclude_from_schema\n argument to the \n@api_view\n decorator and now \nPendingDeprecation\n. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.\n\n\nFor \nAPIView\n you should instead set a \nschema = None\n attribute on the view class.\n\n\nFor function based views the \n@schema\n decorator can be used to exclude the view from the schema, by using \n@schema(None)\n.\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.\n\n\nThe functionality remains fully available, but is instead provided in the \ndjango-filter\n package.\n\n\n\n\nWhat's next\n\n\nWe're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.\n\n\nThis will likely be timed so that any REST framework development here ties in with similar work on \nAPI Star\n.", + "title": "3.7 Announcement" + }, + { + "location": "/topics/3.7-announcement/#django-rest-framework-37", + "text": "The 3.7 release focuses on improvements to schema generation and the interactive API documentation. This release has been made possible by Bayer who have sponsored the release.", + "title": "Django REST framework 3.7" + }, + { + "location": "/topics/3.7-announcement/#funding", + "text": "If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . \n Rover.com \n Sentry \n Stream \n Machinalis \n Rollbar As well as our release sponsor, we'd like to say thanks in particular our premium backers, Rover , Sentry , Stream , Machinalis , and Rollbar .", + "title": "Funding" + }, + { + "location": "/topics/3.7-announcement/#customizing-api-docs-schema-generation", + "text": "The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view. In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features. Let's take a quick look at using the new functionality... The APIView class has a schema attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the AutoSchema class. from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior. We can remove a view from the API schema and docs, like so: class CustomView(APIView):\n schema = None If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily... class CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ]) To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the ManualSchema class instead... class CustomView(APIView):\n schema = ManualSchema(fields=[...]) For more advanced behaviors you can subclass AutoSchema to provide for customized schema generation, and apply that to particular views. class CustomView(APIView):\n schema = CustomizedSchemaGeneration() For full details on the new functionality, please see the Schema Documentation .", + "title": "Customizing API docs & schema generation." + }, + { + "location": "/topics/3.7-announcement/#django-20-support", + "text": "REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.", + "title": "Django 2.0 support" + }, + { + "location": "/topics/3.7-announcement/#minor-fixes-and-improvements", + "text": "There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing. The number of open tickets against the project currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.", + "title": "Minor fixes and improvements" + }, + { + "location": "/topics/3.7-announcement/#deprecations", + "text": "", + "title": "Deprecations" + }, + { + "location": "/topics/3.7-announcement/#exclude_from_schema", + "text": "Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator and now PendingDeprecation . They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9. For APIView you should instead set a schema = None attribute on the view class. For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None) .", + "title": "exclude_from_schema" + }, + { + "location": "/topics/3.7-announcement/#djangofilterbackend", + "text": "The DjangoFilterBackend was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework. The functionality remains fully available, but is instead provided in the django-filter package.", + "title": "DjangoFilterBackend" + }, + { + "location": "/topics/3.7-announcement/#whats-next", + "text": "We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints. This will likely be timed so that any REST framework development here ties in with similar work on API Star .", + "title": "What's next" + }, + { + "location": "/topics/3.8-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.8\n\n\nThe 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying\nthe foundations for future changes.\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by\n\nsigning up for a paid\u00a0plan\n.\n\n\nWe'd like to say thanks in particular our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, and \nRollbar\n.\n\n\n\n\nBreaking Changes\n\n\ndefault\n on Field.\nAltered the behaviour of \nread_only\n plus \n\n\n#5886\n \nread_only\n fields will now \nalways\n be excluded from writable fields.\n\n\nPreviously \nread_only\n fields when combined with a \ndefault\n value would use the \ndefault\n for create and update\noperations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted \nsource\n\nattributes on nullable relations.\n\n\nIn order to maintain the old behaviour you may need to pass the value of \nread_only\n fields when calling \nsave()\n in\nthe view:\n\n\ndef perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n\n\n\nAlternatively you may override \nsave()\n or \ncreate()\n or \nupdate()\n on the serializer as appropriate.\n\n\n\n\nDeprecations\n\n\nlist_route\n and \naction\n decorator replaces \ndetail_route\n\n\n#5705\n \nlist_route\n and \ndetail_route\n have been merge into a single \naction\n decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.\n\n\nBoth \nlist_route\n and \ndetail_route\n are now pending deprecation. They will be deprecated in 3.9 and removed entirely\nin 3.10.\n\n\nThe new \naction\n decorator takes a boolean \ndetail\n argument.\n\n\n\n\nReplace \ndetail_route\n uses with \n@action(detail=True)\n.\n\n\nReplace \nlist_route\n uses with \n@action(detail=False)\n.\n\n\n\n\nexclude_from_schema\n\n\nBoth \nAPIView.exclude_from_schema\n and the \nexclude_from_schema\n argument to the \n@api_view\n decorator are now deprecated. They will be removed entirely in 3.9.\n\n\nFor \nAPIView\n you should instead set a \nschema = None\n attribute on the view class.\n\n\nFor function based views the \n@schema\n decorator can be used to exclude the view from the schema, by using \n@schema(None)\n.\n\n\n\n\nMinor fixes and improvements\n\n\nThere are a large number of minor fixes and improvements in this release. See the \nrelease notes\n page\nfor a complete listing.\n\n\nWhat's next\n\n\nWe're currently working towards moving to using \nOpenAPI\n as our default schema output. We'll also be revisiting our API documentation generation and client libraries.\n\n\nWe're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the \ncoreapi\n and \ncoreschema\n libraries, and instead use \napistar\n for the API documentation generation, schema generation, and API client libraries.", + "title": "3.8 Announcement" + }, + { + "location": "/topics/3.8-announcement/#django-rest-framework-38", + "text": "The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying\nthe foundations for future changes.", + "title": "Django REST framework 3.8" + }, + { + "location": "/topics/3.8-announcement/#funding", + "text": "If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan . We'd like to say thanks in particular our premium backers, Rover , Sentry , Stream , Machinalis , and Rollbar .", + "title": "Funding" + }, + { + "location": "/topics/3.8-announcement/#breaking-changes", + "text": "", + "title": "Breaking Changes" + }, + { + "location": "/topics/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field", + "text": "#5886 read_only fields will now always be excluded from writable fields. Previously read_only fields when combined with a default value would use the default for create and update\noperations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted source \nattributes on nullable relations. In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in\nthe view: def perform_create(self, serializer):\n serializer.save(owner=self.request.user) Alternatively you may override save() or create() or update() on the serializer as appropriate.", + "title": "Altered the behaviour of read_only plus default on Field." + }, + { + "location": "/topics/3.8-announcement/#deprecations", + "text": "", + "title": "Deprecations" + }, + { + "location": "/topics/3.8-announcement/#action-decorator-replaces-list_route-and-detail_route", + "text": "#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions. Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely\nin 3.10. The new action decorator takes a boolean detail argument. Replace detail_route uses with @action(detail=True) . Replace list_route uses with @action(detail=False) .", + "title": "action decorator replaces list_route and detail_route" + }, + { + "location": "/topics/3.8-announcement/#exclude_from_schema", + "text": "Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator are now deprecated. They will be removed entirely in 3.9. For APIView you should instead set a schema = None attribute on the view class. For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None) .", + "title": "exclude_from_schema" + }, + { + "location": "/topics/3.8-announcement/#minor-fixes-and-improvements", + "text": "There are a large number of minor fixes and improvements in this release. See the release notes page\nfor a complete listing.", + "title": "Minor fixes and improvements" + }, + { + "location": "/topics/3.8-announcement/#whats-next", + "text": "We're currently working towards moving to using OpenAPI as our default schema output. We'll also be revisiting our API documentation generation and client libraries. We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the coreapi and coreschema libraries, and instead use apistar for the API documentation generation, schema generation, and API client libraries.", + "title": "What's next" + }, + { + "location": "/topics/kickstarter-announcement/", + "text": "Kickstarting Django REST framework 3\n\n\n\n\n \n\n\n\n\n\nIn order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.\n\n\nProject details\n\n\nThis new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:\n\n\n\n\nFaster, simpler and easier-to-use serializers.\n\n\nAn alternative admin-style interface for the browsable API.\n\n\nSearch and filtering controls made accessible in the browsable API.\n\n\nAlternative API pagination styles.\n\n\nDocumentation around API versioning.\n\n\nTriage of outstanding tickets.\n\n\nImproving the ongoing quality and maintainability of the project.\n\n\n\n\nFull details are available now on the \nproject page\n.\n\n\nIf you're interested in helping make sustainable open source development a reality please \nvisit the Kickstarter page\n and consider funding the project.\n\n\nI can't wait to see where this takes us!\n\n\nMany thanks to everyone for your support so far,\n\n\nTom Christie :)\n\n\n\n\nSponsors\n\n\nWe've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.\n\n\n\n\nPlatinum sponsors\n\n\nOur platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.\n\n\n\n\nEventbrite\n\n\n\n\n\n\n\nDivio\n\n\nLulu\n\n\nPotato\n\n\nWiredrive\n\n\nCyan\n\n\nRunscope\n\n\nSimple Energy\n\n\nVOKAL Interactive\n\n\nPurple Bit\n\n\nKuwaitNET\n\n\n\n\n\n\n\n\n\n\nGold sponsors\n\n\nOur gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.\n\n\n\n\nLaterPay\n\n\nSchuberg Philis\n\n\nProReNata AB\n\n\nSGA Websites\n\n\nSirono\n\n\nVinta Software Studio\n\n\nRapasso\n\n\nMirus Research\n\n\nHipo\n\n\nByte\n\n\nLightning Kite\n\n\nOpbeat\n\n\nKoordinates\n\n\nPulsecode Inc.\n\n\nSinging Horse Studio Ltd.\n\n\nHeroku\n\n\nRheinwerk Verlag\n\n\nSecurity Compass\n\n\nDjango Software Foundation\n\n\nHipflask\n\n\nCrate\n\n\nCryptico Corp\n\n\nNextHub\n\n\nCompile\n\n\nWusaWork\n\n\nEnvision Linux\n\n\n\n\n\n\n\n\n\n\nSilver sponsors\n\n\nThe serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level.\n\n\n\n\nIMT Computer Services\n\n\nWildfish\n\n\nThermondo GmbH\n\n\nProvidenz\n\n\nalwaysdata.com\n\n\nTriggered Messaging\n\n\nPushPull Technology Ltd\n\n\nTranscode\n\n\nGarfo\n\n\nShippo\n\n\nGizmag\n\n\nTivix\n\n\nSafari\n\n\nBright Loop\n\n\nABA Systems\n\n\nbeefarm.ru\n\n\nVzzual.com\n\n\nInfinite Code\n\n\nCrossword Tracker\n\n\nPkgFarm\n\n\nLife. The Game.\n\n\nBlimp\n\n\nPathwright\n\n\nFluxility\n\n\nTeonite\n\n\nTrackMaven\n\n\nPhurba\n\n\nNephila\n\n\nAditium\n\n\nOpenEye Scientific Software\n\n\nHolvi\n\n\nCantemo\n\n\nMakeSpace\n\n\nAX Semantics\n\n\nISL\n\n\n\n\n\n\n\n\nIndividual backers\n: Paul Hallett, \nPaul Whipp\n, Dylan Roy, Jannis Leidel, \nXavier Ordoquy\n, \nJohannes Spielmann\n, \nRob Spectre\n, \nChris Heisel\n, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.\n\n\n\n\nAdvocates\n\n\nThe following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!\n\n\nIndividual backers\n: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.\n\n\nCorporate backers\n: Savannah Informatics, Prism Skylabs, Musical Operating Devices.\n\n\n\n\nSupporters\n\n\nThere were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!", + "title": "Kickstarter Announcement" + }, + { + "location": "/topics/kickstarter-announcement/#kickstarting-django-rest-framework-3", + "text": "In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.", + "title": "Kickstarting Django REST framework 3" + }, + { + "location": "/topics/kickstarter-announcement/#project-details", + "text": "This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following: Faster, simpler and easier-to-use serializers. An alternative admin-style interface for the browsable API. Search and filtering controls made accessible in the browsable API. Alternative API pagination styles. Documentation around API versioning. Triage of outstanding tickets. Improving the ongoing quality and maintainability of the project. Full details are available now on the project page . If you're interested in helping make sustainable open source development a reality please visit the Kickstarter page and consider funding the project. I can't wait to see where this takes us! Many thanks to everyone for your support so far, Tom Christie :)", + "title": "Project details" + }, + { + "location": "/topics/kickstarter-announcement/#sponsors", + "text": "We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.", + "title": "Sponsors" + }, + { + "location": "/topics/kickstarter-announcement/#platinum-sponsors", + "text": "Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough. Eventbrite Divio Lulu Potato Wiredrive Cyan Runscope Simple Energy VOKAL Interactive Purple Bit KuwaitNET", + "title": "Platinum sponsors" + }, + { + "location": "/topics/kickstarter-announcement/#gold-sponsors", + "text": "Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development. LaterPay Schuberg Philis ProReNata AB SGA Websites Sirono Vinta Software Studio Rapasso Mirus Research Hipo Byte Lightning Kite Opbeat Koordinates Pulsecode Inc. Singing Horse Studio Ltd. Heroku Rheinwerk Verlag Security Compass Django Software Foundation Hipflask Crate Cryptico Corp NextHub Compile WusaWork Envision Linux", + "title": "Gold sponsors" + }, + { + "location": "/topics/kickstarter-announcement/#silver-sponsors", + "text": "The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level. IMT Computer Services Wildfish Thermondo GmbH Providenz alwaysdata.com Triggered Messaging PushPull Technology Ltd Transcode Garfo Shippo Gizmag Tivix Safari Bright Loop ABA Systems beefarm.ru Vzzual.com Infinite Code Crossword Tracker PkgFarm Life. The Game. Blimp Pathwright Fluxility Teonite TrackMaven Phurba Nephila Aditium OpenEye Scientific Software Holvi Cantemo MakeSpace AX Semantics ISL Individual backers : Paul Hallett, Paul Whipp , Dylan Roy, Jannis Leidel, Xavier Ordoquy , Johannes Spielmann , Rob Spectre , Chris Heisel , Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.", + "title": "Silver sponsors" + }, + { + "location": "/topics/kickstarter-announcement/#advocates", + "text": "The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you! Individual backers : Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel. Corporate backers : Savannah Informatics, Prism Skylabs, Musical Operating Devices.", + "title": "Advocates" + }, + { + "location": "/topics/kickstarter-announcement/#supporters", + "text": "There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!", + "title": "Supporters" + }, + { + "location": "/topics/mozilla-grant/", + "text": "Mozilla Grant\n\n\nWe have recently been \nawarded a Mozilla grant\n, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.\n\n\nAdditionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.\n\n\nThe \nCore API\n project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with \nany\n API that exposes a supported schema or hypermedia format.\n\n\nSpecifically, the work includes:\n\n\nClient libraries\n\n\nThis work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.\n\n\n\n\nClient library support in REST framework.\n\n\nSchema & hypermedia support for REST framework APIs.\n\n\nA test client, allowing you to write tests that emulate a client library interacting with your API.\n\n\nNew tutorial sections on using client libraries to interact with REST framework APIs.\n\n\nPython client library.\n\n\nJavaScript client library.\n\n\nCommand line client.\n\n\n\n\nRealtime APIs\n\n\nThe next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.\n\n\n\n\nSupport for API subscription endpoints, using REST framework and Django Channels.\n\n\nNew tutorial section on building realtime API endpoints with REST framework.\n\n\nRealtime support in the Python & Javascript client libraries.\n\n\n\n\nAccountability\n\n\nIn order to ensure that I can be fully focused on trying to secure a sustainable\n& well-funded open source business I will be leaving my current role at \nDabApps\n\nat the end of May 2016.\n\n\nI have formed a UK limited company, \nEncode\n, which will\nact as the business entity behind REST framework. I will be issuing monthly reports\nfrom Encode on progress both towards the Mozilla grant, and for development time\nfunded via the \nREST framework paid plans\n.\n\n\n\n\n\n\n\n\n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /\n\n\n\n\n\n\n \n\n \nStay up to date, with our monthly progress reports...\n\n\n\n \nEmail Address \n\n \n\n\n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n\n\n\n\n\n\n(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);", + "title": "Mozilla Grant" + }, + { + "location": "/topics/mozilla-grant/#mozilla-grant", + "text": "We have recently been awarded a Mozilla grant , in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with. Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications. The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format. Specifically, the work includes:", + "title": "Mozilla Grant" + }, + { + "location": "/topics/mozilla-grant/#client-libraries", + "text": "This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation. Client library support in REST framework. Schema & hypermedia support for REST framework APIs. A test client, allowing you to write tests that emulate a client library interacting with your API. New tutorial sections on using client libraries to interact with REST framework APIs. Python client library. JavaScript client library. Command line client.", + "title": "Client libraries" + }, + { + "location": "/topics/mozilla-grant/#realtime-apis", + "text": "The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints. Support for API subscription endpoints, using REST framework and Django Channels. New tutorial section on building realtime API endpoints with REST framework. Realtime support in the Python & Javascript client libraries.", + "title": "Realtime APIs" + }, + { + "location": "/topics/mozilla-grant/#accountability", + "text": "In order to ensure that I can be fully focused on trying to secure a sustainable\n& well-funded open source business I will be leaving my current role at DabApps \nat the end of May 2016. I have formed a UK limited company, Encode , which will\nact as the business entity behind REST framework. I will be issuing monthly reports\nfrom Encode on progress both towards the Mozilla grant, and for development time\nfunded via the REST framework paid plans . \n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /", + "title": "Accountability" + }, + { + "location": "/topics/funding/", + "text": "// Imperfect, but easier to fit in with the existing docs build.\n// Hyperlinks should point directly to the \"fund.\" subdomain, but this'll\n// handle the nav bar links without requiring any docs build changes for the moment.\nif (window.location.hostname == \"www.django-rest-framework.org\") {\n window.location.replace(\"https://fund.django-rest-framework.org/topics/funding/\");\n}\n\n\n\n\n\n.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.chart {\n background-color: #e3e3e3;\n background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);\n border: 1px solid #E6E6E6;\n border-radius: 5px;\n box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);\n padding: 40px 0px 5px;\n position: relative;\n text-align: center;\n width: 97%;\n min-height: 255px;\n position: relative;\n top: 37px;\n margin-bottom: 20px\n}\n.quantity {\n text-align: center\n}\n.dollar {\n font-size: 19px;\n position: relative;\n top: -18px;\n}\n.price {\n font-size: 49px;\n}\n.period {\n font-size: 17px;\n position: relative;\n top: -8px;\n margin-left: 4px;\n}\n.plan-name {\n text-align: center;\n font-size: 20px;\n font-weight: 400;\n color: #777;\n border-bottom: 1px solid #d5d5d5;\n padding-bottom: 15px;\n width: 90%;\n margin: 0 auto;\n margin-top: 8px;\n}\n.specs {\n margin-top: 20px;\n min-height: 130px;\n}\n.specs.freelancer {\n min-height: 0px;\n}\n.spec {\n font-size: 15px;\n color: #474747;\n text-align: center;\n font-weight: 300;\n margin-bottom: 13px;\n}\n.variable {\n color: #1FBEE7;\n font-weight: 400;\n}\nform.signup {\n margin-top: 35px\n}\n.clear-promo {\n padding-top: 30px\n}\n#main-content h1:first-of-type {\n margin: 0 0 50px;\n font-size: 60px;\n font-weight: 200;\n text-align: center\n}\n#main-content {\n padding-top: 10px; line-height: 23px\n}\n#main-content li {\n line-height: 23px\n}\n\n\n\n\nFunding\n\n\nIf you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.\n\n\nWe believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.\n\n\nSigning up for a paid plan will:\n\n\n\n\nDirectly contribute to faster releases, more features, and higher quality software.\n\n\nAllow more time to be invested in documentation, issue triage, and community support.\n\n\nSafeguard the future development of REST framework.\n\n\n\n\nREST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.\n\n\n\n\nWhat funding has enabled so far\n\n\n\n\nThe \n3.4\n and \n3.5\n releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.\n\n\nThe \n3.6\n release, including JavaScript client library, and API documentation, complete with auto-generated code samples.\n\n\nThe \n3.7 release\n, made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.\n\n\nThe recent \n3.8 release\n.\n\n\nTom Christie, the creator of Django REST framework, working on the project full-time.\n\n\nAround 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.\n\n\nA community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.\n\n\nContracting development time for the work on the JavaScript client library and API documentation tooling.\n\n\n\n\n\n\nWhat future funding will enable\n\n\n\n\nRealtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.\n\n\nBetter authentication defaults, possibly bringing JWT & CORs support into the core package.\n\n\nSecuring the community & operations manager position long-term.\n\n\nOpening up and securing a part-time position to focus on ticket triage and resolution.\n\n\nPaying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.\n\n\n\n\nSign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.\n\n\n\n\nWhat our sponsors and users say\n\n\n\n\nAs a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.\n\n\n\u2014 Jos\u00e9 Padilla, Django REST framework contributor\n\n\n\n\n\u00a0\n\n\n\n\nThe number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.\n\n\n\u2014 Filipe Ximenes, Vinta Software\n\n\n\n\n\u00a0\n\n\n\n\nIt's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.\nDRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.\n\n\n\u2014 Andrew Conti, Django REST framework user\n\n\n\n\n\n\nIndividual plan\n\n\nThis subscription is recommended for individuals with an interest in seeing REST framework continue to\u00a0improve.\n\n\nIf you are using REST framework as a full-time employee, consider recommending that your company takes out a \ncorporate\u00a0plan\n.\n\n\n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.personal1 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nIndividual\n\n \n\n \n\n Support ongoing development\n \n\n \n\n Credited on the site\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n\n\n\n\n\nBilling is monthly and you can cancel at any time.\n\n\n\n\nCorporate plans\n\n\nThese subscriptions are recommended for companies and organizations using REST framework either publicly or privately.\n\n\nIn exchange for funding you'll also receive advertising space on our site, allowing you to \npromote your company or product to many tens of thousands of developers worldwide\n.\n\n\nOur professional and premium plans also include \npriority support\n. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.\n\n\n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate1 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nBasic\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nFunding page\n ad placement\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate2 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nProfessional\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nSidebar\n ad placement\n \n\n \n\n \nPriority support\n for your engineers\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n \n\n \n\n \n{{ symbol }}\n\n \n{{ rates.corporate3 }}\n\n \n/month{% if vat %} +VAT{% endif %}\n\n \n\n \nPremium\n\n \n\n \n\n Support ongoing development\n \n\n \n\n \nHomepage\n ad placement\n \n\n \n\n \nSidebar\n ad placement\n \n\n \n\n \nPriority support\n for your engineers\n \n\n \n\n \n\n \n\n \n\n\n\n \n\n \n\n \n\n\n\n\n\n\nBilling is monthly and you can cancel at any time.\n\n\nOnce you've signed up, we will contact you via email and arrange your ad placements on the site.\n\n\nFor further enquires please contact \nfunding@django-rest-framework.org\n.\n\n\n\n\nAccountability\n\n\nIn an effort to keep the project as transparent as possible, we are releasing \nmonthly progress reports\n and regularly include financial reports and cost breakdowns.\n\n\n\n\n\n\n\n\n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /\n\n\n\n\n\n\n \n\n \nStay up to date, with our monthly progress reports...\n\n\n\n \nEmail Address \n\n \n\n\n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n\n\n\n\n\n\n(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);\n\n\n\n\n\n\nFrequently asked questions\n\n\nQ: Can you issue monthly invoices?\n\nA: Yes, we are happy to issue monthly invoices. Please just \nemail us\n and let us know who to issue the invoice to (name and address) and which email address to send it to each month.\n\n\nQ: Does sponsorship include VAT?\n\nA: Sponsorship is VAT exempt.\n\n\nQ: Do I have to sign up for a certain time period?\n\nA: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.\n\n\nQ: Can I pay yearly? Can I pay upfront fox X amount of months at a time?\n\nA: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.\n\n\nQ: Are you only looking for corporate sponsors?\n\nA: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.\n\n\n\n\nOur sponsors", + "title": "Funding" + }, + { + "location": "/topics/funding/#funding", + "text": "If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan. We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development. Signing up for a paid plan will: Directly contribute to faster releases, more features, and higher quality software. Allow more time to be invested in documentation, issue triage, and community support. Safeguard the future development of REST framework. REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.", + "title": "Funding" + }, + { + "location": "/topics/funding/#what-funding-has-enabled-so-far", + "text": "The 3.4 and 3.5 releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. The 3.6 release, including JavaScript client library, and API documentation, complete with auto-generated code samples. The 3.7 release , made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. The recent 3.8 release . Tom Christie, the creator of Django REST framework, working on the project full-time. Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time. A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship. Contracting development time for the work on the JavaScript client library and API documentation tooling.", + "title": "What funding has enabled so far" + }, + { + "location": "/topics/funding/#what-future-funding-will-enable", + "text": "Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries. Better authentication defaults, possibly bringing JWT & CORs support into the core package. Securing the community & operations manager position long-term. Opening up and securing a part-time position to focus on ticket triage and resolution. Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation. Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.", + "title": "What future funding will enable" + }, + { + "location": "/topics/funding/#what-our-sponsors-and-users-say", + "text": "As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem. \u2014 Jos\u00e9 Padilla, Django REST framework contributor \u00a0 The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it. \u2014 Filipe Ximenes, Vinta Software \u00a0 It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.\nDRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large. \u2014 Andrew Conti, Django REST framework user", + "title": "What our sponsors and users say" + }, + { + "location": "/topics/funding/#individual-plan", + "text": "This subscription is recommended for individuals with an interest in seeing REST framework continue to\u00a0improve. If you are using REST framework as a full-time employee, consider recommending that your company takes out a corporate\u00a0plan . \n \n \n \n {{ symbol }} \n {{ rates.personal1 }} \n /month{% if vat %} +VAT{% endif %} \n \n Individual \n \n \n Support ongoing development\n \n \n Credited on the site\n \n \n \n \n \n \n \n Billing is monthly and you can cancel at any time.", + "title": "Individual plan" + }, + { + "location": "/topics/funding/#corporate-plans", + "text": "These subscriptions are recommended for companies and organizations using REST framework either publicly or privately. In exchange for funding you'll also receive advertising space on our site, allowing you to promote your company or product to many tens of thousands of developers worldwide . Our professional and premium plans also include priority support . At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day. \n \n \n \n {{ symbol }} \n {{ rates.corporate1 }} \n /month{% if vat %} +VAT{% endif %} \n \n Basic \n \n \n Support ongoing development\n \n \n Funding page ad placement\n \n \n \n \n \n \n \n \n \n \n {{ symbol }} \n {{ rates.corporate2 }} \n /month{% if vat %} +VAT{% endif %} \n \n Professional \n \n \n Support ongoing development\n \n \n Sidebar ad placement\n \n \n Priority support for your engineers\n \n \n \n \n \n \n \n \n \n \n {{ symbol }} \n {{ rates.corporate3 }} \n /month{% if vat %} +VAT{% endif %} \n \n Premium \n \n \n Support ongoing development\n \n \n Homepage ad placement\n \n \n Sidebar ad placement\n \n \n Priority support for your engineers\n \n \n \n \n \n \n \n Billing is monthly and you can cancel at any time. Once you've signed up, we will contact you via email and arrange your ad placements on the site. For further enquires please contact funding@django-rest-framework.org .", + "title": "Corporate plans" + }, + { + "location": "/topics/funding/#accountability", + "text": "In an effort to keep the project as transparent as possible, we are releasing monthly progress reports and regularly include financial reports and cost breakdowns. \n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /", + "title": "Accountability" + }, + { + "location": "/topics/funding/#frequently-asked-questions", + "text": "Q: Can you issue monthly invoices? \nA: Yes, we are happy to issue monthly invoices. Please just email us and let us know who to issue the invoice to (name and address) and which email address to send it to each month. Q: Does sponsorship include VAT? \nA: Sponsorship is VAT exempt. Q: Do I have to sign up for a certain time period? \nA: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime. Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time? \nA: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution. Q: Are you only looking for corporate sponsors? \nA: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.", + "title": "Frequently asked questions" + }, + { + "location": "/topics/funding/#our-sponsors", + "text": "", + "title": "Our sponsors" + }, + { + "location": "/topics/release-notes/", + "text": "Release Notes\n\n\n\n\nRelease Early, Release Often\n\n\n\u2014 Eric S. Raymond, \nThe Cathedral and the Bazaar\n.\n\n\n\n\nVersioning\n\n\nMinor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.\n\n\nMedium version numbers (0.x.0) may include API changes, in line with the \ndeprecation policy\n. You should read the release notes carefully before upgrading between medium point releases.\n\n\nMajor version numbers (x.0.0) are reserved for substantial project milestones.\n\n\nDeprecation policy\n\n\nREST framework releases follow a formal deprecation policy, which is in line with \nDjango's deprecation policy\n.\n\n\nThe timeline for deprecation of a feature present in version 1.0 would work as follows:\n\n\n\n\n\n\nVersion 1.1 would remain \nfully backwards compatible\n with 1.0, but would raise \nPendingDeprecationWarning\n warnings if you use the feature that are due to be deprecated. These warnings are \nsilent by default\n, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using \npython -Wd manage.py test\n, you'll be warned of any API changes you need to make.\n\n\n\n\n\n\nVersion 1.2 would escalate these warnings to \nDeprecationWarning\n, which is loud by default.\n\n\n\n\n\n\nVersion 1.3 would remove the deprecated bits of API entirely.\n\n\n\n\n\n\nNote that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.\n\n\nUpgrading\n\n\nTo upgrade Django REST framework to the latest version, use pip:\n\n\npip install -U djangorestframework\n\n\n\nYou can determine your currently installed version using \npip show\n:\n\n\npip show djangorestframework\n\n\n\n\n\n3.8.x series\n\n\n3.8.2\n\n\nDate\n: \n6th April 2018\n\n\n\n\nFix \nread_only\n + \ndefault\n \nunique_together\n validation. \n#5922\n\n\nauthtoken.views import coreapi from rest_framework.compat, not directly. \n#5921\n\n\nDocs: Add missing argument 'detail' to Route \n#5920\n\n\n\n\n3.8.1\n\n\nDate\n: \n4th April 2018\n\n\n\n\n\n\nUse old \nurl_name\n behavior in route decorators \n#5915\n\n\nFor \nlist_route\n and \ndetail_route\n maintain the old behavior of \nurl_name\n,\nbasing it on the \nurl_path\n instead of the function name.\n\n\n\n\n\n\n3.8.0\n\n\nDate\n: \n3rd April 2018\n\n\n\n\n\n\nBreaking Change\n: Alter \nread_only\n plus \ndefault\n behaviour. \n#5886\n\n\nread_only\n fields will now \nalways\n be excluded from writable fields.\n\n\nPreviously \nread_only\n fields with a \ndefault\n value would use the \ndefault\n for create and update operations.\n\n\nIn order to maintain the old behaviour you may need to pass the value of \nread_only\n fields when calling \nsave()\n in\nthe view:\n\n\ndef perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n\n\n\nAlternatively you may override \nsave()\n or \ncreate()\n or \nupdate()\n on the serialiser as appropriate.\n\n\n\n\n\n\nCorrect allow_null behaviour when required=False \n#5888\n\n\nWithout an explicit \ndefault\n, \nallow_null\n implies a default of \nnull\n for outgoing serialisation. Previously such\nfields were being skipped when read-only or otherwise not required.\n\n\nPossible backwards compatibility break\n if you were relying on such fields being excluded from the outgoing\nrepresentation. In order to restore the old behaviour you can override \ndata\n to exclude the field when \nNone\n.\n\n\nFor example:\n\n\n@property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data\n\n\n\n\n\n\n\nRefactor dynamic route generation and improve viewset action introspectibility. \n#5705\n\n\nViewSet\ns have been provided with new attributes and methods that allow\nit to introspect its set of actions and the details of the current action.\n\n\n\n\nMerged \nlist_route\n and \ndetail_route\n into a single \naction\n decorator.\n\n\nGet all extra actions on a \nViewSet\n with \n.get_extra_actions()\n.\n\n\nExtra actions now set the \nurl_name\n and \nurl_path\n on the decorated method.\n\n\nurl_name\n is now based on the function name, instead of the \nurl_path\n,\n as the path is not always suitable (e.g., capturing arguments in the path).\n\n\nEnable action url reversing through \n.reverse_action()\n method (added in 3.7.4)\n\n\nExample reverse call: \nself.reverse_action(self.custom_action.url_name)\n\n\nAdd \ndetail\n initkwarg to indicate if the current action is operating on a\n collection or a single instance.\n\n\n\n\nAdditional changes:\n\n\n\n\nDeprecated \nlist_route\n & \ndetail_route\n in favor of \naction\n decorator with \ndetail\n boolean.\n\n\nDeprecated dynamic list/detail route variants in favor of \nDynamicRoute\n with \ndetail\n boolean.\n\n\nRefactored the router's dynamic route generation.\n\n\nlist_route\n and \ndetail_route\n maintain the old behavior of \nurl_name\n,\n basing it on the \nurl_path\n instead of the function name.\n\n\n\n\n\n\n\n\nFix formatting of the 3.7.4 release note \n#5704\n\n\n\n\nDocs: Update DRF Writable Nested Serializers references \n#5711\n\n\nDocs: Fixed typo in auth URLs example. \n#5713\n\n\nImprove composite field child errors \n#5655\n\n\nDisable HTML inputs for dict/list fields \n#5702\n\n\nFix typo in HostNameVersioning doc \n#5709\n\n\nUse rsplit to get module and classname for imports \n#5712\n\n\nFormalize URLPatternsTestCase \n#5703\n\n\nAdd exception translation test \n#5700\n\n\nTest staticfiles \n#5701\n\n\nAdd drf-yasg to documentation and schema 3rd party packages \n#5720\n\n\nRemove unused \ncompat._resolve_model()\n \n#5733\n\n\nDrop compat workaround for unsupported Python 3.2 \n#5734\n\n\nPrefer \niter(dict)\n over \niter(dict.keys())\n \n#5736\n\n\nPass \npython_requires\n argument to setuptools \n#5739\n\n\nRemove unused links from docs \n#5735\n\n\nPrefer https protocol for links in docs when available \n#5729\n\n\nAdd HStoreField, postgres fields tests \n#5654\n\n\nAlways fully qualify ValidationError in docs \n#5751\n\n\nRemove unreachable code from ManualSchema \n#5766\n\n\nAllowed customising API documentation code samples \n#5752\n\n\nUpdated docs to use \npip show\n \n#5757\n\n\nLoad 'static' instead of 'staticfiles' in templates \n#5773\n\n\nFixed a typo in \nfields\n docs \n#5783\n\n\nRefer to \"NamespaceVersioning\" instead of \"NamespacedVersioning\" in the documentation \n#5754\n\n\nErrorDetail: add \n__eq__\n/\n__ne__\n and \n__repr__\n \n#5787\n\n\nReplace \nbackground-attachment: fixed\n in docs \n#5777\n\n\nMake 404 & 403 responses consistent with \nexceptions.APIException\n output \n#5763\n\n\nSmall fix to API documentation: schemas \n#5796\n\n\nFix schema generation for PrimaryKeyRelatedField \n#5764\n\n\nRepresent serializer DictField as an Object in schema \n#5765\n\n\nAdded docs example reimplementing ObtainAuthToken \n#5802\n\n\nAdd schema to the ObtainAuthToken view \n#5676\n\n\nFix request formdata handling \n#5800\n\n\nFix authtoken views imports \n#5818\n\n\nUpdate pytest, isort \n#5815\n \n#5817\n \n#5894\n\n\nFixed active timezone handling for non ISO8601 datetimes. \n#5833\n\n\nMade TemplateHTMLRenderer render IntegerField inputs when value is \n0\n. \n#5834\n\n\nCorrected endpoint in tutorial instructions \n#5835\n\n\nAdd Django Rest Framework Role Filters to Third party packages \n#5809\n\n\nUse single copy of static assets. Update jQuery \n#5823\n\n\nChanges ternary conditionals to be PEP308 compliant \n#5827\n\n\nAdded links to 'A Todo List API with React' and 'Blog API' tutorials \n#5837\n\n\nFix comment typo in ModelSerializer \n#5844\n\n\nAdd admin to installed apps to avoid test failures. \n#5870\n\n\nFixed schema for UUIDField in SimpleMetadata. \n#5872\n\n\nCorrected docs on router include with namespaces. \n#5843\n\n\nTest using model objects for dotted source default \n#5880\n\n\nAllow traversing nullable related fields \n#5849\n\n\nAdded: Tutorial: Django REST with React (Django 2.0) \n#5891\n\n\nAdd \nLimitOffsetPagination.get_count\n to allow method override \n#5846\n\n\nDon't show hidden fields in metadata \n#5854\n\n\nEnable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. \n#5899\n\n\nAdded generic 500 and 400 JSON error handlers. \n#5904\n\n\n\n\n3.7.x series\n\n\n3.7.7\n\n\nDate\n: \n21st December 2017\n\n\n\n\nFix typo to include *.mo locale files to packaging. \n#5697\n, \n#5695\n\n\n\n\n3.7.6\n\n\nDate\n: \n21st December 2017\n\n\n\n\nAdd missing *.ico icon files to packaging.\n\n\n\n\n3.7.5\n\n\nDate\n: \n21st December 2017\n\n\n\n\nAdd missing *.woff2 font files to packaging. \n#5692\n\n\nAdd missing *.mo locale files to packaging. \n#5695\n, \n#5696\n\n\n\n\n3.7.4\n\n\nDate\n: \n20th December 2017\n\n\n\n\n\n\nSchema: Extract method for \nmanual_fields\n processing \n#5633\n\n\nAllows for easier customisation of \nmanual_fields\n processing, for example\nto provide per-method manual fields. \nAutoSchema\n adds \nget_manual_fields\n,\nas the intended override point, and a utility method \nupdate_fields\n, to\nhandle by-name field replacement from a list, which, in general, you are not\nexpected to override.\n\n\nNote: \nAutoSchema.__init__\n now ensures \nmanual_fields\n is a list.\nPreviously may have been stored internally as \nNone\n.\n\n\n\n\n\n\nRemove ulrparse compatability shim; use six instead \n#5579\n\n\n\n\nDrop compat wrapper for \nTimeDelta.total_seconds()\n \n#5577\n\n\nClean up all whitespace throughout project \n#5578\n\n\nCompat cleanup \n#5581\n\n\nAdd pygments CSS block in browsable API views \n#5584\n \n#5587\n\n\nRemove \nset_rollback()\n from compat \n#5591\n\n\nFix request body/POST access \n#5590\n\n\nRename test to reference correct issue \n#5610\n\n\nDocumentation Fixes \n#5611\n \n#5612\n\n\nRemove references to unsupported Django versions in docs and code \n#5602\n\n\nTest Serializer exclude for declared fields \n#5599\n\n\nFixed schema generation for filter backends \n#5613\n\n\nMinor cleanup for ModelSerializer tests \n#5598\n\n\nReimplement request attribute access w/ \n__getattr__\n \n#5617\n\n\nFixed SchemaJSRenderer renders invalid Javascript \n#5607\n\n\nMake Django 2.0 support official/explicit \n#5619\n\n\nPerform type check on passed request argument \n#5618\n\n\nFix AttributeError hiding on request authenticators \n#5600\n\n\nUpdate test requirements \n#5626\n\n\nDocs: \nSerializer._declared_fields\n enable modifying fields on a serializer \n#5629\n\n\nFix packaging \n#5624\n\n\nFix readme rendering for PyPI, add readme build to CI \n#5625\n\n\nUpdate tutorial \n#5622\n\n\nNon-required fields with \nallow_null=True\n should not imply a default value \n#5639\n\n\nDocs: Add \nallow_null\n serialization output note \n#5641\n\n\nUpdate to use the Django 2.0 release in tox.ini \n#5645\n\n\nFix \nSerializer.data\n for Browsable API rendering when provided invalid \ndata\n \n#5646\n\n\nDocs: Note AutoSchema limitations on bare APIView \n#5649\n\n\nAdd \n.basename\n and \n.reverse_action()\n to ViewSet \n#5648\n\n\nDocs: Fix typos in serializers documentation \n#5652\n\n\nFix \noverride_settings\n compat \n#5668\n\n\nAdd DEFAULT_SCHEMA_CLASS setting \n#5658\n\n\nAdd docs note re generated BooleanField being \nrequired=False\n \n#5665\n\n\nAdd 'dist' build \n#5656\n\n\nFix typo in docstring \n#5678\n\n\nDocs: Add \nUNAUTHENTICATED_USER = None\n note \n#5679\n\n\nUpdate OPTIONS example from \u201cDocumenting Your API\u201d \n#5680\n\n\nDocs: Add note on object permissions for FBVs \n#5681\n\n\nDocs: Add example to \nto_representation\n docs \n#5682\n\n\nAdd link to Classy DRF in docs \n#5683\n\n\nDocument ViewSet.action \n#5685\n\n\nFix schema docs typo \n#5687\n\n\nFix URL pattern parsing in schema generation \n#5689\n\n\nAdd example using \nsource=\u2018*\u2019\n to custom field docs. \n#5688\n\n\nFix format_suffix_patterns behavior with Django 2 path() routes \n#5691\n\n\n\n\n3.7.3\n\n\nDate\n: \n6th November 2017\n\n\n\n\nFix \nAppRegistryNotReady\n error from contrib.auth view imports \n#5567\n\n\n\n\n3.7.2\n\n\nDate\n: \n6th November 2017\n\n\n\n\nFixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. \n#5510\n\n\nAdd missing import for TextLexer. \n#5512\n\n\nAdding examples and documentation for caching \n#5514\n\n\nInclude date and date-time format for schema generation \n#5511\n\n\nUse triple backticks for markdown code blocks \n#5513\n\n\nInteractive docs - make bottom sidebar items sticky \n#5516\n\n\nClarify pagination system check \n#5524\n\n\nStop JSONBoundField mangling invalid JSON \n#5527\n\n\nHave JSONField render as textarea in Browsable API \n#5530\n\n\nSchema: Exclude OPTIONS/HEAD for ViewSet actions \n#5532\n\n\nFix ordering for dotted sources \n#5533\n\n\nFix: Fields with \nallow_null=True\n should imply a default serialization value \n#5518\n\n\nEnsure Location header is strictly a 'str', not subclass. \n#5544\n\n\nAdd import to example in api-guide/parsers \n#5547\n\n\nCatch OverflowError for \"out of range\" datetimes \n#5546\n\n\nAdd djangorestframework-rapidjson to third party packages \n#5549\n\n\nIncrease test coverage for \ndrf_create_token\n command \n#5550\n\n\nAdd trove classifier for Python 3.6 support. \n#5555\n\n\nAdd pip cache support to the Travis CI configuration \n#5556\n\n\nRename [\nwheel\n] section to [\nbdist_wheel\n] as the former is legacy \n#5557\n\n\nFix invalid escape sequence deprecation warnings \n#5560\n\n\nAdd interactive docs error template \n#5548\n\n\nAdd rounding parameter to DecimalField \n#5562\n\n\nFix all BytesWarning caught during tests \n#5561\n\n\nUse dict and set literals instead of calls to dict() and set() \n#5559\n\n\nChange ImageField validation pattern, use validators from DjangoImageField \n#5539\n\n\nFix processing unicode symbols in query_string by Python 2 \n#5552\n\n\n\n\n3.7.1\n\n\nDate\n: \n16th October 2017\n\n\n\n\nFix Interactive documentation always uses false for boolean fields in requests \n#5492\n\n\nImprove compatibility with Django 2.0 alpha. \n#5500\n \n#5503\n\n\nImproved handling of schema naming collisions \n#5486\n\n\nAdded additional docs and tests around providing a default value for dotted \nsource\n fields \n#5489\n\n\n\n\n3.7.0\n\n\nDate\n: \n6th October 2017\n\n\n\n\nFix \nDjangoModelPermissions\n to ensure user authentication before calling the view's \nget_queryset()\n method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. \n#5376\n\n\nDeprecated \nexclude_from_schema\n on \nAPIView\n and \napi_view\n decorator. Set \nschema = None\n or \n@schema(None)\n as appropriate. \n#5422\n\n\n\n\nTimezone-aware \nDateTimeField\ns now respect active or default \ntimezone\n during serialization, instead of always using UTC. \n#5435\n\n\nResolves inconsistency whereby instances were serialised with supplied datetime for \ncreate\n but UTC for \nretrieve\n. \n#3732\n\n\nPossible backwards compatibility break\n if you were relying on datetime strings being UTC. Have client interpret datetimes or \nset default or active timezone (docs)\n to UTC if needed.\n\n\n\n\n\n\nRemoved DjangoFilterBackend inline with deprecation policy. Use \ndjango_filters.rest_framework.FilterSet\n and/or \ndjango_filters.rest_framework.DjangoFilterBackend\n instead. \n#5273\n\n\n\n\nDon't strip microseconds from \ntime\n when encoding. Makes consistent with \ndatetime\n.\n \nBC Change\n: Previously only milliseconds were encoded. \n#5440\n\n\nAdded \nSTRICT_JSON\n setting (default \nTrue\n) to raise exception for the extended float values (\nnan\n, \ninf\n, \n-inf\n) accepted by Python's \njson\n module.\n \nBC Change\n: Previously these values would converted to corresponding strings. Set \nSTRICT_JSON\n to \nFalse\n to restore the previous behaviour. \n#5265\n\n\nAdd support for \npage_size\n parameter in CursorPaginator class \n#5250\n\n\nMake \nDEFAULT_PAGINATION_CLASS\n \nNone\n by default.\n \nBC Change\n: If your were \njust\n setting \nPAGE_SIZE\n to enable pagination you will need to add \nDEFAULT_PAGINATION_CLASS\n.\n The previous default was \nrest_framework.pagination.PageNumberPagination\n. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. \n#5170\n\n\nCatch \nAPIException\n from \nget_serializer_fields\n in schema generation. \n#5443\n\n\nAllow custom authentication and permission classes when using \ninclude_docs_urls\n \n#5448\n\n\nDefer translated string evaluation on validators. \n#5452\n\n\nAdded default value for 'detail' param into 'ValidationError' exception \n#5342\n\n\nAdjust schema get_filter_fields rules to match framework \n#5454\n\n\nUpdated test matrix to add Django 2.0 and drop Django 1.8 & 1.9\n \nBC Change\n: This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. \n#5457\n\n\nFixed a deprecation warning in serializers.ModelField \n#5058\n\n\nAdded a more explicit error message when \nget_queryset\n returned \nNone\n \n#5348\n\n\nFix docs for Response \ndata\n description \n#5361\n\n\nFix \npycache\n/.pyc excludes when packaging \n#5373\n\n\nFix default value handling for dotted sources \n#5375\n\n\nEnsure content_type is set when passing empty body to RequestFactory \n#5351\n\n\nFix ErrorDetail Documentation \n#5380\n\n\nAllow optional content in the generic content form \n#5372\n\n\nUpdated supported values for the NullBooleanField \n#5387\n\n\nFix ModelSerializer custom named fields with source on model \n#5388\n\n\nFixed the MultipleFieldLookupMixin documentation example to properly check for object level permission \n#5398\n\n\nUpdate get_object() example in permissions.md \n#5401\n\n\nFix authtoken management command \n#5415\n\n\nFix schema generation markdown \n#5421\n\n\nAllow \nChoiceField.choices\n to be set dynamically \n#5426\n\n\nAdd the project layout to the quickstart \n#5434\n\n\nReuse 'apply_markdown' function in 'render_markdown' templatetag \n#5469\n\n\nAdded links to \ndrf-openapi\n package in docs \n#5470\n\n\nAdded docstrings code highlighting with pygments \n#5462\n\n\nFixed documentation rendering for views named \ndata\n \n#5472\n\n\nDocs: Clarified 'to_internal_value()' validation behavior \n#5466\n\n\nFix missing six.text_type() call on APIException.\nstr\n \n#5476\n\n\nDocument documentation.py \n#5478\n\n\nFix naming collisions in Schema Generation \n#5464\n\n\nCall Django's authenticate function with the request object \n#5295\n\n\nUpdate coreapi JS to 0.1.1 \n#5479\n\n\nHave \nis_list_view\n recognise RetrieveModel\u2026 views \n#5480\n\n\nRemove Django 1.8 & 1.9 compatibility code \n#5481\n\n\nRemove deprecated schema code from DefaultRouter \n#5482\n\n\nRefactor schema generation to allow per-view customisation.\n \nBC Change\n: \nSchemaGenerator.get_serializer_fields\n has been refactored as \nAutoSchema.get_serializer_fields\n and drops the \nview\n argument [#5354][gh5354]\n\n\n\n\n3.6.x series\n\n\n3.6.4\n\n\nDate\n: \n21st August 2017\n\n\n\n\nIgnore any invalidly formed query parameters for OrderingFilter. \n#5131\n\n\nImprove memory footprint when reading large JSON requests. \n#5147\n\n\nFix schema generation for pagination. \n#5161\n\n\nFix exception when \nHTML_CUTOFF\n is set to \nNone\n. \n#5174\n\n\nFix browsable API not supporting \nmultipart/form-data\n correctly. \n#5176\n\n\nFixed \ntest_hyperlinked_related_lookup_url_encoded_exists\n. \n#5179\n\n\nMake sure max_length is in FileField kwargs. \n#5186\n\n\nFix \nlist_route\n & \ndetail_route\n with kwargs contains curly bracket in \nurl_path\n \n#5187\n\n\nAdd Django manage command to create a DRF user Token. \n#5188\n\n\nEnsure API documentation templates do not check for user authentication \n#5162\n\n\nFix special case where OneToOneField is also primary key. \n#5192\n\n\nAdded aria-label and a new region for accessibility purposes in base.html \n#5196\n\n\nQuote nested API parameters in api.js. \n#5214\n\n\nSet ViewSet args/kwargs/request before dispatch. \n#5229\n\n\nAdded unicode support to SlugField. \n#5231\n\n\nFix HiddenField appears in Raw Data form initial content. \n#5259\n\n\nRaise validation error on invalid timezone parsing. \n#5261\n\n\nFix SearchFilter to-many behavior/performance. \n#5264\n\n\nSimplified chained comparisons and minor code fixes. \n#5276\n\n\nRemoteUserAuthentication, docs, and tests. \n#5306\n\n\nRevert \"Cached the field's root and context property\" \n#5313\n\n\nFix introspection of list field in schema. \n#5326\n\n\nFix interactive docs for multiple nested and extra methods. \n#5334\n\n\nFix/remove undefined template var \"schema\" \n#5346\n\n\n\n\n3.6.3\n\n\nDate\n: \n12th May 2017\n\n\n\n\nRaise 404 if a URL lookup results in ValidationError. (\n#5126\n)\n\n\nHonor http_method_names on class based view, when generating API schemas. (\n#5085\n)\n\n\nAllow overridden \nget_limit\n in LimitOffsetPagination to return all records. (\n#4437\n)\n\n\nFix partial update for the ListSerializer. (\n#4222\n)\n\n\nRender JSONField control correctly in browsable API. (\n#4999\n, \n#5042\n)\n\n\nRaise validation errors for invalid datetime in given timezone. (\n#4987\n)\n\n\nSupport restricting doc & schema shortcuts to a subset of urls. (\n#4979\n)\n\n\nResolve SchemaGenerator error with paginators that have no \npage_size\n attribute. (\n#5086\n, \n#3692\n)\n\n\nResolve HyperlinkedRelatedField exception on string with %20 instead of space. (\n#4748\n, \n#5078\n)\n\n\nCustomizable schema generator classes. (\n#5082\n)\n\n\nUpdate existing vary headers in response instead of overwriting them. (\n#5047\n)\n\n\nSupport passing \n.as_view()\n to view instance. (\n#5053\n)\n\n\nUse correct exception handler when settings overridden on a view. (\n#5055\n, \n#5054\n)\n\n\nUpdate Boolean field to support 'yes' and 'no' values. (\n#5038\n)\n\n\nFix unique validator for ChoiceField. (\n#5004\n, \n#5026\n, \n#5028\n)\n\n\nJavaScript cleanups in API Docs. (\n#5001\n)\n\n\nInclude URL path regexs in API schemas where valid. (\n#5014\n)\n\n\nCorrectly set scheme in coreapi TokenAuthentication. (\n#5000\n, \n#4994\n)\n\n\nHEAD requests on ViewSets should not return 405. (\n#4705\n, \n#4973\n, \n#4864\n)\n\n\nSupport usage of 'source' in \nextra_kwargs\n. (\n#4688\n)\n\n\nFix invalid content type for schema.js (\n#4968\n)\n\n\nFix DjangoFilterBackend inheritance issues. (\n#5089\n, \n#5117\n)\n\n\n\n\n3.6.2\n\n\nDate\n: \n10th March 2017\n\n\n\n\nSupport for Safari & IE in API docs. (\n#4959\n, \n#4961\n)\n\n\nAdd missing \nmark_safe\n in API docs template tags. (\n#4952\n, \n#4953\n)\n\n\nAdd missing glyphicon fonts. (\n#4950\n, \n#4951\n)\n\n\nFix One-to-one fields in API docs. (\n#4955\n, \n#4956\n)\n\n\nTest clean ups. (\n#4949\n)\n\n\n\n\n3.6.1\n\n\nDate\n: \n9th March 2017\n\n\n\n\nEnsure \nmarkdown\n dependency is optional. (\n#4947\n)\n\n\n\n\n3.6.0\n\n\nDate\n: \n9th March 2017\n\n\nSee the \nrelease announcement\n.\n\n\n\n\n3.5.x series\n\n\n3.5.4\n\n\nDate\n: \n10th February 2017\n\n\n\n\nAdd max_length and min_length arguments for ListField. (\n#4877\n)\n\n\nAdd per-view custom exception handler support. (\n#4753\n)\n\n\nSupport disabling of declared fields on serializer subclasses. (\n#4764\n)\n\n\nSupport custom view names on \n@list_route\n and \n@detail_route\n endpoints. (\n#4821\n)\n\n\nCorrect labels for fields in login template when custom user model is used. (\n#4841\n)\n\n\nWhitespace fixes for descriptions generated from docstrings. (\n#4759\n, \n#4869\n, \n#4870\n)\n\n\nBetter error reporting when schemas are returned by views without a schema renderer. (\n#4790\n)\n\n\nFix for returned response of \nPUT\n requests when \nprefetch_related\n is used. (\n#4661\n, \n#4668\n)\n\n\nFix for breadcrumb view names. (\n#4750\n)\n\n\nFix for RequestsClient ensuring fully qualified URLs. (\n#4678\n)\n\n\nFix for incorrect behavior of writable-nested fields check in some cases. (\n#4634\n, \n#4669\n)\n\n\nResolve Django deprecation warnings. (\n#4712\n)\n\n\nVarious cleanup of test cases.\n\n\n\n\n3.5.3\n\n\nDate\n: \n7th November 2016\n\n\n\n\nDon't raise incorrect FilterSet deprecation warnings. (\n#4660\n, \n#4643\n, \n#4644\n)\n\n\nSchema generation should not raise 404 when a view permission class does. (\n#4645\n, \n#4646\n)\n\n\nAdd \nautofocus\n support for input controls. (\n#4650\n)\n\n\n\n\n3.5.2\n\n\nDate\n: \n1st November 2016\n\n\n\n\nRestore exception tracebacks in Python 2.7. (\n#4631\n, \n#4638\n)\n\n\nProperly display dicts in the admin console. (\n#4532\n, \n#4636\n)\n\n\nFix is_simple_callable with variable args, kwargs. (\n#4622\n, \n#4602\n)\n\n\nSupport 'on'/'off' literals with BooleanField. (\n#4640\n, \n#4624\n)\n\n\nEnable cursor pagination of value querysets. (\n#4569\n)\n\n\nFix support of get_full_details() for Throttled exceptions. (\n#4627\n)\n\n\nFix FilterSet proxy. (\n#4620\n)\n\n\nMake serializer fields import explicit. (\n#4628\n)\n\n\nDrop redundant requests adapter. (\n#4639\n)\n\n\n\n\n3.5.1\n\n\nDate\n: \n21st October 2016\n\n\n\n\nMake \nrest_framework/compat.py\n imports. (\n#4612\n, \n#4608\n, \n#4601\n)\n\n\nFix bug in schema base path generation. (\n#4611\n, \n#4605\n)\n\n\nFix broken case of ListSerializer with single item. (\n#4609\n, \n#4606\n)\n\n\nRemove bare \nraise\n for Python 3.5 compat. (\n#4600\n)\n\n\n\n\n3.5.0\n\n\nDate\n: \n20th October 2016\n\n\n\n\n3.4.x series\n\n\n3.4.7\n\n\nDate\n: \n21st September 2016\n\n\n\n\nFallback behavior for request parsing when request.POST already accessed. (\n#3951\n, \n#4500\n)\n\n\nFix regression of \nRegexField\n. (\n#4489\n, \n#4490\n, \n#2617\n)\n\n\nMissing comma in \nadmin.html\n causing CSRF error. (\n#4472\n, \n#4473\n)\n\n\nFix response rendering with empty context. (\n#4495\n)\n\n\nFix indentation regression in API listing. (\n#4493\n)\n\n\nFixed an issue where the incorrect value is set to \nResolverMatch.func_name\n of api_view decorated view. (\n#4465\n, \n#4462\n)\n\n\nFix \nAPIClient.get()\n when path contains unicode arguments (\n#4458\n)\n\n\n\n\n3.4.6\n\n\nDate\n: \n23rd August 2016\n\n\n\n\nFix malformed Javascript in browsable API. (\n#4435\n)\n\n\nSkip HiddenField from Schema fields. (\n#4425\n, \n#4429\n)\n\n\nImprove Create to show the original exception traceback. (\n#3508\n)\n\n\nFix \nAdminRenderer\n display of PK only related fields. (\n#4419\n, \n#4423\n)\n\n\n\n\n3.4.5\n\n\nDate\n: \n19th August 2016\n\n\n\n\nImprove debug error handling. (\n#4416\n, \n#4409\n)\n\n\nAllow custom CSRF_HEADER_NAME setting. (\n#4415\n, \n#4410\n)\n\n\nInclude .action attribute on viewsets when generating schemas. (\n#4408\n, \n#4398\n)\n\n\nDo not include request.FILES items in request.POST. (\n#4407\n)\n\n\nFix rendering of checkbox multiple. (\n#4403\n)\n\n\nFix docstring of Field.get_default. (\n#4404\n)\n\n\nReplace utf8 character with its ascii counterpart in README. (\n#4412\n)\n\n\n\n\n3.4.4\n\n\nDate\n: \n12th August 2016\n\n\n\n\nEnsure views are fully initialized when generating schemas. (\n#4373\n, \n#4382\n, \n#4383\n, \n#4279\n, \n#4278\n)\n\n\nAdd form field descriptions to schemas. (\n#4387\n)\n\n\nFix category generation for schema endpoints. (\n#4391\n, \n#4394\n, \n#4390\n, \n#4386\n, \n#4376\n, \n#4329\n)\n\n\nDon't strip empty query params when paginating. (\n#4392\n, \n#4393\n, \n#4260\n)\n\n\nDo not re-run query for empty results with LimitOffsetPagination. (\n#4201\n, \n#4388\n)\n\n\nStricter type validation for CharField. (\n#4380\n, \n#3394\n)\n\n\nRelatedField.choices should preserve non-string values. (\n#4111\n, \n#4379\n, \n#3365\n)\n\n\nTest case for rendering checkboxes in vertical form style. (\n#4378\n, \n#3868\n, \n#3868\n)\n\n\nShow error traceback HTML in browsable API (\n#4042\n, \n#4172\n)\n\n\nFix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. \n#4370\n\n\nAllow \nmax_digits=None\n on DecimalField. (\n#4377\n, \n#4372\n)\n\n\nLimit queryset when rendering relational choices. (\n#4375\n, \n#4122\n, \n#3329\n, \n#3330\n, \n#3877\n)\n\n\nResolve form display with ChoiceField, MultipleChoiceField and non-string choices. (\n#4374\n, \n#4119\n, \n#4121\n, \n#4137\n, \n#4120\n)\n\n\nFix call to TemplateHTMLRenderer.resolve_context() fallback method. (\n#4371\n)\n\n\n\n\n3.4.3\n\n\nDate\n: \n5th August 2016\n\n\n\n\nInclude fallback for users of older TemplateHTMLRenderer internal API. (\n#4361\n)\n\n\n\n\n3.4.2\n\n\nDate\n: \n5th August 2016\n\n\n\n\nInclude kwargs passed to 'as_view' when generating schemas. (\n#4359\n, \n#4330\n, \n#4331\n)\n\n\nAccess \nrequest.user.is_authenticated\n as property not method, under Django 1.10+ (\n#4358\n, \n#4354\n)\n\n\nFilter HEAD out from schemas. (\n#4357\n)\n\n\nextra_kwargs takes precedence over uniqueness kwargs. (\n#4198\n, \n#4199\n, \n#4349\n)\n\n\nCorrect descriptions when tabs are used in code indentation. (\n#4345\n, \n#4347\n)*\n\n\nChange template context generation in TemplateHTMLRenderer. (\n#4236\n)\n\n\nSerializer defaults should not be included in partial updates. (\n#4346\n, \n#3565\n)\n\n\nConsistent behavior & descriptive error from FileUploadParser when filename not included. (\n#4340\n, \n#3610\n, \n#4292\n, \n#4296\n)\n\n\nDecimalField quantizes incoming digitals. (\n#4339\n, \n#4318\n)\n\n\nHandle non-string input for IP fields. (\n#4335\n, \n#4336\n, \n#4338\n)\n\n\nFix leading slash handling when Schema generation includes a root URL. (\n#4332\n)\n\n\nTest cases for DictField with allow_null options. (\n#4348\n)\n\n\nUpdate tests from Django 1.10 beta to Django 1.10. (\n#4344\n)\n\n\n\n\n3.4.1\n\n\nDate\n: \n28th July 2016\n\n\n\n\nAdded \nroot_renderers\n argument to \nDefaultRouter\n. (\n#4323\n, \n#4268\n)\n\n\nAdded \nurl\n and \nschema_url\n arguments. (\n#4321\n, \n#4308\n, \n#4305\n)\n\n\nUnique together checks should apply to read-only fields which have a default. (\n#4316\n, \n#4294\n)\n\n\nSet view.format_kwarg in schema generator. (\n#4293\n, \n#4315\n)\n\n\nFix schema generator for views with \npagination_class = None\n. (\n#4314\n, \n#4289\n)\n\n\nFix schema generator for views with no \nget_serializer_class\n. (\n#4265\n, \n#4285\n)\n\n\nFixes for media type parameters in \nAccept\n and \nContent-Type\n headers. (\n#4287\n, \n#4313\n, \n#4281\n)\n\n\nUse verbose_name instead of object_name in error messages. (\n#4299\n)\n\n\nMinor version update to Twitter Bootstrap. (\n#4307\n)\n\n\nSearchFilter raises error when using with related field. (\n#4302\n, \n#4303\n, \n#4298\n)\n\n\nAdding support for RFC 4918 status codes. (\n#4291\n)\n\n\nAdd LICENSE.md to the built wheel. (\n#4270\n)\n\n\nSerializing \"complex\" field returns None instead of the value since 3.4 (\n#4272\n, \n#4273\n, \n#4288\n)\n\n\n\n\n3.4.0\n\n\nDate\n: \n14th July 2016\n\n\n\n\nDon't strip microseconds in JSON output. (\n#4256\n)\n\n\nTwo slightly different iso 8601 datetime serialization. (\n#4255\n)\n\n\nResolve incorrect inclusion of media type parameters. (\n#4254\n)\n\n\nResponse Content-Type potentially malformed. (\n#4253\n)\n\n\nFix setup.py error on some platforms. (\n#4246\n)\n\n\nMove alternate formats in coreapi into separate packages. (\n#4244\n)\n\n\nAdd localize keyword argument to \nDecimalField\n. (\n#4233\n)\n\n\nFix issues with routers for custom list-route and detail-routes. (\n#4229\n)\n\n\nNamespace versioning with nested namespaces. (\n#4219\n)\n\n\nRobust uniqueness checks. (\n#4217\n)\n\n\nMinor refactoring of \nmust_call_distinct\n. (\n#4215\n)\n\n\nOverridable offset cutoff in CursorPagination. (\n#4212\n)\n\n\nPass through strings as-in with date/time fields. (\n#4196\n)\n\n\nAdd test confirming that required=False is valid on a relational field. (\n#4195\n)\n\n\nIn LimitOffsetPagination \nlimit=0\n should revert to default limit. (\n#4194\n)\n\n\nExclude read_only=True fields from unique_together validation & add docs. (\n#4192\n)\n\n\nHandle bytestrings in JSON. (\n#4191\n)\n\n\nJSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (\n#4187\n)\n\n\nJSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (\n#4185\n)\n\n\nMore robust form rendering in the browsable API. (\n#4181\n)\n\n\nEmpty cases of \n.validated_data\n and \n.errors\n as lists not dicts for ListSerializer. (\n#4180\n)\n\n\nSchemas & client libraries. (\n#4179\n)\n\n\nRemoved \nAUTH_USER_MODEL\n compat property. (\n#4176\n)\n\n\nClean up existing deprecation warnings. (\n#4166\n)\n\n\nDjango 1.10 support. (\n#4158\n)\n\n\nUpdated jQuery version to 1.12.4. (\n#4157\n)\n\n\nMore robust default behavior on OrderingFilter. (\n#4156\n)\n\n\ndescription.py codes and tests removal. (\n#4153\n)\n\n\nWrap guardian.VERSION in tuple. (\n#4149\n)\n\n\nRefine validator for fields with \n kwargs. (\n#4146\n)\n\n\nFix None values representation in childs of ListField, DictField. (\n#4118\n)\n\n\nResolve TimeField representation for midnight value. (\n#4107\n)\n\n\nSet proper status code in AdminRenderer for the redirection after POST/DELETE requests. (\n#4106\n)\n\n\nTimeField render returns None instead of 00:00:00. (\n#4105\n)\n\n\nFix incorrectly named zh-hans and zh-hant locale path. (\n#4103\n)\n\n\nPrevent raising exception when limit is 0. (\n#4098\n)\n\n\nTokenAuthentication: Allow custom keyword in the header. (\n#4097\n)\n\n\nHandle incorrectly padded HTTP basic auth header. (\n#4090\n)\n\n\nLimitOffset pagination crashes Browseable API when limit=0. (\n#4079\n)\n\n\nFixed DecimalField arbitrary precision support. (\n#4075\n)\n\n\nAdded support for custom CSRF cookie names. (\n#4049\n)\n\n\nFix regression introduced by #4035. (\n#4041\n)\n\n\nNo auth view failing permission should raise 403. (\n#4040\n)\n\n\nFix string_types / text_types confusion. (\n#4025\n)\n\n\nDo not list related field choices in OPTIONS requests. (\n#4021\n)\n\n\nFix typo. (\n#4008\n)\n\n\nReorder initializing the view. (\n#4006\n)\n\n\nType error in DjangoObjectPermissionsFilter on Python 3.4. (\n#4005\n)\n\n\nFixed use of deprecated Query.aggregates. (\n#4003\n)\n\n\nFix blank lines around docstrings. (\n#4002\n)\n\n\nFixed admin pagination when limit is 0. (\n#3990\n)\n\n\nOrderingFilter adjustments. (\n#3983\n)\n\n\nNon-required serializer related fields. (\n#3976\n)\n\n\nUsing safer calling way of \"@api_view\" in tutorial. (\n#3971\n)\n\n\nListSerializer doesn't handle unique_together constraints. (\n#3970\n)\n\n\nAdd missing migration file. (\n#3968\n)\n\n\nOrderingFilter\n should call \nget_serializer_class()\n to determine default fields. (\n#3964\n)\n\n\nRemove old Django checks from tests and compat. (\n#3953\n)\n\n\nSupport callable as the value of \ninitial\n for any \nserializer.Field\n. (\n#3943\n)\n\n\nPrevented unnecessary distinct() call in SearchFilter. (\n#3938\n)\n\n\nFix None UUID ForeignKey serialization. (\n#3936\n)\n\n\nDrop EOL Django 1.7. (\n#3933\n)\n\n\nAdd missing space in serializer error message. (\n#3926\n)\n\n\nFixed _force_text_recursive typo. (\n#3908\n)\n\n\nAttempt to address Django 2.0 deprecate warnings related to \nfield.rel\n. (\n#3906\n)\n\n\nFix parsing multipart data using a nested serializer with list. (\n#3820\n)\n\n\nResolving APIs URL to different namespaces. (\n#3816\n)\n\n\nDo not HTML-escape \nhelp_text\n in Browsable API forms. (\n#3812\n)\n\n\nOPTIONS fetches and shows all possible foreign keys in choices field. (\n#3751\n)\n\n\nDjango 1.9 deprecation warnings (\n#3729\n)\n\n\nTest case for #3598 (\n#3710\n)\n\n\nAdding support for multiple values for search filter. (\n#3541\n)\n\n\nUse get_serializer_class in ordering filter. (\n#3487\n)\n\n\nSerializers with many=True should return empty list rather than empty dict. (\n#3476\n)\n\n\nLimitOffsetPagination limit=0 fix. (\n#3444\n)\n\n\nEnable Validators to defer string evaluation and handle new string format. (\n#3438\n)\n\n\nUnique validator is executed and breaks if field is invalid. (\n#3381\n)\n\n\nDo not ignore overridden View.get_view_name() in breadcrumbs. (\n#3273\n)\n\n\nRetry form rendering when rendering with serializer fails. (\n#3164\n)\n\n\nUnique constraint prevents nested serializers from updating. (\n#2996\n)\n\n\nUniqueness validators should not be run for excluded (read_only) fields. (\n#2848\n)\n\n\nUniqueValidator raises exception for nested objects. (\n#2403\n)\n\n\nlookup_type\n is deprecated in favor of \nlookup_expr\n. (\n#4259\n)\n\n\n\n\n\n\n3.3.x series\n\n\n3.3.3\n\n\nDate\n: \n14th March 2016\n.\n\n\n\n\nRemove version string from templates. Thanks to @blag for the report and fixes. (\n#3878\n, \n#3913\n, \n#3912\n)\n\n\nFixes vertical html layout for \nBooleanField\n. Thanks to Mikalai Radchuk for the fix. (\n#3910\n)\n\n\nSilenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. (\n#3903\n)\n\n\nInternationalization for authtoken. Thanks to Michael Nacharov for the fix. (\n#3887\n, \n#3968\n)\n\n\nFix \nToken\n model as \nabstract\n when the authtoken application isn't declared. Thanks to Adam Thomas for the report. (\n#3860\n, \n#3858\n)\n\n\nImprove Markdown version compatibility. Thanks to Michael J. Schultz for the fix. (\n#3604\n, \n#3842\n)\n\n\nQueryParameterVersioning\n does not use \nDEFAULT_VERSION\n setting. Thanks to Brad Montgomery for the fix. (\n#3833\n)\n\n\nAdd an explicit \non_delete\n on the models. Thanks to Mads Jensen for the fix. (\n#3832\n)\n\n\nFix \nDateField.to_representation\n to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. (\n#3819\n)\n\n\nFixed \nTimeField\n not handling string times. Thanks to Areski Belaid for the fix. (\n#3809\n)\n\n\nAvoid updates of \nMeta.extra_kwargs\n. Thanks to Kevin Massey for the report and fix. (\n#3805\n, \n#3804\n)\n\n\nFix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. (\n#3801\n)\n\n\nDocument how to avoid CSRF and missing button issues with \ndjango-crispy-forms\n. Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. (\n#3787\n, \n#3636\n, \n#3637\n)\n\n\nImprove Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. (\n#3786\n, \n#3815\n)\n\n\nImprove authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. (\n#3785\n)\n\n\nFix \nMin/MaxValueValidator\n transfer from a model's \nDecimalField\n. Thanks to Kevin Brown for the fix. (\n#3774\n)\n\n\nImprove HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. (\n#3769\n)\n\n\nFix \nAutoFilterSet\n to inherit from \ndefault_filter_set\n. Thanks to Tom Linford for the fix. (\n#3753\n)\n\n\nFix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. (\n#3739\n)\n\n\nDateTimeField\n does not handle empty values correctly. Thanks to Mick Parker for the report and fix. (\n#3731\n, \n#3726\n)\n\n\nRaise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. (\n#3715\n)\n\n\nAdd missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. (\n#3703\n)\n\n\nRefactored \n_get_reverse_relationships()\n to use correct \nto_field\n. Thanks to Benjamin Phillips for the fix. (\n#3696\n)\n\n\nDocument the use of \nget_queryset\n for \nRelatedField\n. Thanks to Ryan Hiebert for the fix. (\n#3605\n)\n\n\nFix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix (\n#3962\n)\n\n\n\n\n3.3.2\n\n\nDate\n: \n14th December 2015\n.\n\n\n\n\nListField\n enforces input is a list. (\n#3513\n)\n\n\nFix regression hiding raw data form. (\n#3600\n, \n#3578\n)\n\n\nFix Python 3.5 compatibility. (\n#3534\n, \n#3626\n)\n\n\nAllow setting a custom Django Paginator in \npagination.PageNumberPagination\n. (\n#3631\n, \n#3684\n)\n\n\nFix relational fields without \nto_fields\n attribute. (\n#3635\n, \n#3634\n)\n\n\nFix \ntemplate.render\n deprecation warnings for Django 1.9. (\n#3654\n)\n\n\nSort response headers in browsable API renderer. (\n#3655\n)\n\n\nUse related_objects api for Django 1.9+. (\n#3656\n, \n#3252\n)\n\n\nAdd confirm modal when deleting. (\n#3228\n, \n#3662\n)\n\n\nReveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. (\n#3668\n)\n\n\nMake DRF compatible with multi template engine in Django 1.8. (\n#3672\n)\n\n\nUpdate \nNestedBoundField\n to also handle empty string when rendering its form. (\n#3677\n)\n\n\nFix UUID validation to properly catch invalid input types. (\n#3687\n, \n#3679\n)\n\n\nFix caching issues. (\n#3628\n, \n#3701\n)\n\n\nFix Admin and API browser for views without a filter_class. (\n#3705\n, \n#3596\n, \n#3597\n)\n\n\nAdd app_name to rest_framework.urls. (\n#3714\n)\n\n\nImprove authtoken's views to support url versioning. (\n#3718\n, \n#3723\n)\n\n\n\n\n3.3.1\n\n\nDate\n: \n4th November 2015\n.\n\n\n\n\nResolve parsing bug when accessing \nrequest.POST\n (\n#3592\n)\n\n\nCorrectly deal with \nto_field\n referring to primary key. (\n#3593\n)\n\n\nAllow filter HTML to render when no \nfilter_class\n is defined. (\n#3560\n)\n\n\nFix admin rendering issues. (\n#3564\n, \n#3556\n)\n\n\nFix issue with DecimalValidator. (\n#3568\n)\n\n\n\n\n3.3.0\n\n\nDate\n: \n28th October 2015\n.\n\n\n\n\nHTML controls for filters. (\n#3315\n)\n\n\nForms API. (\n#3475\n)\n\n\nAJAX browsable API. (\n#3410\n)\n\n\nAdded JSONField. (\n#3454\n)\n\n\nCorrectly map \nto_field\n when creating \nModelSerializer\n relational fields. (\n#3526\n)\n\n\nInclude keyword arguments when mapping \nFilePathField\n to a serializer field. (\n#3536\n)\n\n\nMap appropriate model \nerror_messages\n on \nModelSerializer\n uniqueness constraints. (\n#3435\n)\n\n\nInclude \nmax_length\n constraint for \nModelSerializer\n fields mapped from TextField. (\n#3509\n)\n\n\nAdded support for Django 1.9. (\n#3450\n, \n#3525\n)\n\n\nRemoved support for Django 1.5 & 1.6. (\n#3421\n, \n#3429\n)\n\n\nRemoved 'south' migrations. (\n#3495\n)\n\n\n\n\n\n\n3.2.x series\n\n\n3.2.5\n\n\nDate\n: \n27th October 2015\n.\n\n\n\n\nEscape \nusername\n in optional logout tag. (\n#3550\n)\n\n\n\n\n3.2.4\n\n\nDate\n: \n21th September 2015\n.\n\n\n\n\nDon't error on missing \nViewSet.search_fields\n attribute. (\n#3324\n, \n#3323\n)\n\n\nFix \nallow_empty\n not working on serializers with \nmany=True\n. (\n#3361\n, \n#3364\n)\n\n\nLet \nDurationField\n accepts integers. (\n#3359\n)\n\n\nMulti-level dictionaries not supported in multipart requests. (\n#3314\n)\n\n\nFix \nListField\n truncation on HTTP PATCH (\n#3415\n, \n#2761\n)\n\n\n\n\n3.2.3\n\n\nDate\n: \n24th August 2015\n.\n\n\n\n\nAdded \nhtml_cutoff\n and \nhtml_cutoff_text\n for limiting select dropdowns. (\n#3313\n)\n\n\nAdded regex style to \nSearchFilter\n. (\n#3316\n)\n\n\nResolve issues with setting blank HTML fields. (\n#3318\n) (\n#3321\n)\n\n\nCorrectly display existing 'select multiple' values in browsable API forms. (\n#3290\n)\n\n\nResolve duplicated validation message for \nIPAddressField\n. ([#3249[gh3249]) (\n#3250\n)\n\n\nFix to ensure admin renderer continues to work when pagination is disabled. (\n#3275\n)\n\n\nResolve error with \nLimitOffsetPagination\n when count=0, offset=0. (\n#3303\n)\n\n\n\n\n3.2.2\n\n\nDate\n: \n13th August 2015\n.\n\n\n\n\nAdd \ndisplay_value()\n method for use when displaying relational field select inputs. (\n#3254\n)\n\n\nFix issue with \nBooleanField\n checkboxes incorrectly displaying as checked. (\n#3258\n)\n\n\nEnsure empty checkboxes properly set \nBooleanField\n to \nFalse\n in all cases. (\n#2776\n)\n\n\nAllow \nWSGIRequest.FILES\n property without raising incorrect deprecated error. (\n#3261\n)\n\n\nResolve issue with rendering nested serializers in forms. (\n#3260\n)\n\n\nRaise an error if user accidentally pass a serializer instance to a response, rather than data. (\n#3241\n)\n\n\n\n\n3.2.1\n\n\nDate\n: \n7th August 2015\n.\n\n\n\n\nFix for relational select widgets rendering without any choices. (\n#3237\n)\n\n\nFix for \n1\n, \n0\n rendering as \ntrue\n, \nfalse\n in the admin interface. \n#3227\n)\n\n\nFix for ListFields with single value in HTML form input. (\n#3238\n)\n\n\nAllow \nrequest.FILES\n for compat with Django's \nHTTPRequest\n class. (\n#3239\n)\n\n\n\n\n3.2.0\n\n\nDate\n: \n6th August 2015\n.\n\n\n\n\nAdd \nAdminRenderer\n. (\n#2926\n)\n\n\nAdd \nFilePathField\n. (\n#1854\n)\n\n\nAdd \nallow_empty\n to \nListField\n. (\n#2250\n)\n\n\nSupport django-guardian 1.3. (\n#3165\n)\n\n\nSupport grouped choices. (\n#3225\n)\n\n\nSupport error forms in browsable API. (\n#3024\n)\n\n\nAllow permission classes to customize the error message. (\n#2539\n)\n\n\nSupport \nsource=\n on hyperlinked fields. (\n#2690\n)\n\n\nListField(allow_null=True)\n now allows null as the list value, not null items in the list. (\n#2766\n)\n\n\nManyToMany()\n maps to \nallow_empty=False\n, \nManyToMany(blank=True)\n maps to \nallow_empty=True\n. (\n#2804\n)\n\n\nSupport custom serialization styles for primary key fields. (\n#2789\n)\n\n\nOPTIONS\n requests support nested representations. (\n#2915\n)\n\n\nSet \nview.action == \"metadata\"\n for viewsets with \nOPTIONS\n requests. (\n#3115\n)\n\n\nSupport \nallow_blank\n on \nUUIDField\n. ([#3130][gh#3130])\n\n\nDo not display view docstrings with 401 or 403 response codes. (\n#3216\n)\n\n\nResolve Django 1.8 deprecation warnings. (\n#2886\n)\n\n\nFix for \nDecimalField\n validation. (\n#3139\n)\n\n\nFix behavior of \nallow_blank=False\n when used with \ntrim_whitespace=True\n. (\n#2712\n)\n\n\nFix issue with some field combinations incorrectly mapping to an invalid \nallow_blank\n argument. (\n#3011\n)\n\n\nFix for output representations with prefetches and modified querysets. (\n#2704\n, \n#2727\n)\n\n\nFix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920)\ngh2920\n.\n\n\nFix \nUnicodeDecodeError\n when invalid characters included in header with \nTokenAuthentication\n. (\n#2928\n)\n\n\nFix transaction rollbacks with \n@non_atomic_requests\n decorator. (\n#3016\n)\n\n\nFix duplicate results issue with Oracle databases using \nSearchFilter\n. (\n#2935\n)\n\n\nFix checkbox alignment and rendering in browsable API forms. (\n#2783\n)\n\n\nFix for unsaved file objects which should use \n\"url\": null\n in the representation. (\n#2759\n)\n\n\nFix field value rendering in browsable API. (\n#2416\n)\n\n\nFix \nHStoreField\n to include \nallow_blank=True\n in \nDictField\n mapping. (\n#2659\n)\n\n\nNumerous other cleanups, improvements to error messaging, private API & minor fixes.\n\n\n\n\n\n\n3.1.x series\n\n\n3.1.3\n\n\nDate\n: \n4th June 2015\n.\n\n\n\n\nAdd \nDurationField\n. (\n#2481\n, \n#2989\n)\n\n\nAdd \nformat\n argument to \nUUIDField\n. (\n#2788\n, \n#3000\n)\n\n\nMultipleChoiceField\n empties incorrectly on a partial update using multipart/form-data (\n#2993\n, \n#2894\n)\n\n\nFix a bug in options related to read-only \nRelatedField\n. (\n#2981\n, \n#2811\n)\n\n\nFix nested serializers with \nunique_together\n relations. (\n#2975\n)\n\n\nAllow unexpected values for \nChoiceField\n/\nMultipleChoiceField\n representations. (\n#2839\n, \n#2940\n)\n\n\nRollback the transaction on error if \nATOMIC_REQUESTS\n is set. (\n#2887\n, \n#2034\n)\n\n\nSet the action on a view when override_method regardless of its None-ness. (\n#2933\n)\n\n\nDecimalField\n accepts \n2E+2\n as 200 and validates decimal place correctly. (\n#2948\n, \n#2947\n)\n\n\nSupport basic authentication with custom \nUserModel\n that change \nusername\n. (\n#2952\n)\n\n\nIPAddressField\n improvements. (\n#2747\n, \n#2618\n, \n#3008\n)\n\n\nImprove \nDecimalField\n for easier subclassing. (\n#2695\n)\n\n\n\n\n3.1.2\n\n\nDate\n: \n13rd May 2015\n.\n\n\n\n\nDateField.to_representation\n can handle str and empty values. (\n#2656\n, \n#2687\n, \n#2869\n)\n\n\nUse default reason phrases from HTTP standard. (\n#2764\n, \n#2763\n)\n\n\nRaise error when \nModelSerializer\n used with abstract model. (\n#2757\n, \n#2630\n)\n\n\nHandle reversal of non-API view_name in \nHyperLinkedRelatedField\n (\n#2724\n, \n#2711\n)\n\n\nDon't require pk strictly for related fields. (\n#2745\n, \n#2754\n)\n\n\nMetadata detects null boolean field type. (\n#2762\n)\n\n\nProper handling of depth in nested serializers. (\n#2798\n)\n\n\nDisplay viewset without paginator. (\n#2807\n)\n\n\nDon't check for deprecated \n.model\n attribute in permissions (\n#2818\n)\n\n\nRestrict integer field to integers and strings. (\n#2835\n, \n#2836\n)\n\n\nImprove \nIntegerField\n to use compiled decimal regex. (\n#2853\n)\n\n\nPrevent empty \nqueryset\n to raise AssertionError. (\n#2862\n)\n\n\nDjangoModelPermissions\n rely on \nget_queryset\n. (\n#2863\n)\n\n\nCheck \nAcceptHeaderVersioning\n with content negotiation in place. (\n#2868\n)\n\n\nAllow \nDjangoObjectPermissions\n to use views that define \nget_queryset\n. (\n#2905\n)\n\n\n\n\n3.1.1\n\n\nDate\n: \n23rd March 2015\n.\n\n\n\n\nSecurity fix\n: Escape tab switching cookie name in browsable API.\n\n\nDisplay input forms in browsable API if \nserializer_class\n is used, even when \nget_serializer\n method does not exist on the view. (\n#2743\n)\n\n\nUse a password input for the AuthTokenSerializer. (\n#2741\n)\n\n\nFix missing anchor closing tag after next button. (\n#2691\n)\n\n\nFix \nlookup_url_kwarg\n handling in viewsets. (\n#2685\n, \n#2591\n)\n\n\nFix problem with importing \nrest_framework.views\n in \napps.py\n (\n#2678\n)\n\n\nLimitOffsetPagination raises \nTypeError\n if PAGE_SIZE not set (\n#2667\n, \n#2700\n)\n\n\nGerman translation for \nmin_value\n field error message references \nmax_value\n. (\n#2645\n)\n\n\nRemove \nMergeDict\n. (\n#2640\n)\n\n\nSupport serializing unsaved models with related fields. (\n#2637\n, \n#2641\n)\n\n\nAllow blank/null on radio.html choices. (\n#2631\n)\n\n\n\n\n3.1.0\n\n\nDate\n: \n5th March 2015\n.\n\n\nFor full details see the \n3.1 release announcement\n.\n\n\n\n\n3.0.x series\n\n\n3.0.5\n\n\nDate\n: \n10th February 2015\n.\n\n\n\n\nFix a bug where \n_closable_objects\n breaks pickling. (\n#1850\n, \n#2492\n)\n\n\nAllow non-standard \nUser\n models with \nThrottling\n. (\n#2524\n)\n\n\nSupport custom \nUser.db_table\n in TokenAuthentication migration. (\n#2479\n)\n\n\nFix misleading \nAttributeError\n tracebacks on \nRequest\n objects. (\n#2530\n, \n#2108\n)\n\n\nManyRelatedField.get_value\n clearing field on partial update. (\n#2475\n)\n\n\nRemoved '.model' shortcut from code. (\n#2486\n)\n\n\nFix \ndetail_route\n and \nlist_route\n mutable argument. (\n#2518\n)\n\n\nPrefetching the user object when getting the token in \nTokenAuthentication\n. (\n#2519\n)\n\n\n\n\n3.0.4\n\n\nDate\n: \n28th January 2015\n.\n\n\n\n\nDjango 1.8a1 support. (\n#2425\n, \n#2446\n, \n#2441\n)\n\n\nAdd \nDictField\n and support Django 1.8 \nHStoreField\n. (\n#2451\n, \n#2106\n)\n\n\nAdd \nUUIDField\n and support Django 1.8 \nUUIDField\n. (\n#2448\n, \n#2433\n, \n#2432\n)\n\n\nBaseRenderer.render\n now raises \nNotImplementedError\n. (\n#2434\n)\n\n\nFix timedelta JSON serialization on Python 2.6. (\n#2430\n)\n\n\nResultDict\n and \nResultList\n now appear as standard dict/list. (\n#2421\n)\n\n\nFix visible \nHiddenField\n in the HTML form of the web browsable API page. (\n#2410\n)\n\n\nUse \nOrderedDict\n for \nRelatedField.choices\n. (\n#2408\n)\n\n\nFix ident format when using \nHTTP_X_FORWARDED_FOR\n. (\n#2401\n)\n\n\nFix invalid key with memcached while using throttling. (\n#2400\n)\n\n\nFix \nFileUploadParser\n with version 3.x. (\n#2399\n)\n\n\nFix the serializer inheritance. (\n#2388\n)\n\n\nFix caching issues with \nReturnDict\n. (\n#2360\n)\n\n\n\n\n3.0.3\n\n\nDate\n: \n8th January 2015\n.\n\n\n\n\nFix \nMinValueValidator\n on \nmodels.DateField\n. (\n#2369\n)\n\n\nFix serializer missing context when pagination is used. (\n#2355\n)\n\n\nNamespaced router URLs are now supported by the \nDefaultRouter\n. (\n#2351\n)\n\n\nrequired=False\n allows omission of value for output. (\n#2342\n)\n\n\nUse textarea input for \nmodels.TextField\n. (\n#2340\n)\n\n\nUse custom \nListSerializer\n for pagination if required. (\n#2331\n, \n#2327\n)\n\n\nBetter behavior with null and '' for blank HTML fields. (\n#2330\n)\n\n\nEnsure fields in \nexclude\n are model fields. (\n#2319\n)\n\n\nFix \nIntegerField\n and \nmax_length\n argument incompatibility. (\n#2317\n)\n\n\nFix the YAML encoder for 3.0 serializers. (\n#2315\n, \n#2283\n)\n\n\nFix the behavior of empty HTML fields. (\n#2311\n, \n#1101\n)\n\n\nFix Metaclass attribute depth ignoring fields attribute. (\n#2287\n)\n\n\nFix \nformat_suffix_patterns\n to work with Django's \ni18n_patterns\n. (\n#2278\n)\n\n\nAbility to customize router URLs for custom actions, using \nurl_path\n. (\n#2010\n)\n\n\nDon't install Django REST Framework as egg. (\n#2386\n)\n\n\n\n\n3.0.2\n\n\nDate\n: \n17th December 2014\n.\n\n\n\n\nEnsure \nrequest.user\n is made available to response middleware. (\n#2155\n)\n\n\nClient.logout()\n also cancels any existing \nforce_authenticate\n. (\n#2218\n, \n#2259\n)\n\n\nExtra assertions and better checks to preventing incorrect serializer API use. (\n#2228\n, \n#2234\n, \n#2262\n, \n#2263\n, \n#2266\n, \n#2267\n, \n#2289\n, \n#2291\n)\n\n\nFixed \nmin_length\n message for \nCharField\n. (\n#2255\n)\n\n\nFix \nUnicodeDecodeError\n, which can occur on serializer \nrepr\n. (\n#2270\n, \n#2279\n)\n\n\nFix empty HTML values when a default is provided. (\n#2280\n, \n#2294\n)\n\n\nFix \nSlugRelatedField\n raising \nUnicodeEncodeError\n when used as a multiple choice input. (\n#2290\n)\n\n\n\n\n3.0.1\n\n\nDate\n: \n11th December 2014\n.\n\n\n\n\nMore helpful error message when the default Serializer \ncreate()\n fails. (\n#2013\n)\n\n\nRaise error when attempting to save serializer if data is not valid. (\n#2098\n)\n\n\nFix \nFileUploadParser\n breaks with empty file names and multiple upload handlers. (\n#2109\n)\n\n\nImprove \nBindingDict\n to support standard dict-functions. (\n#2135\n, \n#2163\n)\n\n\nAdd \nvalidate()\n to \nListSerializer\n. (\n#2168\n, \n#2225\n, \n#2232\n)\n\n\nFix JSONP renderer failing to escape some characters. (\n#2169\n, \n#2195\n)\n\n\nAdd missing default style for \nFileField\n. (\n#2172\n)\n\n\nActions are required when calling \nViewSet.as_view()\n. (\n#2175\n)\n\n\nAdd \nallow_blank\n to \nChoiceField\n. (\n#2184\n, \n#2239\n)\n\n\nCosmetic fixes in the HTML renderer. (\n#2187\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2193\n, \n#2213\n)\n\n\nImprove checks for nested creates and updates. (\n#2194\n, \n#2196\n)\n\n\nvalidated_attrs\n argument renamed to \nvalidated_data\n in \nSerializer\n \ncreate()\n/\nupdate()\n. (\n#2197\n)\n\n\nRemove deprecated code to reflect the dropped Django versions. (\n#2200\n)\n\n\nBetter serializer errors for nested writes. (\n#2202\n, \n#2215\n)\n\n\nFix pagination and custom permissions incompatibility. (\n#2205\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2213\n)\n\n\nAdd missing translation markers for relational fields. (\n#2231\n)\n\n\nImprove field lookup behavior for dicts/mappings. (\n#2244\n, \n#2243\n)\n\n\nOptimized hyperlinked PK. (\n#2242\n)\n\n\n\n\n3.0.0\n\n\nDate\n: 1st December 2014\n\n\nFor full details see the \n3.0 release announcement\n.\n\n\n\n\nFor older release notes, \nplease see the version 2.x documentation\n.", + "title": "Release Notes" + }, + { + "location": "/topics/release-notes/#release-notes", + "text": "Release Early, Release Often \u2014 Eric S. Raymond, The Cathedral and the Bazaar .", + "title": "Release Notes" + }, + { + "location": "/topics/release-notes/#versioning", + "text": "Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes. Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy . You should read the release notes carefully before upgrading between medium point releases. Major version numbers (x.0.0) are reserved for substantial project milestones.", + "title": "Versioning" + }, + { + "location": "/topics/release-notes/#deprecation-policy", + "text": "REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy . The timeline for deprecation of a feature present in version 1.0 would work as follows: Version 1.1 would remain fully backwards compatible with 1.0, but would raise PendingDeprecationWarning warnings if you use the feature that are due to be deprecated. These warnings are silent by default , but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test , you'll be warned of any API changes you need to make. Version 1.2 would escalate these warnings to DeprecationWarning , which is loud by default. Version 1.3 would remove the deprecated bits of API entirely. Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.", + "title": "Deprecation policy" + }, + { + "location": "/topics/release-notes/#upgrading", + "text": "To upgrade Django REST framework to the latest version, use pip: pip install -U djangorestframework You can determine your currently installed version using pip show : pip show djangorestframework", + "title": "Upgrading" + }, + { + "location": "/topics/release-notes/#38x-series", + "text": "", + "title": "3.8.x series" + }, + { + "location": "/topics/release-notes/#382", + "text": "Date : 6th April 2018 Fix read_only + default unique_together validation. #5922 authtoken.views import coreapi from rest_framework.compat, not directly. #5921 Docs: Add missing argument 'detail' to Route #5920", + "title": "3.8.2" + }, + { + "location": "/topics/release-notes/#381", + "text": "Date : 4th April 2018 Use old url_name behavior in route decorators #5915 For list_route and detail_route maintain the old behavior of url_name ,\nbasing it on the url_path instead of the function name.", + "title": "3.8.1" + }, + { + "location": "/topics/release-notes/#380", + "text": "Date : 3rd April 2018 Breaking Change : Alter read_only plus default behaviour. #5886 read_only fields will now always be excluded from writable fields. Previously read_only fields with a default value would use the default for create and update operations. In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in\nthe view: def perform_create(self, serializer):\n serializer.save(owner=self.request.user) Alternatively you may override save() or create() or update() on the serialiser as appropriate. Correct allow_null behaviour when required=False #5888 Without an explicit default , allow_null implies a default of null for outgoing serialisation. Previously such\nfields were being skipped when read-only or otherwise not required. Possible backwards compatibility break if you were relying on such fields being excluded from the outgoing\nrepresentation. In order to restore the old behaviour you can override data to exclude the field when None . For example: @property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data Refactor dynamic route generation and improve viewset action introspectibility. #5705 ViewSet s have been provided with new attributes and methods that allow\nit to introspect its set of actions and the details of the current action. Merged list_route and detail_route into a single action decorator. Get all extra actions on a ViewSet with .get_extra_actions() . Extra actions now set the url_name and url_path on the decorated method. url_name is now based on the function name, instead of the url_path ,\n as the path is not always suitable (e.g., capturing arguments in the path). Enable action url reversing through .reverse_action() method (added in 3.7.4) Example reverse call: self.reverse_action(self.custom_action.url_name) Add detail initkwarg to indicate if the current action is operating on a\n collection or a single instance. Additional changes: Deprecated list_route & detail_route in favor of action decorator with detail boolean. Deprecated dynamic list/detail route variants in favor of DynamicRoute with detail boolean. Refactored the router's dynamic route generation. list_route and detail_route maintain the old behavior of url_name ,\n basing it on the url_path instead of the function name. Fix formatting of the 3.7.4 release note #5704 Docs: Update DRF Writable Nested Serializers references #5711 Docs: Fixed typo in auth URLs example. #5713 Improve composite field child errors #5655 Disable HTML inputs for dict/list fields #5702 Fix typo in HostNameVersioning doc #5709 Use rsplit to get module and classname for imports #5712 Formalize URLPatternsTestCase #5703 Add exception translation test #5700 Test staticfiles #5701 Add drf-yasg to documentation and schema 3rd party packages #5720 Remove unused compat._resolve_model() #5733 Drop compat workaround for unsupported Python 3.2 #5734 Prefer iter(dict) over iter(dict.keys()) #5736 Pass python_requires argument to setuptools #5739 Remove unused links from docs #5735 Prefer https protocol for links in docs when available #5729 Add HStoreField, postgres fields tests #5654 Always fully qualify ValidationError in docs #5751 Remove unreachable code from ManualSchema #5766 Allowed customising API documentation code samples #5752 Updated docs to use pip show #5757 Load 'static' instead of 'staticfiles' in templates #5773 Fixed a typo in fields docs #5783 Refer to \"NamespaceVersioning\" instead of \"NamespacedVersioning\" in the documentation #5754 ErrorDetail: add __eq__ / __ne__ and __repr__ #5787 Replace background-attachment: fixed in docs #5777 Make 404 & 403 responses consistent with exceptions.APIException output #5763 Small fix to API documentation: schemas #5796 Fix schema generation for PrimaryKeyRelatedField #5764 Represent serializer DictField as an Object in schema #5765 Added docs example reimplementing ObtainAuthToken #5802 Add schema to the ObtainAuthToken view #5676 Fix request formdata handling #5800 Fix authtoken views imports #5818 Update pytest, isort #5815 #5817 #5894 Fixed active timezone handling for non ISO8601 datetimes. #5833 Made TemplateHTMLRenderer render IntegerField inputs when value is 0 . #5834 Corrected endpoint in tutorial instructions #5835 Add Django Rest Framework Role Filters to Third party packages #5809 Use single copy of static assets. Update jQuery #5823 Changes ternary conditionals to be PEP308 compliant #5827 Added links to 'A Todo List API with React' and 'Blog API' tutorials #5837 Fix comment typo in ModelSerializer #5844 Add admin to installed apps to avoid test failures. #5870 Fixed schema for UUIDField in SimpleMetadata. #5872 Corrected docs on router include with namespaces. #5843 Test using model objects for dotted source default #5880 Allow traversing nullable related fields #5849 Added: Tutorial: Django REST with React (Django 2.0) #5891 Add LimitOffsetPagination.get_count to allow method override #5846 Don't show hidden fields in metadata #5854 Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. #5899 Added generic 500 and 400 JSON error handlers. #5904", + "title": "3.8.0" + }, + { + "location": "/topics/release-notes/#37x-series", + "text": "", + "title": "3.7.x series" + }, + { + "location": "/topics/release-notes/#377", + "text": "Date : 21st December 2017 Fix typo to include *.mo locale files to packaging. #5697 , #5695", + "title": "3.7.7" + }, + { + "location": "/topics/release-notes/#376", + "text": "Date : 21st December 2017 Add missing *.ico icon files to packaging.", + "title": "3.7.6" + }, + { + "location": "/topics/release-notes/#375", + "text": "Date : 21st December 2017 Add missing *.woff2 font files to packaging. #5692 Add missing *.mo locale files to packaging. #5695 , #5696", + "title": "3.7.5" + }, + { + "location": "/topics/release-notes/#374", + "text": "Date : 20th December 2017 Schema: Extract method for manual_fields processing #5633 Allows for easier customisation of manual_fields processing, for example\nto provide per-method manual fields. AutoSchema adds get_manual_fields ,\nas the intended override point, and a utility method update_fields , to\nhandle by-name field replacement from a list, which, in general, you are not\nexpected to override. Note: AutoSchema.__init__ now ensures manual_fields is a list.\nPreviously may have been stored internally as None . Remove ulrparse compatability shim; use six instead #5579 Drop compat wrapper for TimeDelta.total_seconds() #5577 Clean up all whitespace throughout project #5578 Compat cleanup #5581 Add pygments CSS block in browsable API views #5584 #5587 Remove set_rollback() from compat #5591 Fix request body/POST access #5590 Rename test to reference correct issue #5610 Documentation Fixes #5611 #5612 Remove references to unsupported Django versions in docs and code #5602 Test Serializer exclude for declared fields #5599 Fixed schema generation for filter backends #5613 Minor cleanup for ModelSerializer tests #5598 Reimplement request attribute access w/ __getattr__ #5617 Fixed SchemaJSRenderer renders invalid Javascript #5607 Make Django 2.0 support official/explicit #5619 Perform type check on passed request argument #5618 Fix AttributeError hiding on request authenticators #5600 Update test requirements #5626 Docs: Serializer._declared_fields enable modifying fields on a serializer #5629 Fix packaging #5624 Fix readme rendering for PyPI, add readme build to CI #5625 Update tutorial #5622 Non-required fields with allow_null=True should not imply a default value #5639 Docs: Add allow_null serialization output note #5641 Update to use the Django 2.0 release in tox.ini #5645 Fix Serializer.data for Browsable API rendering when provided invalid data #5646 Docs: Note AutoSchema limitations on bare APIView #5649 Add .basename and .reverse_action() to ViewSet #5648 Docs: Fix typos in serializers documentation #5652 Fix override_settings compat #5668 Add DEFAULT_SCHEMA_CLASS setting #5658 Add docs note re generated BooleanField being required=False #5665 Add 'dist' build #5656 Fix typo in docstring #5678 Docs: Add UNAUTHENTICATED_USER = None note #5679 Update OPTIONS example from \u201cDocumenting Your API\u201d #5680 Docs: Add note on object permissions for FBVs #5681 Docs: Add example to to_representation docs #5682 Add link to Classy DRF in docs #5683 Document ViewSet.action #5685 Fix schema docs typo #5687 Fix URL pattern parsing in schema generation #5689 Add example using source=\u2018*\u2019 to custom field docs. #5688 Fix format_suffix_patterns behavior with Django 2 path() routes #5691", + "title": "3.7.4" + }, + { + "location": "/topics/release-notes/#373", + "text": "Date : 6th November 2017 Fix AppRegistryNotReady error from contrib.auth view imports #5567", + "title": "3.7.3" + }, + { + "location": "/topics/release-notes/#372", + "text": "Date : 6th November 2017 Fixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. #5510 Add missing import for TextLexer. #5512 Adding examples and documentation for caching #5514 Include date and date-time format for schema generation #5511 Use triple backticks for markdown code blocks #5513 Interactive docs - make bottom sidebar items sticky #5516 Clarify pagination system check #5524 Stop JSONBoundField mangling invalid JSON #5527 Have JSONField render as textarea in Browsable API #5530 Schema: Exclude OPTIONS/HEAD for ViewSet actions #5532 Fix ordering for dotted sources #5533 Fix: Fields with allow_null=True should imply a default serialization value #5518 Ensure Location header is strictly a 'str', not subclass. #5544 Add import to example in api-guide/parsers #5547 Catch OverflowError for \"out of range\" datetimes #5546 Add djangorestframework-rapidjson to third party packages #5549 Increase test coverage for drf_create_token command #5550 Add trove classifier for Python 3.6 support. #5555 Add pip cache support to the Travis CI configuration #5556 Rename [ wheel ] section to [ bdist_wheel ] as the former is legacy #5557 Fix invalid escape sequence deprecation warnings #5560 Add interactive docs error template #5548 Add rounding parameter to DecimalField #5562 Fix all BytesWarning caught during tests #5561 Use dict and set literals instead of calls to dict() and set() #5559 Change ImageField validation pattern, use validators from DjangoImageField #5539 Fix processing unicode symbols in query_string by Python 2 #5552", + "title": "3.7.2" + }, + { + "location": "/topics/release-notes/#371", + "text": "Date : 16th October 2017 Fix Interactive documentation always uses false for boolean fields in requests #5492 Improve compatibility with Django 2.0 alpha. #5500 #5503 Improved handling of schema naming collisions #5486 Added additional docs and tests around providing a default value for dotted source fields #5489", + "title": "3.7.1" + }, + { + "location": "/topics/release-notes/#370", + "text": "Date : 6th October 2017 Fix DjangoModelPermissions to ensure user authentication before calling the view's get_queryset() method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. #5376 Deprecated exclude_from_schema on APIView and api_view decorator. Set schema = None or @schema(None) as appropriate. #5422 Timezone-aware DateTimeField s now respect active or default timezone during serialization, instead of always using UTC. #5435 Resolves inconsistency whereby instances were serialised with supplied datetime for create but UTC for retrieve . #3732 Possible backwards compatibility break if you were relying on datetime strings being UTC. Have client interpret datetimes or set default or active timezone (docs) to UTC if needed. Removed DjangoFilterBackend inline with deprecation policy. Use django_filters.rest_framework.FilterSet and/or django_filters.rest_framework.DjangoFilterBackend instead. #5273 Don't strip microseconds from time when encoding. Makes consistent with datetime .\n BC Change : Previously only milliseconds were encoded. #5440 Added STRICT_JSON setting (default True ) to raise exception for the extended float values ( nan , inf , -inf ) accepted by Python's json module.\n BC Change : Previously these values would converted to corresponding strings. Set STRICT_JSON to False to restore the previous behaviour. #5265 Add support for page_size parameter in CursorPaginator class #5250 Make DEFAULT_PAGINATION_CLASS None by default.\n BC Change : If your were just setting PAGE_SIZE to enable pagination you will need to add DEFAULT_PAGINATION_CLASS .\n The previous default was rest_framework.pagination.PageNumberPagination . There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. #5170 Catch APIException from get_serializer_fields in schema generation. #5443 Allow custom authentication and permission classes when using include_docs_urls #5448 Defer translated string evaluation on validators. #5452 Added default value for 'detail' param into 'ValidationError' exception #5342 Adjust schema get_filter_fields rules to match framework #5454 Updated test matrix to add Django 2.0 and drop Django 1.8 & 1.9\n BC Change : This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. #5457 Fixed a deprecation warning in serializers.ModelField #5058 Added a more explicit error message when get_queryset returned None #5348 Fix docs for Response data description #5361 Fix pycache /.pyc excludes when packaging #5373 Fix default value handling for dotted sources #5375 Ensure content_type is set when passing empty body to RequestFactory #5351 Fix ErrorDetail Documentation #5380 Allow optional content in the generic content form #5372 Updated supported values for the NullBooleanField #5387 Fix ModelSerializer custom named fields with source on model #5388 Fixed the MultipleFieldLookupMixin documentation example to properly check for object level permission #5398 Update get_object() example in permissions.md #5401 Fix authtoken management command #5415 Fix schema generation markdown #5421 Allow ChoiceField.choices to be set dynamically #5426 Add the project layout to the quickstart #5434 Reuse 'apply_markdown' function in 'render_markdown' templatetag #5469 Added links to drf-openapi package in docs #5470 Added docstrings code highlighting with pygments #5462 Fixed documentation rendering for views named data #5472 Docs: Clarified 'to_internal_value()' validation behavior #5466 Fix missing six.text_type() call on APIException. str #5476 Document documentation.py #5478 Fix naming collisions in Schema Generation #5464 Call Django's authenticate function with the request object #5295 Update coreapi JS to 0.1.1 #5479 Have is_list_view recognise RetrieveModel\u2026 views #5480 Remove Django 1.8 & 1.9 compatibility code #5481 Remove deprecated schema code from DefaultRouter #5482 Refactor schema generation to allow per-view customisation.\n BC Change : SchemaGenerator.get_serializer_fields has been refactored as AutoSchema.get_serializer_fields and drops the view argument [#5354][gh5354]", + "title": "3.7.0" + }, + { + "location": "/topics/release-notes/#36x-series", + "text": "", + "title": "3.6.x series" + }, + { + "location": "/topics/release-notes/#364", + "text": "Date : 21st August 2017 Ignore any invalidly formed query parameters for OrderingFilter. #5131 Improve memory footprint when reading large JSON requests. #5147 Fix schema generation for pagination. #5161 Fix exception when HTML_CUTOFF is set to None . #5174 Fix browsable API not supporting multipart/form-data correctly. #5176 Fixed test_hyperlinked_related_lookup_url_encoded_exists . #5179 Make sure max_length is in FileField kwargs. #5186 Fix list_route & detail_route with kwargs contains curly bracket in url_path #5187 Add Django manage command to create a DRF user Token. #5188 Ensure API documentation templates do not check for user authentication #5162 Fix special case where OneToOneField is also primary key. #5192 Added aria-label and a new region for accessibility purposes in base.html #5196 Quote nested API parameters in api.js. #5214 Set ViewSet args/kwargs/request before dispatch. #5229 Added unicode support to SlugField. #5231 Fix HiddenField appears in Raw Data form initial content. #5259 Raise validation error on invalid timezone parsing. #5261 Fix SearchFilter to-many behavior/performance. #5264 Simplified chained comparisons and minor code fixes. #5276 RemoteUserAuthentication, docs, and tests. #5306 Revert \"Cached the field's root and context property\" #5313 Fix introspection of list field in schema. #5326 Fix interactive docs for multiple nested and extra methods. #5334 Fix/remove undefined template var \"schema\" #5346", + "title": "3.6.4" + }, + { + "location": "/topics/release-notes/#363", + "text": "Date : 12th May 2017 Raise 404 if a URL lookup results in ValidationError. ( #5126 ) Honor http_method_names on class based view, when generating API schemas. ( #5085 ) Allow overridden get_limit in LimitOffsetPagination to return all records. ( #4437 ) Fix partial update for the ListSerializer. ( #4222 ) Render JSONField control correctly in browsable API. ( #4999 , #5042 ) Raise validation errors for invalid datetime in given timezone. ( #4987 ) Support restricting doc & schema shortcuts to a subset of urls. ( #4979 ) Resolve SchemaGenerator error with paginators that have no page_size attribute. ( #5086 , #3692 ) Resolve HyperlinkedRelatedField exception on string with %20 instead of space. ( #4748 , #5078 ) Customizable schema generator classes. ( #5082 ) Update existing vary headers in response instead of overwriting them. ( #5047 ) Support passing .as_view() to view instance. ( #5053 ) Use correct exception handler when settings overridden on a view. ( #5055 , #5054 ) Update Boolean field to support 'yes' and 'no' values. ( #5038 ) Fix unique validator for ChoiceField. ( #5004 , #5026 , #5028 ) JavaScript cleanups in API Docs. ( #5001 ) Include URL path regexs in API schemas where valid. ( #5014 ) Correctly set scheme in coreapi TokenAuthentication. ( #5000 , #4994 ) HEAD requests on ViewSets should not return 405. ( #4705 , #4973 , #4864 ) Support usage of 'source' in extra_kwargs . ( #4688 ) Fix invalid content type for schema.js ( #4968 ) Fix DjangoFilterBackend inheritance issues. ( #5089 , #5117 )", + "title": "3.6.3" + }, + { + "location": "/topics/release-notes/#362", + "text": "Date : 10th March 2017 Support for Safari & IE in API docs. ( #4959 , #4961 ) Add missing mark_safe in API docs template tags. ( #4952 , #4953 ) Add missing glyphicon fonts. ( #4950 , #4951 ) Fix One-to-one fields in API docs. ( #4955 , #4956 ) Test clean ups. ( #4949 )", + "title": "3.6.2" + }, + { + "location": "/topics/release-notes/#361", + "text": "Date : 9th March 2017 Ensure markdown dependency is optional. ( #4947 )", + "title": "3.6.1" + }, + { + "location": "/topics/release-notes/#360", + "text": "Date : 9th March 2017 See the release announcement .", + "title": "3.6.0" + }, + { + "location": "/topics/release-notes/#35x-series", + "text": "", + "title": "3.5.x series" + }, + { + "location": "/topics/release-notes/#354", + "text": "Date : 10th February 2017 Add max_length and min_length arguments for ListField. ( #4877 ) Add per-view custom exception handler support. ( #4753 ) Support disabling of declared fields on serializer subclasses. ( #4764 ) Support custom view names on @list_route and @detail_route endpoints. ( #4821 ) Correct labels for fields in login template when custom user model is used. ( #4841 ) Whitespace fixes for descriptions generated from docstrings. ( #4759 , #4869 , #4870 ) Better error reporting when schemas are returned by views without a schema renderer. ( #4790 ) Fix for returned response of PUT requests when prefetch_related is used. ( #4661 , #4668 ) Fix for breadcrumb view names. ( #4750 ) Fix for RequestsClient ensuring fully qualified URLs. ( #4678 ) Fix for incorrect behavior of writable-nested fields check in some cases. ( #4634 , #4669 ) Resolve Django deprecation warnings. ( #4712 ) Various cleanup of test cases.", + "title": "3.5.4" + }, + { + "location": "/topics/release-notes/#353", + "text": "Date : 7th November 2016 Don't raise incorrect FilterSet deprecation warnings. ( #4660 , #4643 , #4644 ) Schema generation should not raise 404 when a view permission class does. ( #4645 , #4646 ) Add autofocus support for input controls. ( #4650 )", + "title": "3.5.3" + }, + { + "location": "/topics/release-notes/#352", + "text": "Date : 1st November 2016 Restore exception tracebacks in Python 2.7. ( #4631 , #4638 ) Properly display dicts in the admin console. ( #4532 , #4636 ) Fix is_simple_callable with variable args, kwargs. ( #4622 , #4602 ) Support 'on'/'off' literals with BooleanField. ( #4640 , #4624 ) Enable cursor pagination of value querysets. ( #4569 ) Fix support of get_full_details() for Throttled exceptions. ( #4627 ) Fix FilterSet proxy. ( #4620 ) Make serializer fields import explicit. ( #4628 ) Drop redundant requests adapter. ( #4639 )", + "title": "3.5.2" + }, + { + "location": "/topics/release-notes/#351", + "text": "Date : 21st October 2016 Make rest_framework/compat.py imports. ( #4612 , #4608 , #4601 ) Fix bug in schema base path generation. ( #4611 , #4605 ) Fix broken case of ListSerializer with single item. ( #4609 , #4606 ) Remove bare raise for Python 3.5 compat. ( #4600 )", + "title": "3.5.1" + }, + { + "location": "/topics/release-notes/#350", + "text": "Date : 20th October 2016", + "title": "3.5.0" + }, + { + "location": "/topics/release-notes/#34x-series", + "text": "", + "title": "3.4.x series" + }, + { + "location": "/topics/release-notes/#347", + "text": "Date : 21st September 2016 Fallback behavior for request parsing when request.POST already accessed. ( #3951 , #4500 ) Fix regression of RegexField . ( #4489 , #4490 , #2617 ) Missing comma in admin.html causing CSRF error. ( #4472 , #4473 ) Fix response rendering with empty context. ( #4495 ) Fix indentation regression in API listing. ( #4493 ) Fixed an issue where the incorrect value is set to ResolverMatch.func_name of api_view decorated view. ( #4465 , #4462 ) Fix APIClient.get() when path contains unicode arguments ( #4458 )", + "title": "3.4.7" + }, + { + "location": "/topics/release-notes/#346", + "text": "Date : 23rd August 2016 Fix malformed Javascript in browsable API. ( #4435 ) Skip HiddenField from Schema fields. ( #4425 , #4429 ) Improve Create to show the original exception traceback. ( #3508 ) Fix AdminRenderer display of PK only related fields. ( #4419 , #4423 )", + "title": "3.4.6" + }, + { + "location": "/topics/release-notes/#345", + "text": "Date : 19th August 2016 Improve debug error handling. ( #4416 , #4409 ) Allow custom CSRF_HEADER_NAME setting. ( #4415 , #4410 ) Include .action attribute on viewsets when generating schemas. ( #4408 , #4398 ) Do not include request.FILES items in request.POST. ( #4407 ) Fix rendering of checkbox multiple. ( #4403 ) Fix docstring of Field.get_default. ( #4404 ) Replace utf8 character with its ascii counterpart in README. ( #4412 )", + "title": "3.4.5" + }, + { + "location": "/topics/release-notes/#344", + "text": "Date : 12th August 2016 Ensure views are fully initialized when generating schemas. ( #4373 , #4382 , #4383 , #4279 , #4278 ) Add form field descriptions to schemas. ( #4387 ) Fix category generation for schema endpoints. ( #4391 , #4394 , #4390 , #4386 , #4376 , #4329 ) Don't strip empty query params when paginating. ( #4392 , #4393 , #4260 ) Do not re-run query for empty results with LimitOffsetPagination. ( #4201 , #4388 ) Stricter type validation for CharField. ( #4380 , #3394 ) RelatedField.choices should preserve non-string values. ( #4111 , #4379 , #3365 ) Test case for rendering checkboxes in vertical form style. ( #4378 , #3868 , #3868 ) Show error traceback HTML in browsable API ( #4042 , #4172 ) Fix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. #4370 Allow max_digits=None on DecimalField. ( #4377 , #4372 ) Limit queryset when rendering relational choices. ( #4375 , #4122 , #3329 , #3330 , #3877 ) Resolve form display with ChoiceField, MultipleChoiceField and non-string choices. ( #4374 , #4119 , #4121 , #4137 , #4120 ) Fix call to TemplateHTMLRenderer.resolve_context() fallback method. ( #4371 )", + "title": "3.4.4" + }, + { + "location": "/topics/release-notes/#343", + "text": "Date : 5th August 2016 Include fallback for users of older TemplateHTMLRenderer internal API. ( #4361 )", + "title": "3.4.3" + }, + { + "location": "/topics/release-notes/#342", + "text": "Date : 5th August 2016 Include kwargs passed to 'as_view' when generating schemas. ( #4359 , #4330 , #4331 ) Access request.user.is_authenticated as property not method, under Django 1.10+ ( #4358 , #4354 ) Filter HEAD out from schemas. ( #4357 ) extra_kwargs takes precedence over uniqueness kwargs. ( #4198 , #4199 , #4349 ) Correct descriptions when tabs are used in code indentation. ( #4345 , #4347 )* Change template context generation in TemplateHTMLRenderer. ( #4236 ) Serializer defaults should not be included in partial updates. ( #4346 , #3565 ) Consistent behavior & descriptive error from FileUploadParser when filename not included. ( #4340 , #3610 , #4292 , #4296 ) DecimalField quantizes incoming digitals. ( #4339 , #4318 ) Handle non-string input for IP fields. ( #4335 , #4336 , #4338 ) Fix leading slash handling when Schema generation includes a root URL. ( #4332 ) Test cases for DictField with allow_null options. ( #4348 ) Update tests from Django 1.10 beta to Django 1.10. ( #4344 )", + "title": "3.4.2" + }, + { + "location": "/topics/release-notes/#341", + "text": "Date : 28th July 2016 Added root_renderers argument to DefaultRouter . ( #4323 , #4268 ) Added url and schema_url arguments. ( #4321 , #4308 , #4305 ) Unique together checks should apply to read-only fields which have a default. ( #4316 , #4294 ) Set view.format_kwarg in schema generator. ( #4293 , #4315 ) Fix schema generator for views with pagination_class = None . ( #4314 , #4289 ) Fix schema generator for views with no get_serializer_class . ( #4265 , #4285 ) Fixes for media type parameters in Accept and Content-Type headers. ( #4287 , #4313 , #4281 ) Use verbose_name instead of object_name in error messages. ( #4299 ) Minor version update to Twitter Bootstrap. ( #4307 ) SearchFilter raises error when using with related field. ( #4302 , #4303 , #4298 ) Adding support for RFC 4918 status codes. ( #4291 ) Add LICENSE.md to the built wheel. ( #4270 ) Serializing \"complex\" field returns None instead of the value since 3.4 ( #4272 , #4273 , #4288 )", + "title": "3.4.1" + }, + { + "location": "/topics/release-notes/#340", + "text": "Date : 14th July 2016 Don't strip microseconds in JSON output. ( #4256 ) Two slightly different iso 8601 datetime serialization. ( #4255 ) Resolve incorrect inclusion of media type parameters. ( #4254 ) Response Content-Type potentially malformed. ( #4253 ) Fix setup.py error on some platforms. ( #4246 ) Move alternate formats in coreapi into separate packages. ( #4244 ) Add localize keyword argument to DecimalField . ( #4233 ) Fix issues with routers for custom list-route and detail-routes. ( #4229 ) Namespace versioning with nested namespaces. ( #4219 ) Robust uniqueness checks. ( #4217 ) Minor refactoring of must_call_distinct . ( #4215 ) Overridable offset cutoff in CursorPagination. ( #4212 ) Pass through strings as-in with date/time fields. ( #4196 ) Add test confirming that required=False is valid on a relational field. ( #4195 ) In LimitOffsetPagination limit=0 should revert to default limit. ( #4194 ) Exclude read_only=True fields from unique_together validation & add docs. ( #4192 ) Handle bytestrings in JSON. ( #4191 ) JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ( #4187 ) JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ( #4185 ) More robust form rendering in the browsable API. ( #4181 ) Empty cases of .validated_data and .errors as lists not dicts for ListSerializer. ( #4180 ) Schemas & client libraries. ( #4179 ) Removed AUTH_USER_MODEL compat property. ( #4176 ) Clean up existing deprecation warnings. ( #4166 ) Django 1.10 support. ( #4158 ) Updated jQuery version to 1.12.4. ( #4157 ) More robust default behavior on OrderingFilter. ( #4156 ) description.py codes and tests removal. ( #4153 ) Wrap guardian.VERSION in tuple. ( #4149 ) Refine validator for fields with kwargs. ( #4146 ) Fix None values representation in childs of ListField, DictField. ( #4118 ) Resolve TimeField representation for midnight value. ( #4107 ) Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. ( #4106 ) TimeField render returns None instead of 00:00:00. ( #4105 ) Fix incorrectly named zh-hans and zh-hant locale path. ( #4103 ) Prevent raising exception when limit is 0. ( #4098 ) TokenAuthentication: Allow custom keyword in the header. ( #4097 ) Handle incorrectly padded HTTP basic auth header. ( #4090 ) LimitOffset pagination crashes Browseable API when limit=0. ( #4079 ) Fixed DecimalField arbitrary precision support. ( #4075 ) Added support for custom CSRF cookie names. ( #4049 ) Fix regression introduced by #4035. ( #4041 ) No auth view failing permission should raise 403. ( #4040 ) Fix string_types / text_types confusion. ( #4025 ) Do not list related field choices in OPTIONS requests. ( #4021 ) Fix typo. ( #4008 ) Reorder initializing the view. ( #4006 ) Type error in DjangoObjectPermissionsFilter on Python 3.4. ( #4005 ) Fixed use of deprecated Query.aggregates. ( #4003 ) Fix blank lines around docstrings. ( #4002 ) Fixed admin pagination when limit is 0. ( #3990 ) OrderingFilter adjustments. ( #3983 ) Non-required serializer related fields. ( #3976 ) Using safer calling way of \"@api_view\" in tutorial. ( #3971 ) ListSerializer doesn't handle unique_together constraints. ( #3970 ) Add missing migration file. ( #3968 ) OrderingFilter should call get_serializer_class() to determine default fields. ( #3964 ) Remove old Django checks from tests and compat. ( #3953 ) Support callable as the value of initial for any serializer.Field . ( #3943 ) Prevented unnecessary distinct() call in SearchFilter. ( #3938 ) Fix None UUID ForeignKey serialization. ( #3936 ) Drop EOL Django 1.7. ( #3933 ) Add missing space in serializer error message. ( #3926 ) Fixed _force_text_recursive typo. ( #3908 ) Attempt to address Django 2.0 deprecate warnings related to field.rel . ( #3906 ) Fix parsing multipart data using a nested serializer with list. ( #3820 ) Resolving APIs URL to different namespaces. ( #3816 ) Do not HTML-escape help_text in Browsable API forms. ( #3812 ) OPTIONS fetches and shows all possible foreign keys in choices field. ( #3751 ) Django 1.9 deprecation warnings ( #3729 ) Test case for #3598 ( #3710 ) Adding support for multiple values for search filter. ( #3541 ) Use get_serializer_class in ordering filter. ( #3487 ) Serializers with many=True should return empty list rather than empty dict. ( #3476 ) LimitOffsetPagination limit=0 fix. ( #3444 ) Enable Validators to defer string evaluation and handle new string format. ( #3438 ) Unique validator is executed and breaks if field is invalid. ( #3381 ) Do not ignore overridden View.get_view_name() in breadcrumbs. ( #3273 ) Retry form rendering when rendering with serializer fails. ( #3164 ) Unique constraint prevents nested serializers from updating. ( #2996 ) Uniqueness validators should not be run for excluded (read_only) fields. ( #2848 ) UniqueValidator raises exception for nested objects. ( #2403 ) lookup_type is deprecated in favor of lookup_expr . ( #4259 )", + "title": "3.4.0" + }, + { + "location": "/topics/release-notes/#33x-series", + "text": "", + "title": "3.3.x series" + }, + { + "location": "/topics/release-notes/#333", + "text": "Date : 14th March 2016 . Remove version string from templates. Thanks to @blag for the report and fixes. ( #3878 , #3913 , #3912 ) Fixes vertical html layout for BooleanField . Thanks to Mikalai Radchuk for the fix. ( #3910 ) Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. ( #3903 ) Internationalization for authtoken. Thanks to Michael Nacharov for the fix. ( #3887 , #3968 ) Fix Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. ( #3860 , #3858 ) Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. ( #3604 , #3842 ) QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. ( #3833 ) Add an explicit on_delete on the models. Thanks to Mads Jensen for the fix. ( #3832 ) Fix DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. ( #3819 ) Fixed TimeField not handling string times. Thanks to Areski Belaid for the fix. ( #3809 ) Avoid updates of Meta.extra_kwargs . Thanks to Kevin Massey for the report and fix. ( #3805 , #3804 ) Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. ( #3801 ) Document how to avoid CSRF and missing button issues with django-crispy-forms . Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. ( #3787 , #3636 , #3637 ) Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. ( #3786 , #3815 ) Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. ( #3785 ) Fix Min/MaxValueValidator transfer from a model's DecimalField . Thanks to Kevin Brown for the fix. ( #3774 ) Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. ( #3769 ) Fix AutoFilterSet to inherit from default_filter_set . Thanks to Tom Linford for the fix. ( #3753 ) Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. ( #3739 ) DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. ( #3731 , #3726 ) Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. ( #3715 ) Add missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. ( #3703 ) Refactored _get_reverse_relationships() to use correct to_field . Thanks to Benjamin Phillips for the fix. ( #3696 ) Document the use of get_queryset for RelatedField . Thanks to Ryan Hiebert for the fix. ( #3605 ) Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix ( #3962 )", + "title": "3.3.3" + }, + { + "location": "/topics/release-notes/#332", + "text": "Date : 14th December 2015 . ListField enforces input is a list. ( #3513 ) Fix regression hiding raw data form. ( #3600 , #3578 ) Fix Python 3.5 compatibility. ( #3534 , #3626 ) Allow setting a custom Django Paginator in pagination.PageNumberPagination . ( #3631 , #3684 ) Fix relational fields without to_fields attribute. ( #3635 , #3634 ) Fix template.render deprecation warnings for Django 1.9. ( #3654 ) Sort response headers in browsable API renderer. ( #3655 ) Use related_objects api for Django 1.9+. ( #3656 , #3252 ) Add confirm modal when deleting. ( #3228 , #3662 ) Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. ( #3668 ) Make DRF compatible with multi template engine in Django 1.8. ( #3672 ) Update NestedBoundField to also handle empty string when rendering its form. ( #3677 ) Fix UUID validation to properly catch invalid input types. ( #3687 , #3679 ) Fix caching issues. ( #3628 , #3701 ) Fix Admin and API browser for views without a filter_class. ( #3705 , #3596 , #3597 ) Add app_name to rest_framework.urls. ( #3714 ) Improve authtoken's views to support url versioning. ( #3718 , #3723 )", + "title": "3.3.2" + }, + { + "location": "/topics/release-notes/#331", + "text": "Date : 4th November 2015 . Resolve parsing bug when accessing request.POST ( #3592 ) Correctly deal with to_field referring to primary key. ( #3593 ) Allow filter HTML to render when no filter_class is defined. ( #3560 ) Fix admin rendering issues. ( #3564 , #3556 ) Fix issue with DecimalValidator. ( #3568 )", + "title": "3.3.1" + }, + { + "location": "/topics/release-notes/#330", + "text": "Date : 28th October 2015 . HTML controls for filters. ( #3315 ) Forms API. ( #3475 ) AJAX browsable API. ( #3410 ) Added JSONField. ( #3454 ) Correctly map to_field when creating ModelSerializer relational fields. ( #3526 ) Include keyword arguments when mapping FilePathField to a serializer field. ( #3536 ) Map appropriate model error_messages on ModelSerializer uniqueness constraints. ( #3435 ) Include max_length constraint for ModelSerializer fields mapped from TextField. ( #3509 ) Added support for Django 1.9. ( #3450 , #3525 ) Removed support for Django 1.5 & 1.6. ( #3421 , #3429 ) Removed 'south' migrations. ( #3495 )", + "title": "3.3.0" + }, + { + "location": "/topics/release-notes/#32x-series", + "text": "", + "title": "3.2.x series" + }, + { + "location": "/topics/release-notes/#325", + "text": "Date : 27th October 2015 . Escape username in optional logout tag. ( #3550 )", + "title": "3.2.5" + }, + { + "location": "/topics/release-notes/#324", + "text": "Date : 21th September 2015 . Don't error on missing ViewSet.search_fields attribute. ( #3324 , #3323 ) Fix allow_empty not working on serializers with many=True . ( #3361 , #3364 ) Let DurationField accepts integers. ( #3359 ) Multi-level dictionaries not supported in multipart requests. ( #3314 ) Fix ListField truncation on HTTP PATCH ( #3415 , #2761 )", + "title": "3.2.4" + }, + { + "location": "/topics/release-notes/#323", + "text": "Date : 24th August 2015 . Added html_cutoff and html_cutoff_text for limiting select dropdowns. ( #3313 ) Added regex style to SearchFilter . ( #3316 ) Resolve issues with setting blank HTML fields. ( #3318 ) ( #3321 ) Correctly display existing 'select multiple' values in browsable API forms. ( #3290 ) Resolve duplicated validation message for IPAddressField . ([#3249[gh3249]) ( #3250 ) Fix to ensure admin renderer continues to work when pagination is disabled. ( #3275 ) Resolve error with LimitOffsetPagination when count=0, offset=0. ( #3303 )", + "title": "3.2.3" + }, + { + "location": "/topics/release-notes/#322", + "text": "Date : 13th August 2015 . Add display_value() method for use when displaying relational field select inputs. ( #3254 ) Fix issue with BooleanField checkboxes incorrectly displaying as checked. ( #3258 ) Ensure empty checkboxes properly set BooleanField to False in all cases. ( #2776 ) Allow WSGIRequest.FILES property without raising incorrect deprecated error. ( #3261 ) Resolve issue with rendering nested serializers in forms. ( #3260 ) Raise an error if user accidentally pass a serializer instance to a response, rather than data. ( #3241 )", + "title": "3.2.2" + }, + { + "location": "/topics/release-notes/#321", + "text": "Date : 7th August 2015 . Fix for relational select widgets rendering without any choices. ( #3237 ) Fix for 1 , 0 rendering as true , false in the admin interface. #3227 ) Fix for ListFields with single value in HTML form input. ( #3238 ) Allow request.FILES for compat with Django's HTTPRequest class. ( #3239 )", + "title": "3.2.1" + }, + { + "location": "/topics/release-notes/#320", + "text": "Date : 6th August 2015 . Add AdminRenderer . ( #2926 ) Add FilePathField . ( #1854 ) Add allow_empty to ListField . ( #2250 ) Support django-guardian 1.3. ( #3165 ) Support grouped choices. ( #3225 ) Support error forms in browsable API. ( #3024 ) Allow permission classes to customize the error message. ( #2539 ) Support source= on hyperlinked fields. ( #2690 ) ListField(allow_null=True) now allows null as the list value, not null items in the list. ( #2766 ) ManyToMany() maps to allow_empty=False , ManyToMany(blank=True) maps to allow_empty=True . ( #2804 ) Support custom serialization styles for primary key fields. ( #2789 ) OPTIONS requests support nested representations. ( #2915 ) Set view.action == \"metadata\" for viewsets with OPTIONS requests. ( #3115 ) Support allow_blank on UUIDField . ([#3130][gh#3130]) Do not display view docstrings with 401 or 403 response codes. ( #3216 ) Resolve Django 1.8 deprecation warnings. ( #2886 ) Fix for DecimalField validation. ( #3139 ) Fix behavior of allow_blank=False when used with trim_whitespace=True . ( #2712 ) Fix issue with some field combinations incorrectly mapping to an invalid allow_blank argument. ( #3011 ) Fix for output representations with prefetches and modified querysets. ( #2704 , #2727 ) Fix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920) gh2920 . Fix UnicodeDecodeError when invalid characters included in header with TokenAuthentication . ( #2928 ) Fix transaction rollbacks with @non_atomic_requests decorator. ( #3016 ) Fix duplicate results issue with Oracle databases using SearchFilter . ( #2935 ) Fix checkbox alignment and rendering in browsable API forms. ( #2783 ) Fix for unsaved file objects which should use \"url\": null in the representation. ( #2759 ) Fix field value rendering in browsable API. ( #2416 ) Fix HStoreField to include allow_blank=True in DictField mapping. ( #2659 ) Numerous other cleanups, improvements to error messaging, private API & minor fixes.", + "title": "3.2.0" + }, + { + "location": "/topics/release-notes/#31x-series", + "text": "", + "title": "3.1.x series" + }, + { + "location": "/topics/release-notes/#313", + "text": "Date : 4th June 2015 . Add DurationField . ( #2481 , #2989 ) Add format argument to UUIDField . ( #2788 , #3000 ) MultipleChoiceField empties incorrectly on a partial update using multipart/form-data ( #2993 , #2894 ) Fix a bug in options related to read-only RelatedField . ( #2981 , #2811 ) Fix nested serializers with unique_together relations. ( #2975 ) Allow unexpected values for ChoiceField / MultipleChoiceField representations. ( #2839 , #2940 ) Rollback the transaction on error if ATOMIC_REQUESTS is set. ( #2887 , #2034 ) Set the action on a view when override_method regardless of its None-ness. ( #2933 ) DecimalField accepts 2E+2 as 200 and validates decimal place correctly. ( #2948 , #2947 ) Support basic authentication with custom UserModel that change username . ( #2952 ) IPAddressField improvements. ( #2747 , #2618 , #3008 ) Improve DecimalField for easier subclassing. ( #2695 )", + "title": "3.1.3" + }, + { + "location": "/topics/release-notes/#312", + "text": "Date : 13rd May 2015 . DateField.to_representation can handle str and empty values. ( #2656 , #2687 , #2869 ) Use default reason phrases from HTTP standard. ( #2764 , #2763 ) Raise error when ModelSerializer used with abstract model. ( #2757 , #2630 ) Handle reversal of non-API view_name in HyperLinkedRelatedField ( #2724 , #2711 ) Don't require pk strictly for related fields. ( #2745 , #2754 ) Metadata detects null boolean field type. ( #2762 ) Proper handling of depth in nested serializers. ( #2798 ) Display viewset without paginator. ( #2807 ) Don't check for deprecated .model attribute in permissions ( #2818 ) Restrict integer field to integers and strings. ( #2835 , #2836 ) Improve IntegerField to use compiled decimal regex. ( #2853 ) Prevent empty queryset to raise AssertionError. ( #2862 ) DjangoModelPermissions rely on get_queryset . ( #2863 ) Check AcceptHeaderVersioning with content negotiation in place. ( #2868 ) Allow DjangoObjectPermissions to use views that define get_queryset . ( #2905 )", + "title": "3.1.2" + }, + { + "location": "/topics/release-notes/#311", + "text": "Date : 23rd March 2015 . Security fix : Escape tab switching cookie name in browsable API. Display input forms in browsable API if serializer_class is used, even when get_serializer method does not exist on the view. ( #2743 ) Use a password input for the AuthTokenSerializer. ( #2741 ) Fix missing anchor closing tag after next button. ( #2691 ) Fix lookup_url_kwarg handling in viewsets. ( #2685 , #2591 ) Fix problem with importing rest_framework.views in apps.py ( #2678 ) LimitOffsetPagination raises TypeError if PAGE_SIZE not set ( #2667 , #2700 ) German translation for min_value field error message references max_value . ( #2645 ) Remove MergeDict . ( #2640 ) Support serializing unsaved models with related fields. ( #2637 , #2641 ) Allow blank/null on radio.html choices. ( #2631 )", + "title": "3.1.1" + }, + { + "location": "/topics/release-notes/#310", + "text": "Date : 5th March 2015 . For full details see the 3.1 release announcement .", + "title": "3.1.0" + }, + { + "location": "/topics/release-notes/#30x-series", + "text": "", + "title": "3.0.x series" + }, + { + "location": "/topics/release-notes/#305", + "text": "Date : 10th February 2015 . Fix a bug where _closable_objects breaks pickling. ( #1850 , #2492 ) Allow non-standard User models with Throttling . ( #2524 ) Support custom User.db_table in TokenAuthentication migration. ( #2479 ) Fix misleading AttributeError tracebacks on Request objects. ( #2530 , #2108 ) ManyRelatedField.get_value clearing field on partial update. ( #2475 ) Removed '.model' shortcut from code. ( #2486 ) Fix detail_route and list_route mutable argument. ( #2518 ) Prefetching the user object when getting the token in TokenAuthentication . ( #2519 )", + "title": "3.0.5" + }, + { + "location": "/topics/release-notes/#304", + "text": "Date : 28th January 2015 . Django 1.8a1 support. ( #2425 , #2446 , #2441 ) Add DictField and support Django 1.8 HStoreField . ( #2451 , #2106 ) Add UUIDField and support Django 1.8 UUIDField . ( #2448 , #2433 , #2432 ) BaseRenderer.render now raises NotImplementedError . ( #2434 ) Fix timedelta JSON serialization on Python 2.6. ( #2430 ) ResultDict and ResultList now appear as standard dict/list. ( #2421 ) Fix visible HiddenField in the HTML form of the web browsable API page. ( #2410 ) Use OrderedDict for RelatedField.choices . ( #2408 ) Fix ident format when using HTTP_X_FORWARDED_FOR . ( #2401 ) Fix invalid key with memcached while using throttling. ( #2400 ) Fix FileUploadParser with version 3.x. ( #2399 ) Fix the serializer inheritance. ( #2388 ) Fix caching issues with ReturnDict . ( #2360 )", + "title": "3.0.4" + }, + { + "location": "/topics/release-notes/#303", + "text": "Date : 8th January 2015 . Fix MinValueValidator on models.DateField . ( #2369 ) Fix serializer missing context when pagination is used. ( #2355 ) Namespaced router URLs are now supported by the DefaultRouter . ( #2351 ) required=False allows omission of value for output. ( #2342 ) Use textarea input for models.TextField . ( #2340 ) Use custom ListSerializer for pagination if required. ( #2331 , #2327 ) Better behavior with null and '' for blank HTML fields. ( #2330 ) Ensure fields in exclude are model fields. ( #2319 ) Fix IntegerField and max_length argument incompatibility. ( #2317 ) Fix the YAML encoder for 3.0 serializers. ( #2315 , #2283 ) Fix the behavior of empty HTML fields. ( #2311 , #1101 ) Fix Metaclass attribute depth ignoring fields attribute. ( #2287 ) Fix format_suffix_patterns to work with Django's i18n_patterns . ( #2278 ) Ability to customize router URLs for custom actions, using url_path . ( #2010 ) Don't install Django REST Framework as egg. ( #2386 )", + "title": "3.0.3" + }, + { + "location": "/topics/release-notes/#302", + "text": "Date : 17th December 2014 . Ensure request.user is made available to response middleware. ( #2155 ) Client.logout() also cancels any existing force_authenticate . ( #2218 , #2259 ) Extra assertions and better checks to preventing incorrect serializer API use. ( #2228 , #2234 , #2262 , #2263 , #2266 , #2267 , #2289 , #2291 ) Fixed min_length message for CharField . ( #2255 ) Fix UnicodeDecodeError , which can occur on serializer repr . ( #2270 , #2279 ) Fix empty HTML values when a default is provided. ( #2280 , #2294 ) Fix SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. ( #2290 )", + "title": "3.0.2" + }, + { + "location": "/topics/release-notes/#301", + "text": "Date : 11th December 2014 . More helpful error message when the default Serializer create() fails. ( #2013 ) Raise error when attempting to save serializer if data is not valid. ( #2098 ) Fix FileUploadParser breaks with empty file names and multiple upload handlers. ( #2109 ) Improve BindingDict to support standard dict-functions. ( #2135 , #2163 ) Add validate() to ListSerializer . ( #2168 , #2225 , #2232 ) Fix JSONP renderer failing to escape some characters. ( #2169 , #2195 ) Add missing default style for FileField . ( #2172 ) Actions are required when calling ViewSet.as_view() . ( #2175 ) Add allow_blank to ChoiceField . ( #2184 , #2239 ) Cosmetic fixes in the HTML renderer. ( #2187 ) Raise error if fields on serializer is not a list of strings. ( #2193 , #2213 ) Improve checks for nested creates and updates. ( #2194 , #2196 ) validated_attrs argument renamed to validated_data in Serializer create() / update() . ( #2197 ) Remove deprecated code to reflect the dropped Django versions. ( #2200 ) Better serializer errors for nested writes. ( #2202 , #2215 ) Fix pagination and custom permissions incompatibility. ( #2205 ) Raise error if fields on serializer is not a list of strings. ( #2213 ) Add missing translation markers for relational fields. ( #2231 ) Improve field lookup behavior for dicts/mappings. ( #2244 , #2243 ) Optimized hyperlinked PK. ( #2242 )", + "title": "3.0.1" + }, + { + "location": "/topics/release-notes/#300", + "text": "Date : 1st December 2014 For full details see the 3.0 release announcement . For older release notes, please see the version 2.x documentation .", + "title": "3.0.0" } ] } \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 65b150b04..b3e304364 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -4,7 +4,7 @@ http://www.django-rest-framework.org// - 2018-09-11 + 2018-09-14 daily @@ -13,49 +13,49 @@ http://www.django-rest-framework.org//tutorial/quickstart/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/1-serialization/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/2-requests-and-responses/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/3-class-based-views/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//tutorial/7-schemas-and-client-libraries/ - 2018-09-11 + 2018-09-14 daily @@ -65,169 +65,163 @@ http://www.django-rest-framework.org//api-guide/requests/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/responses/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/views/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/generic-views/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/viewsets/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/routers/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/parsers/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/renderers/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/serializers/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/fields/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/relations/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/validators/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/authentication/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/permissions/ - 2018-09-11 - daily - - - - http://www.django-rest-framework.org//api-guide/caching/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/throttling/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/filtering/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/pagination/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/versioning/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/content-negotiation/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/metadata/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/schemas/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/format-suffixes/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/reverse/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/exceptions/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/status-codes/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/testing/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//api-guide/settings/ - 2018-09-11 + 2018-09-14 daily @@ -237,161 +231,157 @@ http://www.django-rest-framework.org//topics/documenting-your-api/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/api-clients/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/internationalization/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/ajax-csrf-cors/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/html-and-forms/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/browser-enhancements/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/browsable-api/ - 2018-09-11 + 2018-09-14 daily http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/ - 2018-09-11 - daily - - - - - - - - http://www.django-rest-framework.org//community/tutorials-and-resources/ - 2018-09-11 + 2018-09-14 daily - http://www.django-rest-framework.org//community/third-party-packages/ - 2018-09-11 + http://www.django-rest-framework.org//topics/third-party-packages/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/contributing/ - 2018-09-11 + http://www.django-rest-framework.org//topics/tutorials-and-resources/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/project-management/ - 2018-09-11 + http://www.django-rest-framework.org//topics/contributing/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/release-notes/ - 2018-09-11 + http://www.django-rest-framework.org//topics/project-management/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.8-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/jobs/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.7-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.0-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.6-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.1-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.5-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.2-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.4-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.3-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.3-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.4-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.2-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.5-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.1-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.6-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/3.0-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.7-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/kickstarter-announcement/ - 2018-09-11 + http://www.django-rest-framework.org//topics/3.8-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/mozilla-grant/ - 2018-09-11 + http://www.django-rest-framework.org//topics/kickstarter-announcement/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/funding/ - 2018-09-11 + http://www.django-rest-framework.org//topics/mozilla-grant/ + 2018-09-14 daily - http://www.django-rest-framework.org//community/jobs/ - 2018-09-11 + http://www.django-rest-framework.org//topics/funding/ + 2018-09-14 + daily + + + + http://www.django-rest-framework.org//topics/release-notes/ + 2018-09-14 daily diff --git a/community/3.0-announcement/index.html b/topics/3.0-announcement/index.html similarity index 97% rename from community/3.0-announcement/index.html rename to topics/3.0-announcement/index.html index ce3030bdb..89fda9050 100644 --- a/community/3.0-announcement/index.html +++ b/topics/3.0-announcement/index.html @@ -6,7 +6,7 @@ 3.0 Announcement - Django REST framework - + @@ -58,10 +58,10 @@
      - - -
    • Calling serializer.save() then saves and returns the new object instance.
    • The resulting API changes are further detailed below.

      -

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

      +

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

      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.

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

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

    -

    Use .validated_data instead of .object.

    +

    .object.Use .validated_data instead of

    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():
    @@ -897,7 +886,7 @@ def all_high_scores(request):
     

    Serializer fields

    -

    The Field and ReadOnly field classes.

    +

    ReadOnly field classes.The Field and

    There are some minor tweaks to the field base classes.

    Previously we had these two base classes:

      @@ -909,7 +898,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.
    -

    The required, allow_null, allow_blank and default arguments.

    +

    allow_null, default arguments.The required, allow_blank and

    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.

    @@ -1019,7 +1008,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')
     
    -

    The UniqueValidator and UniqueTogetherValidator classes.

    +

    UniqueTogetherValidator classes.The UniqueValidator and

    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/community/3.1-announcement/index.html b/topics/3.1-announcement/index.html
    similarity index 94%
    rename from community/3.1-announcement/index.html
    rename to topics/3.1-announcement/index.html
    index 022011983..67eb50228 100644
    --- a/community/3.1-announcement/index.html
    +++ b/topics/3.1-announcement/index.html
    @@ -6,7 +6,7 @@
       
       3.1 Announcement - Django REST framework
       
    -  
    +  
       
       
       
    @@ -58,10 +58,10 @@
           

    Internationalization

    -

    REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header.

    +

    REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header.

    You can change the default language by using the standard Django LANGUAGE_CODE setting:

    LANGUAGE_CODE = "es-es"
     
    @@ -538,7 +527,7 @@ Host: example.org ('en', _('English')), ]
    -

    For more details, see the internationalization documentation.

    +

    For more details, see the internationalization documentation.

    Many thanks to Craig Blaszczyk for helping push this through.


    New field types

    diff --git a/community/3.2-announcement/index.html b/topics/3.2-announcement/index.html similarity index 95% rename from community/3.2-announcement/index.html rename to topics/3.2-announcement/index.html index 7a4388df6..0382eaade 100644 --- a/community/3.2-announcement/index.html +++ b/topics/3.2-announcement/index.html @@ -6,7 +6,7 @@ 3.2 Announcement - Django REST framework - + @@ -58,10 +58,10 @@