diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..0bc60619d Binary files /dev/null and b/.DS_Store differ diff --git a/404.html b/404.html index 4938da6ea..38b436a53 100644 --- a/404.html +++ b/404.html @@ -1,112 +1,116 @@ - - - Django REST framework - 404 - Page not found - - - - - - - - - - + + + + Django REST framework - 404 - Page not found + + + + + - - + + + + + - + - - - +
- - - + +

404

-

Page not found

-

Try the homepage, or search the documentation.

-
-
-
-
+

Page not found +

+

Try the homepage, or search the documentation.

+ + + + + + + + -
- +
+ + - - - - - - + + + + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/authentication.html b/api-guide/authentication/index.html similarity index 60% rename from api-guide/authentication.html rename to api-guide/authentication/index.html index 420a1874b..e55e4dddf 100644 --- a/api-guide/authentication.html +++ b/api-guide/authentication/index.html @@ -1,65 +1,74 @@ - - - Authentication - Django REST framework - - - - - - - - - - + + + + Authentication - Django REST framework + + + + + - - + + + + + - - - - - + + +
- @@ -148,32 +295,34 @@ a.fusion-poweredby {
- - + +
-

authentication.py

-

Authentication

+ + + + authentication.py + + + + +

Authentication

Auth needs to be pluggable.

— Jacob Kaplan-Moss, "REST worst practices"

-

Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted.

+

Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted.

REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.

Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.

The request.user property will typically be set to an instance of the contrib.auth package's User class.

The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.


Note: Don't forget that authentication by itself won't allow or disallow an incoming request, it simply identifies the credentials that the request was made with.

-

For information on how to setup the permission polices for your API please see the permissions documentation.

+

For information on how to setup the permission polices for your API please see the permissions documentation.


How authentication is determined

The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates.

@@ -238,7 +476,7 @@ a.fusion-poweredby {

The value of request.user and request.auth for unauthenticated requests can be modified using the UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings.

Setting the authentication scheme

The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION setting. For example.

-
REST_FRAMEWORK = {
+
REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.BasicAuthentication',
         'rest_framework.authentication.SessionAuthentication',
@@ -247,7 +485,7 @@ a.fusion-poweredby {
 

You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class based views.

-
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
+
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response
 from rest_framework.views import APIView
@@ -264,7 +502,7 @@ class ExampleView(APIView):
         return Response(content)
 

Or, if you're using the @api_view decorator with function based views.

-
@api_view(['GET'])
+
@api_view(['GET'])
 @authentication_classes((SessionAuthentication, BasicAuthentication))
 @permission_classes((IsAuthenticated,))
 def example_view(request, format=None):
@@ -286,7 +524,7 @@ def example_view(request, format=None):
 

Apache mod_wsgi specific configuration

Note that if deploying to Apache using mod_wsgi, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.

If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the WSGIPassAuthorization directive in the appropriate context and setting it to 'On'.

-
# this can go in either server config, virtual host, directory or .htaccess
+
# this can go in either server config, virtual host, directory or .htaccess
 WSGIPassAuthorization On
 

@@ -299,13 +537,13 @@ WSGIPassAuthorization On
  • request.auth will be None.
  • Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example:

    -
    WWW-Authenticate: Basic realm="api"
    +
    WWW-Authenticate: Basic realm="api"
     

    Note: If you use BasicAuthentication in production you must ensure that your API is only available over https. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.

    TokenAuthentication

    This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.

    To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication, and additionally include rest_framework.authtoken in your INSTALLED_APPS setting:

    -
    INSTALLED_APPS = (
    +
    INSTALLED_APPS = (
         ...
         'rest_framework.authtoken'
     )
    @@ -314,13 +552,13 @@ WSGIPassAuthorization On
     

    Note: Make sure to run manage.py syncdb after changing your settings. The rest_framework.authtoken app provides both Django (from v1.7) and South database migrations. See Schema migrations below.


    You'll also need to create tokens for your users.

    -
    from rest_framework.authtoken.models import Token
    +
    from rest_framework.authtoken.models import Token
     
     token = Token.objects.create(user=...)
     print token.key
     

    For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:

    -
    Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
    +
    Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
     

    If successfully authenticated, TokenAuthentication provides the following credentials.

      @@ -328,17 +566,17 @@ print token.key
    • request.auth will be a rest_framework.authtoken.models.BasicToken instance.

    Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example:

    -
    WWW-Authenticate: Token
    +
    WWW-Authenticate: Token
     

    The curl command line tool may be useful for testing token authenticated APIs. For example:

    -
    curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
    +
    curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
     

    Note: If you use TokenAuthentication in production you must ensure that your API is only available over https.


    Generating Tokens

    If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal.

    -
    from django.conf import settings
    +
    from django.conf import settings
     from django.contrib.auth import get_user_model
     from django.db.models.signals import post_save
     from django.dispatch import receiver
    @@ -351,21 +589,21 @@ def create_auth_token(sender, instance=None, created=False, **kwargs):
     

    Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup.

    If you've already created some users, you can generate tokens for all existing users like this:

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from rest_framework.authtoken.models import Token
     
     for user in User.objects.all():
         Token.objects.get_or_create(user=user)
     

    When using TokenAuthentication, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the obtain_auth_token view to your URLconf:

    -
    from rest_framework.authtoken import views
    +
    from rest_framework.authtoken import views
     urlpatterns += [
         url(r'^api-token-auth/', views.obtain_auth_token)
     ]
     

    Note that the URL part of the pattern can be whatever you want to use.

    The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON:

    -
    { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
    +
    { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
     

    Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the obtain_auth_token view, you can do so by overriding the ObtainAuthToken view class, and using that in your url conf instead.

    Schema migrations

    @@ -375,7 +613,7 @@ urlpatterns += [

    If you're using a custom user model you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.

    You can do so by inserting a needed_by attribute in your user migration:

    -
    class Migration:
    +
    class Migration:
     
         needed_by = (
             ('authtoken', '0001_initial'),
    @@ -386,7 +624,7 @@ urlpatterns += [
     

    For more details, see the south documentation on dependencies.

    Also note that if you're using a post_save signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example:

    -
    python manage.py syncdb --noinput  # Won't create a superuser just yet, due to `--noinput`.
    +
    python manage.py syncdb --noinput  # Won't create a superuser just yet, due to `--noinput`.
     python manage.py migrate
     python manage.py createsuperuser
     
    @@ -402,13 +640,13 @@ python manage.py createsuperuser

    OAuthAuthentication

    This authentication uses OAuth 1.0a authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.

    This authentication class depends on the optional django-oauth-plus and oauth2 packages. In order to make it work you must install these packages and add oauth_provider to your INSTALLED_APPS:

    -
    INSTALLED_APPS = (
    +
    INSTALLED_APPS = (
         ...
         `oauth_provider`,
     )
     

    Don't forget to run syncdb once you've added the package.

    -
    python manage.py syncdb
    +
    python manage.py syncdb
     

    Getting started with django-oauth-plus

    The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.

    @@ -416,23 +654,23 @@ python manage.py createsuperuser

    OAuth2Authentication

    This authentication uses OAuth 2.0 authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection.

    This authentication class depends on the optional django-oauth2-provider project. In order to make it work you must install this package and add provider and provider.oauth2 to your INSTALLED_APPS:

    -
    INSTALLED_APPS = (
    +
    INSTALLED_APPS = (
         ...
         'provider',
         'provider.oauth2',
     )
     

    Then add OAuth2Authentication to your global DEFAULT_AUTHENTICATION setting:

    -
    'DEFAULT_AUTHENTICATION_CLASSES': (
    +
    'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.OAuth2Authentication',
     ),
     

    You must also include the following in your root urls.py module:

    -
    url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
    +
    url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
     

    Note that the namespace='oauth2' argument is required.

    Finally, sync your database.

    -
    python manage.py syncdb
    +
    python manage.py syncdb
     python manage.py migrate
     

    @@ -454,15 +692,15 @@ python manage.py migrate
  • password well, that speaks for itself.
  • You can use the command line to test that your local configuration is working:

    -
    curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
    +
    curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
     

    You should get a response that looks something like this:

    -
    {"access_token": "<your-access-token>", "scope": "read", "expires_in": 86399, "refresh_token": "<your-refresh-token>"}
    +
    {"access_token": "<your-access-token>", "scope": "read", "expires_in": 86399, "refresh_token": "<your-refresh-token>"}
     
    3. Access the API

    The only thing needed to make the OAuth2Authentication class work is to insert the access_token you've received in the Authorization request header.

    The command line to test the authentication looks like:

    -
    curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/
    +
    curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/
     

    Alternative OAuth 2 implementations

    Note that Django OAuth Toolkit is an alternative external package that also includes OAuth 2.0 support for REST framework.

    @@ -479,7 +717,7 @@ python manage.py migrate

    If the .authenticate_header() method is not overridden, the authentication scheme will return HTTP 403 Forbidden responses when an unauthenticated request is denied access.

    Example

    The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from rest_framework import authentication
     from rest_framework import exceptions
     
    @@ -502,7 +740,7 @@ class ExampleAuthentication(authentication.BaseAuthentication):
     

    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 OAuth Toolkit

    -

    The Django OAuth Toolkit package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by Evonove and uses the excelllent OAuthLib. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.

    +

    The Django OAuth Toolkit package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by Evonove and uses the excellent OAuthLib. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.

    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

    @@ -513,42 +751,52 @@ class ExampleAuthentication(authentication.BaseAuthentication):

    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.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/content-negotiation.html b/api-guide/content-negotiation.html deleted file mode 100644 index abb639f4a..000000000 --- a/api-guide/content-negotiation.html +++ /dev/null @@ -1,315 +0,0 @@ - - - - - Content negotiation - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    negotiation.py

    -

    Content negotiation

    -
    -

    HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.

    -

    RFC 2616, Fielding et al.

    -
    -

    Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.

    -

    Determining the accepted renderer

    -

    REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's Accept: header. The style used is partly client-driven, and partly server-driven.

    -
      -
    1. More specific media types are given preference to less specific media types.
    2. -
    3. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view.
    4. -
    -

    For example, given the following Accept header:

    -
    application/json; indent=4, application/json, application/yaml, text/html, */*
    -
    -

    The priorities for each of the given media types would be:

    -
      -
    • application/json; indent=4
    • -
    • application/json, application/yaml and text/html
    • -
    • */*
    • -
    -

    If the requested view was only configured with renderers for YAML and HTML, then REST framework would select whichever renderer was listed first in the renderer_classes list or DEFAULT_RENDERER_CLASSES setting.

    -

    For more information on the HTTP Accept header, see RFC 2616

    -
    -

    Note: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.

    -

    This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.

    -
    -

    Custom content negotiation

    -

    It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override BaseContentNegotiation.

    -

    REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the .select_parser(request, parsers) and .select_renderer(request, renderers, format_suffix) methods.

    -

    The select_parser() method should return one of the parser instances from the list of available parsers, or None if none of the parsers can handle the incoming request.

    -

    The select_renderer() method should return a two-tuple of (renderer instance, media type), or raise a NotAcceptable exception.

    -

    Example

    -

    The following is a custom content negotiation class which ignores the client -request when selecting the appropriate parser or renderer.

    -
    from rest_framework.negotiation import BaseContentNegotiation
    -
    -class IgnoreClientContentNegotiation(BaseContentNegotiation):
    -    def select_parser(self, request, parsers):
    -        """
    -        Select the first parser in the `.parser_classes` list.
    -        """
    -        return parsers[0]
    -
    -    def select_renderer(self, request, renderers, format_suffix):
    -        """
    -        Select the first renderer in the `.renderer_classes` list.
    -        """
    -        return (renderers[0], renderers[0].media_type)
    -
    -

    Setting the content negotiation

    -

    The default content negotiation class may be set globally, using the DEFAULT_CONTENT_NEGOTIATION_CLASS setting. For example, the following settings would use our example IgnoreClientContentNegotiation class.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
    -}
    -
    -

    You can also set the content negotiation used for an individual view, or viewset, using the APIView class based views.

    -
    from myapp.negotiation import IgnoreClientContentNegotiation
    -from rest_framework.response import Response
    -from rest_framework.views import APIView
    -
    -class NoNegotiationView(APIView):
    -    """
    -    An example view that does not perform content negotiation.
    -    """
    -    content_negotiation_class = IgnoreClientContentNegotiation
    -
    -    def get(self, request, format=None):
    -        return Response({
    -            'accepted media type': request.accepted_renderer.media_type
    -        })
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html new file mode 100644 index 000000000..160ef261b --- /dev/null +++ b/api-guide/content-negotiation/index.html @@ -0,0 +1,507 @@ + + + + + + + Content negotiation - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + negotiation.py + + + + +

    Content negotiation

    +
    +

    HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.

    +

    RFC 2616, Fielding et al.

    +
    +

    Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.

    +

    Determining the accepted renderer

    +

    REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's Accept: header. The style used is partly client-driven, and partly server-driven.

    +
      +
    1. More specific media types are given preference to less specific media types.
    2. +
    3. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view.
    4. +
    +

    For example, given the following Accept header:

    +
    application/json; indent=4, application/json, application/yaml, text/html, */*
    +
    +

    The priorities for each of the given media types would be:

    +
      +
    • application/json; indent=4
    • +
    • application/json, application/yaml and text/html
    • +
    • */*
    • +
    +

    If the requested view was only configured with renderers for YAML and HTML, then REST framework would select whichever renderer was listed first in the renderer_classes list or DEFAULT_RENDERER_CLASSES setting.

    +

    For more information on the HTTP Accept header, see RFC 2616

    +
    +

    Note: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.

    +

    This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.

    +
    +

    Custom content negotiation

    +

    It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override BaseContentNegotiation.

    +

    REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the .select_parser(request, parsers) and .select_renderer(request, renderers, format_suffix) methods.

    +

    The select_parser() method should return one of the parser instances from the list of available parsers, or None if none of the parsers can handle the incoming request.

    +

    The select_renderer() method should return a two-tuple of (renderer instance, media type), or raise a NotAcceptable exception.

    +

    Example

    +

    The following is a custom content negotiation class which ignores the client +request when selecting the appropriate parser or renderer.

    +
    from rest_framework.negotiation import BaseContentNegotiation
    +
    +class IgnoreClientContentNegotiation(BaseContentNegotiation):
    +    def select_parser(self, request, parsers):
    +        """
    +        Select the first parser in the `.parser_classes` list.
    +        """
    +        return parsers[0]
    +
    +    def select_renderer(self, request, renderers, format_suffix):
    +        """
    +        Select the first renderer in the `.renderer_classes` list.
    +        """
    +        return (renderers[0], renderers[0].media_type)
    +
    +

    Setting the content negotiation

    +

    The default content negotiation class may be set globally, using the DEFAULT_CONTENT_NEGOTIATION_CLASS setting. For example, the following settings would use our example IgnoreClientContentNegotiation class.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
    +}
    +
    +

    You can also set the content negotiation used for an individual view, or viewset, using the APIView class based views.

    +
    from myapp.negotiation import IgnoreClientContentNegotiation
    +from rest_framework.response import Response
    +from rest_framework.views import APIView
    +
    +class NoNegotiationView(APIView):
    +    """
    +    An example view that does not perform content negotiation.
    +    """
    +    content_negotiation_class = IgnoreClientContentNegotiation
    +
    +    def get(self, request, format=None):
    +        return Response({
    +            'accepted media type': request.accepted_renderer.media_type
    +        })
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/exceptions.html b/api-guide/exceptions.html deleted file mode 100644 index adbf5b889..000000000 --- a/api-guide/exceptions.html +++ /dev/null @@ -1,352 +0,0 @@ - - - - - Exceptions - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    exceptions.py

    -

    Exceptions

    -
    -

    Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

    -

    — Doug Hellmann, Python Exception Handling Techniques

    -
    -

    Exception handling in REST framework views

    -

    REST framework's views handle various exceptions, and deal with returning appropriate error responses.

    -

    The handled exceptions are:

    -
      -
    • Subclasses of APIException raised inside REST framework.
    • -
    • Django's Http404 exception.
    • -
    • Django's PermissionDenied exception.
    • -
    -

    In 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.

    -

    By default all error responses will include a key detail in the body of the response, but other keys may also be included.

    -

    For example, the following request:

    -
    DELETE http://api.example.com/foo/bar HTTP/1.1
    -Accept: application/json
    -
    -

    Might receive an error response indicating that the DELETE method is not allowed on that resource:

    -
    HTTP/1.1 405 Method Not Allowed
    -Content-Type: application/json
    -Content-Length: 42
    -
    -{"detail": "Method 'DELETE' not allowed."}
    -
    -

    Custom exception handling

    -

    You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

    -

    The function must take a single argument, which is the exception to be handled, and should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

    -

    For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:

    -
    HTTP/1.1 405 Method Not Allowed
    -Content-Type: application/json
    -Content-Length: 62
    -
    -{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
    -
    -

    In order to alter the style of the response, you could write the following custom exception handler:

    -
    from rest_framework.views import exception_handler
    -
    -def custom_exception_handler(exc):
    -    # Call REST framework's default exception handler first,
    -    # to get the standard error response.
    -    response = exception_handler(exc)
    -
    -    # Now add the HTTP status code to the response.
    -    if response is not None:
    -        response.data['status_code'] = response.status_code
    -
    -    return response
    -
    -

    The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:

    -
    REST_FRAMEWORK = {
    -    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    -}
    -
    -

    If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:

    -
    REST_FRAMEWORK = {
    -    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    -}
    -
    -

    Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

    -
    -

    API Reference

    -

    APIException

    -

    Signature: APIException()

    -

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

    -

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

    -

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

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

    ParseError

    -

    Signature: ParseError(detail=None)

    -

    Raised if the request contains malformed data when accessing request.DATA or request.FILES.

    -

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

    -

    AuthenticationFailed

    -

    Signature: AuthenticationFailed(detail=None)

    -

    Raised when an incoming request includes incorrect authentication.

    -

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

    -

    NotAuthenticated

    -

    Signature: NotAuthenticated(detail=None)

    -

    Raised when an unauthenticated request fails the permission checks.

    -

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

    -

    PermissionDenied

    -

    Signature: PermissionDenied(detail=None)

    -

    Raised when an authenticated request fails the permission checks.

    -

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

    -

    MethodNotAllowed

    -

    Signature: MethodNotAllowed(method, detail=None)

    -

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

    -

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

    -

    UnsupportedMediaType

    -

    Signature: UnsupportedMediaType(media_type, detail=None)

    -

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

    -

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

    -

    Throttled

    -

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

    -

    Raised when an incoming request fails the throttling checks.

    -

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

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/exceptions/index.html b/api-guide/exceptions/index.html new file mode 100644 index 000000000..4857a7d42 --- /dev/null +++ b/api-guide/exceptions/index.html @@ -0,0 +1,565 @@ + + + + + + + Exceptions - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + exceptions.py + + + + +

    Exceptions

    +
    +

    Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

    +

    — Doug Hellmann, Python Exception Handling Techniques

    +
    +

    Exception handling in REST framework views

    +

    REST framework's views handle various exceptions, and deal with returning appropriate error responses.

    +

    The handled exceptions are:

    +
      +
    • Subclasses of APIException raised inside REST framework.
    • +
    • Django's Http404 exception.
    • +
    • Django's PermissionDenied exception.
    • +
    +

    In 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.

    +

    By default all error responses will include a key detail in the body of the response, but other keys may also be included.

    +

    For example, the following request:

    +
    DELETE http://api.example.com/foo/bar HTTP/1.1
    +Accept: application/json
    +
    +

    Might receive an error response indicating that the DELETE method is not allowed on that resource:

    +
    HTTP/1.1 405 Method Not Allowed
    +Content-Type: application/json
    +Content-Length: 42
    +
    +{"detail": "Method 'DELETE' not allowed."}
    +
    +

    Custom exception handling

    +

    You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

    +

    The function must take a single argument, which is the exception to be handled, and should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

    +

    For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:

    +
    HTTP/1.1 405 Method Not Allowed
    +Content-Type: application/json
    +Content-Length: 62
    +
    +{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
    +
    +

    In order to alter the style of the response, you could write the following custom exception handler:

    +
    from rest_framework.views import exception_handler
    +
    +def custom_exception_handler(exc):
    +    # Call REST framework's default exception handler first,
    +    # to get the standard error response.
    +    response = exception_handler(exc)
    +
    +    # Now add the HTTP status code to the response.
    +    if response is not None:
    +        response.data['status_code'] = response.status_code
    +
    +    return response
    +
    +

    The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:

    +
    REST_FRAMEWORK = {
    +    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    +}
    +
    +

    If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:

    +
    REST_FRAMEWORK = {
    +    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    +}
    +
    +

    Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

    +
    +

    API Reference

    +

    APIException

    +

    Signature: APIException()

    +

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

    +

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

    +

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

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

    ParseError

    +

    Signature: ParseError(detail=None)

    +

    Raised if the request contains malformed data when accessing request.DATA or request.FILES.

    +

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

    +

    AuthenticationFailed

    +

    Signature: AuthenticationFailed(detail=None)

    +

    Raised when an incoming request includes incorrect authentication.

    +

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

    +

    NotAuthenticated

    +

    Signature: NotAuthenticated(detail=None)

    +

    Raised when an unauthenticated request fails the permission checks.

    +

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

    +

    PermissionDenied

    +

    Signature: PermissionDenied(detail=None)

    +

    Raised when an authenticated request fails the permission checks.

    +

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

    +

    MethodNotAllowed

    +

    Signature: MethodNotAllowed(method, detail=None)

    +

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

    +

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

    +

    UnsupportedMediaType

    +

    Signature: UnsupportedMediaType(media_type, detail=None)

    +

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

    +

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

    +

    Throttled

    +

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

    +

    Raised when an incoming request fails the throttling checks.

    +

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

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/fields.html b/api-guide/fields/index.html similarity index 54% rename from api-guide/fields.html rename to api-guide/fields/index.html index 7ba5ac315..c27962bc6 100644 --- a/api-guide/fields.html +++ b/api-guide/fields/index.html @@ -1,65 +1,74 @@ - - - Serializer fields - Django REST framework - - - - - - - - - - + + + + Serializer fields - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    -

    fields.py

    -

    Serializer fields

    + + + + fields.py + + + + +

    Serializer fields

    Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.

    Django documentation

    @@ -261,7 +530,7 @@ Set to false if this field is not required to be present during deserialization.

    A dictionary of error codes to error messages.

    widget

    Used only if rendering the field to HTML. -This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see the Django documentation on form widgets.

    +This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see the Django documentation on form widgets.

    label

    A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.

    help_text

    @@ -272,7 +541,7 @@ This argument sets the widget that should be used to render the field. For more

    Field

    A generic, read-only field. You can use this field for any attribute that does not need to support write operations.

    For example, using the following model.

    -
    from django.db import models
    +
    from django.db import models
     from django.utils.timezone import now
     
     class Account(models.Model):
    @@ -285,7 +554,7 @@ class Account(models.Model):
             return now() > self.payment_expiry
     

    A serializer definition that looked like this:

    -
    from rest_framework import serializers
    +
    from rest_framework import serializers
     
     class AccountSerializer(serializers.HyperlinkedModelSerializer):
         expired = serializers.Field(source='has_expired')
    @@ -295,7 +564,7 @@ class AccountSerializer(serializers.HyperlinkedModelSerializer):
             fields = ('url', 'owner', 'name', 'expired')
     

    Would produce output similar to:

    -
    {
    +
    {
         'url': 'http://example.com/api/accounts/3/',
         'owner': 'http://example.com/api/users/12/',
         'name': 'FooCorp business account',
    @@ -312,7 +581,7 @@ class AccountSerializer(serializers.HyperlinkedModelSerializer):
     

    Signature: ModelField(model_field=<Django ModelField instance>)

    SerializerMethodField

    This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from django.utils.timezone import now
     from rest_framework import serializers
     
    @@ -359,7 +628,7 @@ or django.db.models.fields.TextField.

    Corresponds to django.db.models.fields.DateTimeField

    When using ModelSerializer or HyperlinkedModelSerializer, note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default.

    If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example:

    -
    class CommentSerializer(serializers.ModelSerializer):
    +
    class CommentSerializer(serializers.ModelSerializer):
         created = serializers.DateTimeField()
     
         class Meta:
    @@ -399,7 +668,25 @@ or django.db.models.fields.TextField.

    A floating point representation.

    Corresponds to django.db.models.fields.FloatField.

    DecimalField

    -

    A decimal representation.

    +

    A decimal representation, represented in Python by a Decimal instance.

    +

    Has two required arguments:

    +
      +
    • +

      max_digits The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.

      +
    • +
    • +

      decimal_places The number of decimal places to store with the number.

      +
    • +
    +

    For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use:

    +
    serializers.DecimalField(max_digits=5, decimal_places=2)
    +
    +

    And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:

    +
    serializers.DecimalField(max_digits=19, decimal_places=10)
    +
    +

    This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.

    +

    If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.

    +

    Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None)

    Corresponds to django.db.models.fields.DecimalField.

    FileField

    A file representation. Performs Django's standard FileField validation.

    @@ -427,7 +714,7 @@ Django's regular Examples

    Let's look at an example of serializing a class that represents an RGB color value:

    -
    class Color(object):
    +
    class Color(object):
         """
         A color represented in the RGB colorspace.
         """
    @@ -450,7 +737,7 @@ class ColourField(serializers.WritableField):
     

    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 .field_to_native() and/or .field_from_native().

    As an example, let's create a field that can be used represent the class name of the object being serialized:

    -
    class ClassNameField(serializers.Field):
    +
    class ClassNameField(serializers.Field):
         def field_to_native(self, obj, field_name):
             """
             Serialize the object's class name.
    @@ -467,42 +754,52 @@ class ColourField(serializers.WritableField):
     

    The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer.

    django-rest-framework-hstore

    The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/filtering.html b/api-guide/filtering/index.html similarity index 55% rename from api-guide/filtering.html rename to api-guide/filtering/index.html index fe7da8799..eb56e0511 100644 --- a/api-guide/filtering.html +++ b/api-guide/filtering/index.html @@ -1,65 +1,74 @@ - - - Filtering - Django REST framework - - - - - - - - - - + + + + Filtering - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    -

    filters.py

    -

    Filtering

    + + + + filters.py + + + + +

    Filtering

    The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.

    Django documentation

    @@ -226,7 +456,7 @@ a.fusion-poweredby {

    You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.

    You can do so by filtering based on the value of request.user.

    For example:

    -
    from myapp.models import Purchase
    +
    from myapp.models import Purchase
     from myapp.serializers import PurchaseSerializer
     from rest_framework import generics
     
    @@ -242,12 +472,12 @@ class PurchaseList(generics.ListAPIView):
             return Purchase.objects.filter(purchaser=user)
     

    Filtering against the URL

    -

    Another style of filtering might involve restricting the queryset based on some part of the URL.

    +

    Another style of filtering might involve restricting the queryset based on some part of the URL.

    For example if your URL config contained an entry like this:

    -
    url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
    +
    url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
     

    You could then write a view that returned a purchase queryset filtered by the username portion of the URL:

    -
    class PurchaseList(generics.ListAPIView):
    +
    class PurchaseList(generics.ListAPIView):
         serializer_class = PurchaseSerializer
     
         def get_queryset(self):
    @@ -261,7 +491,7 @@ class PurchaseList(generics.ListAPIView):
     

    Filtering against query parameters

    A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.

    We can override .get_queryset() to deal with URLs such as http://example.com/api/purchases?username=denvercoder9, and filter the queryset only if the username parameter is included in the URL:

    -
    class PurchaseList(generics.ListAPIView):
    +
    class PurchaseList(generics.ListAPIView):
         serializer_class = PurchaseSerializer
     
         def get_queryset(self):
    @@ -280,13 +510,13 @@ class PurchaseList(generics.ListAPIView):
     

    As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.

    Setting filter backends

    The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example.

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
     }
     

    You can also set the filter backends on a per-view, or per-viewset basis, using the GenericAPIView class based views.

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from myapp.serializers import UserSerializer
     from rest_framework import filters
     from rest_framework import generics
    @@ -299,11 +529,11 @@ class UserListView(generics.ListAPIView):
     

    Filtering and object lookups

    Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.

    For instance, given the previous example, and a product with an id of 4675, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:

    -
    http://example.com/api/products/4675/?category=clothing&max_price=10.00
    +
    http://example.com/api/products/4675/?category=clothing&max_price=10.00
     

    Overriding the initial queryset

    Note that you can use both an overridden .get_queryset() and generic filtering together, and everything will work as expected. For example, if Product had a many-to-many relationship with User, named purchase, you might want to write a view like this:

    -
    class PurchasedProductsList(generics.ListAPIView):
    +
    class PurchasedProductsList(generics.ListAPIView):
         """
         Return a list of all the products that the authenticated
         user has ever purchased, with optional filtering.
    @@ -319,23 +549,23 @@ class UserListView(generics.ListAPIView):
     

    API Guide

    DjangoFilterBackend

    -

    The DjangoFilterBackend class supports highly customizable field filtering, using the django-filter package.

    +

    The DjangoFilterBackend class supports highly customizable field filtering, using the django-filter package.

    To use REST framework's DjangoFilterBackend, first install django-filter.

    -
    pip install django-filter
    +
    pip install django-filter
     

    Specifying filter fields

    If all you need is simple equality-based filtering, you can set a filter_fields attribute on the view, or viewset, listing the set of fields you wish to filter against.

    -
    class ProductList(generics.ListAPIView):
    +
    class ProductList(generics.ListAPIView):
         queryset = Product.objects.all()
         serializer_class = ProductSerializer
         filter_fields = ('category', 'in_stock')
     

    This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as:

    -
    http://example.com/api/products?category=clothing&in_stock=True
    +
    http://example.com/api/products?category=clothing&in_stock=True
     

    Specifying a FilterSet

    For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. For example:

    -
    import django_filters
    +
    import django_filters
     from myapp.models import Product
     from myapp.serializers import ProductSerializer
     from rest_framework import generics
    @@ -353,12 +583,12 @@ class ProductList(generics.ListAPIView):
         filter_class = ProductFilter
     

    Which will allow you to make requests such as:

    -
    http://example.com/api/products?category=clothing&max_price=10.00
    +
    http://example.com/api/products?category=clothing&max_price=10.00
     

    You can also span relationships using django-filter, let's assume that each product has foreign key to Manufacturer model, so we create filter that filters using Manufacturer name. For example:

    -
    import django_filters
    +
    import django_filters
     from myapp.models import Product
     from myapp.serializers import ProductSerializer
     from rest_framework import generics
    @@ -369,10 +599,10 @@ class ProductFilter(django_filters.FilterSet):
             fields = ['category', 'in_stock', 'manufacturer__name']
     

    This enables us to make queries like:

    -
    http://example.com/api/products?manufacturer__name=foo
    +
    http://example.com/api/products?manufacturer__name=foo
     

    This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the FilterSet class:

    -
    import django_filters
    +
    import django_filters
     from myapp.models import Product
     from myapp.serializers import ProductSerializer
     from rest_framework import generics
    @@ -385,14 +615,14 @@ class ProductFilter(django_filters.FilterSet):
             fields = ['category', 'in_stock', 'manufacturer']
     

    And now you can execute:

    -
    http://example.com/api/products?manufacturer=foo
    +
    http://example.com/api/products?manufacturer=foo
     

    For more details on using filter sets see the django-filter documentation.


    Hints & Tips

    • By default filtering is not enabled. If you want to use DjangoFilterBackend remember to make sure it is installed by using the 'DEFAULT_FILTER_BACKENDS' setting.
    • -
    • When using boolean fields, you should use the values True and False in the URL query parameters, rather than 0, 1, true or false. (The allowed boolean values are currently hardwired in Django's NullBooleanSelect implementation.)
    • +
    • When using boolean fields, you should use the values True and False in the URL query parameters, rather than 0, 1, true or false. (The allowed boolean values are currently hardwired in Django's NullBooleanSelect implementation.)
    • django-filter supports filtering across relationships, using Django's double-underscore syntax.
    • For Django 1.3 support, make sure to install django-filter version 0.5.4, as later versions drop support for 1.3.
    @@ -400,17 +630,17 @@ class ProductFilter(django_filters.FilterSet):

    SearchFilter

    The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality.

    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):
    +
    class UserListView(generics.ListAPIView):
         queryset = User.objects.all()
         serializer = UserSerializer
         filter_backends = (filters.SearchFilter,)
         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
    +
    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')
    +
    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.

    @@ -420,7 +650,7 @@ class ProductFilter(django_filters.FilterSet):
  • '@' Full-text search. (Currently only supported Django's MySQL backend.)
  • For example:

    -
    search_fields = ('=username', '=email')
    +
    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.

    @@ -428,17 +658,17 @@ class ProductFilter(django_filters.FilterSet):

    OrderingFilter

    The OrderingFilter class supports simple query parameter controlled ordering of results. By default, the query parameter is named 'ordering', but this may by overridden with the ORDERING_PARAM setting.

    For example, to order users by username:

    -
    http://example.com/api/users?ordering=username
    +
    http://example.com/api/users?ordering=username
     

    The client may also specify reverse orderings by prefixing the field name with '-', like so:

    -
    http://example.com/api/users?ordering=-username
    +
    http://example.com/api/users?ordering=-username
     

    Multiple orderings may also be specified:

    -
    http://example.com/api/users?ordering=account,username
    +
    http://example.com/api/users?ordering=account,username
     

    Specifying which fields may be ordered against

    It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so:

    -
    class UserListView(generics.ListAPIView):
    +
    class UserListView(generics.ListAPIView):
         queryset = User.objects.all()
         serializer_class = UserSerializer
         filter_backends = (filters.OrderingFilter,)
    @@ -447,7 +677,7 @@ class ProductFilter(django_filters.FilterSet):
     

    This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.

    If you don't specify an ordering_fields 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 serializer_class attribute.

    If 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 any model field or queryset aggregate, by using the special value '__all__'.

    -
    class BookingsListView(generics.ListAPIView):
    +
    class BookingsListView(generics.ListAPIView):
         queryset = Booking.objects.all()
         serializer_class = BookingSerializer
         filter_backends = (filters.OrderingFilter,)
    @@ -456,7 +686,7 @@ class ProductFilter(django_filters.FilterSet):
     

    Specifying a default ordering

    If an ordering attribute is set on the view, this will be used as the default ordering.

    Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering 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.

    -
    class UserListView(generics.ListAPIView):
    +
    class UserListView(generics.ListAPIView):
         queryset = User.objects.all()
         serializer_class = UserSerializer
         filter_backends = (filters.OrderingFilter,)
    @@ -470,7 +700,7 @@ class ProductFilter(django_filters.FilterSet):
     

    If you're using DjangoObjectPermissionsFilter, 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 DjangoObjectPermissions and add 'view' permissions to the perms_map attribute.

    A complete example using both DjangoObjectPermissionsFilter and DjangoObjectPermissions might look something like this.

    permissions.py:

    -
    class CustomObjectPermissions(permissions.DjangoObjectPermissions):
    +
    class CustomObjectPermissions(permissions.DjangoObjectPermissions):
         """
         Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
         """
    @@ -485,7 +715,7 @@ class ProductFilter(django_filters.FilterSet):
         }
     

    views.py:

    -
    class EventViewSet(viewsets.ModelViewSet):
    +
    class EventViewSet(viewsets.ModelViewSet):
         """
         Viewset that only lists events if user has 'view' permissions, and only
         allows operations on individual events if user has appropriate 'view', 'add',
    @@ -504,7 +734,7 @@ class ProductFilter(django_filters.FilterSet):
     

    As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.

    Example

    For example, you might need to restrict users to only being able to see objects they created.

    -
    class IsOwnerFilterBackend(filters.BaseFilterBackend):
    +
    class IsOwnerFilterBackend(filters.BaseFilterBackend):
         """
         Filter that only allows users to see their own objects.
         """
    @@ -516,42 +746,52 @@ class ProductFilter(django_filters.FilterSet):
     

    The following third party packages provide additional filter implementations.

    Django REST framework chain

    The django-rest-framework-chain package works together with the DjangoFilterBackend class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/format-suffixes.html b/api-guide/format-suffixes.html deleted file mode 100644 index 0531f75c7..000000000 --- a/api-guide/format-suffixes.html +++ /dev/null @@ -1,291 +0,0 @@ - - - - - Format suffixes - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    urlpatterns.py

    -

    Format suffixes

    -
    -

    Section 6.2.1 does not say that content negotiation should be -used all the time.

    -

    — Roy Fielding, REST discuss mailing list

    -
    -

    A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.

    -

    Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.

    -

    format_suffix_patterns

    -

    Signature: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None)

    -

    Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided.

    -

    Arguments:

    -
      -
    • urlpatterns: Required. A URL pattern list.
    • -
    • suffix_required: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False, meaning that suffixes are optional by default.
    • -
    • allowed: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
    • -
    -

    Example:

    -
    from rest_framework.urlpatterns import format_suffix_patterns
    -from blog import views
    -
    -urlpatterns = [
    -    url(r'^/$', views.apt_root),
    -    url(r'^comments/$', views.comment_list),
    -    url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
    -]
    -
    -urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
    -
    -

    When using format_suffix_patterns, you must make sure to add the 'format' keyword argument to the corresponding views. For example:

    -
    @api_view(('GET', 'POST'))
    -def comment_list(request, format=None):
    -    # do stuff...
    -
    -

    Or with class based views:

    -
    class CommentList(APIView):
    -    def get(self, request, format=None):
    -        # do stuff...
    -
    -    def post(self, request, format=None):
    -        # do stuff...
    -
    -

    The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting.

    -

    Also note that format_suffix_patterns does not support descending into include URL patterns.

    -
    -

    Accept headers vs. format suffixes

    -

    There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that HTTP Accept headers should always be used instead.

    -

    It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:

    -

    “That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, REST discuss mailing list

    -

    The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/format-suffixes/index.html b/api-guide/format-suffixes/index.html new file mode 100644 index 000000000..7e73503f6 --- /dev/null +++ b/api-guide/format-suffixes/index.html @@ -0,0 +1,473 @@ + + + + + + + Format suffixes - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + urlpatterns.py + + + + +

    Format suffixes

    +
    +

    Section 6.2.1 does not say that content negotiation should be +used all the time.

    +

    — Roy Fielding, REST discuss mailing list

    +
    +

    A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.

    +

    Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.

    +

    format_suffix_patterns

    +

    Signature: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None)

    +

    Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided.

    +

    Arguments:

    +
      +
    • urlpatterns: Required. A URL pattern list.
    • +
    • suffix_required: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False, meaning that suffixes are optional by default.
    • +
    • allowed: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
    • +
    +

    Example:

    +
    from rest_framework.urlpatterns import format_suffix_patterns
    +from blog import views
    +
    +urlpatterns = [
    +    url(r'^/$', views.apt_root),
    +    url(r'^comments/$', views.comment_list),
    +    url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
    +]
    +
    +urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
    +
    +

    When using format_suffix_patterns, you must make sure to add the 'format' keyword argument to the corresponding views. For example:

    +
    @api_view(('GET', 'POST'))
    +def comment_list(request, format=None):
    +    # do stuff...
    +
    +

    Or with class based views:

    +
    class CommentList(APIView):
    +    def get(self, request, format=None):
    +        # do stuff...
    +
    +    def post(self, request, format=None):
    +        # do stuff...
    +
    +

    The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting.

    +

    Also note that format_suffix_patterns does not support descending into include URL patterns.

    +
    +

    Accept headers vs. format suffixes

    +

    There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that HTTP Accept headers should always be used instead.

    +

    It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:

    +

    “That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, REST discuss mailing list

    +

    The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/generic-views.html b/api-guide/generic-views/index.html similarity index 56% rename from api-guide/generic-views.html rename to api-guide/generic-views/index.html index af3f445c1..57c1649a0 100644 --- a/api-guide/generic-views.html +++ b/api-guide/generic-views/index.html @@ -1,65 +1,74 @@ - - - Generic views - Django REST framework - - - - - - - - - - + + + + Generic views - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    -

    mixins.py -generics.py

    -

    Generic views

    + + + + mixins.py + + + + generics.py + + + + +

    Generic views

    Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.

    Django Documentation

    @@ -233,7 +502,7 @@ a.fusion-poweredby {

    If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.

    Examples

    Typically when using the generic views, you'll override the view, and set several class attributes.

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from myapp.serializers import UserSerializer
     from rest_framework import generics
     from rest_framework.permissions import IsAdminUser
    @@ -245,7 +514,7 @@ class UserList(generics.ListCreateAPIView):
         paginate_by = 100
     

    For more complex cases you might also want to override various methods on the view class. For example.

    -
    class UserList(generics.ListCreateAPIView):
    +
    class UserList(generics.ListCreateAPIView):
         queryset = User.objects.all()
         serializer_class = UserSerializer
         permission_classes = (IsAdminUser,)
    @@ -265,7 +534,7 @@ class UserList(generics.ListCreateAPIView):
             return Response(serializer.data)
     

    For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something like the following entry:

    -
    url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
    +
    url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
     

    API Reference

    @@ -304,7 +573,7 @@ class UserList(generics.ListCreateAPIView):

    This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.

    May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.

    For example:

    -
    def get_queryset(self):
    +
    def get_queryset(self):
         user = self.request.user
         return user.accounts.all()
     
    @@ -312,7 +581,7 @@ class UserList(generics.ListCreateAPIView):

    Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset.

    May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.

    For example:

    -
    def get_object(self):
    +
    def get_object(self):
         queryset = self.get_queryset()
         filter = {}
         for field in self.multiple_lookup_fields:
    @@ -327,7 +596,7 @@ class UserList(generics.ListCreateAPIView):
     

    Returns the classes that should be used to filter the queryset. Defaults to returning the filter_backends attribute.

    May be overridden to provide more complex behavior with filters, such as using different (or even exlusive) lists of filter_backends depending on different criteria.

    For example:

    -
    def get_filter_backends(self):
    +
    def get_filter_backends(self):
         if "geo_route" in self.request.QUERY_PARAMS:
             return (GeoRouteFilter, CategoryFilter)
         elif "geo_point" in self.request.QUERY_PARAMS:
    @@ -339,7 +608,7 @@ class UserList(generics.ListCreateAPIView):
     

    Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute, or dynamically generating a serializer class if the model shortcut is being used.

    May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.

    For example:

    -
    def get_serializer_class(self):
    +
    def get_serializer_class(self):
         if self.request.user.is_staff:
             return FullAccountSerializer
         return BasicAccountSerializer
    @@ -348,7 +617,7 @@ class UserList(generics.ListCreateAPIView):
     

    Returns the page size to use with pagination. By default this uses the paginate_by attribute, and may be overridden by the client if the paginate_by_param attribute is set.

    You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.

    For example:

    -
    def get_paginate_by(self):
    +
    def get_paginate_by(self):
         if self.request.accepted_renderer.format == 'html':
             return 20
         return 100
    @@ -362,7 +631,7 @@ class UserList(generics.ListCreateAPIView):
     
  • post_delete(self, obj) - A hook that is called after deleting an object.
  • The pre_save method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

    -
    def pre_save(self, obj):
    +
    def pre_save(self, obj):
         """
         Set the object's owner, based on the incoming request.
         """
    @@ -384,7 +653,6 @@ class UserList(generics.ListCreateAPIView):
     

    ListModelMixin

    Provides a .list(request, *args, **kwargs) method, that implements listing a queryset.

    If the queryset is populated, this returns a 200 OK response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.

    -

    If the queryset is empty this returns a 200 OK response, unless the .allow_empty attribute on the view is set to False, in which case it will return a 404 Not Found.

    CreateModelMixin

    Provides a .create(request, *args, **kwargs) method, that implements creating and saving a new model instance.

    If an object is created this returns a 201 Created response, with a serialized representation of the object as the body of the response. If the representation contains a key named url, then the Location header of the response will be populated with that value.

    @@ -445,7 +713,7 @@ class UserList(generics.ListCreateAPIView):

    Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.

    Creating custom mixins

    For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:

    -
    class MultipleFieldLookupMixin(object):
    +
    class MultipleFieldLookupMixin(object):
         """
         Apply this mixin to any view or viewset to get multiple field filtering
         based on a `lookup_fields` attribute, instead of the default single field filtering.
    @@ -459,7 +727,7 @@ class UserList(generics.ListCreateAPIView):
             return get_object_or_404(queryset, **filter)  # Lookup the object
     

    You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.

    -
    class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
    +
    class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
         queryset = User.objects.all()
         serializer_class = UserSerializer
         lookup_fields = ('account', 'username')
    @@ -467,7 +735,7 @@ class UserList(generics.ListCreateAPIView):
     

    Using custom mixins is a good option if you have custom behavior that needs to be used

    Creating custom base classes

    If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:

    -
    class BaseRetrieveView(MultipleFieldLookupMixin,
    +
    class BaseRetrieveView(MultipleFieldLookupMixin,
                            generics.RetrieveAPIView):
         pass
     
    @@ -476,46 +744,63 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
         pass
     

    Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.

    +
    +

    PUT as create

    +

    Prior to version 3.0 the REST framework mixins treated PUT as either an update or a create operation, depending on if the object already existed or not.

    +

    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 from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.

    +

    If you need to generic PUT-as-create behavior you may want to include something like this AllowPUTAsCreateMixin class as a mixin to your views.

    +

    Third party packages

    The following third party packages provide additional generic view implementations.

    Django REST Framework bulk

    The django-rest-framework-bulk package implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/metadata.html b/api-guide/metadata.html deleted file mode 100644 index 1ca656b7f..000000000 --- a/api-guide/metadata.html +++ /dev/null @@ -1,324 +0,0 @@ - - - - - Metadata - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    metadata.py

    -

    Metadata

    -
    -

    [The OPTIONS] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

    -

    RFC7231, Section 4.3.7.

    -
    -

    REST framework includes a configurable mechanism for determining how your API should respond to OPTIONS requests. This allows you to return API schema or other resource information.

    -

    There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP OPTIONS requests, so we provide an ad-hoc style that returns some useful information.

    -

    Here's an example response that demonstrates the information that is returned by default.

    -
    HTTP 200 OK
    -Allow: GET, POST, HEAD, OPTIONS
    -Content-Type: application/json
    -
    -{
    -    "name": "To Do List",
    -    "description": "List existing 'To Do' items, or create a new item.",
    -    "renders": [
    -        "application/json",
    -        "text/html"
    -    ],
    -    "parses": [
    -        "application/json",
    -        "application/x-www-form-urlencoded",
    -        "multipart/form-data"
    -    ],
    -    "actions": {
    -        "POST": {
    -            "note": {
    -                "type": "string",
    -                "required": false,
    -                "read_only": false,
    -                "label": "title",
    -                "max_length": 100
    -            }
    -        }
    -    }
    -}
    -
    -

    Setting the metadata scheme

    -

    You can set the metadata class globally using the 'DEFAULT_METADATA_CLASS' settings key:

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
    -}
    -
    -

    Or you can set the metadata class individually for a view:

    -
    class APIRoot(APIView):
    -    metadata_class = APIRootMetadata
    -
    -    def get(self, request, format=None):
    -        return Response({
    -            ...
    -        })
    -
    -

    The REST framework package only includes a single metadata class implementation, named SimpleMetadata. If you want to use an alternative style you'll need to implement a custom metadata class.

    -

    Creating schema endpoints

    -

    If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider re-using the metadata API for doing so.

    -

    For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.

    -
    @list_route(methods=['GET'])
    -def schema(self, request):
    -    meta = self.metadata_class()
    -    data = meta.determine_metadata(request, self)
    -    return Response(data)
    -
    -

    There are a couple of reasons that you might choose to take this approach, including that OPTIONS responses are not cacheable.

    -
    -

    Custom metadata classes

    -

    If you want to provide a custom metadata class you should override BaseMetadata and implement the determine_metadata(self, request, view) method.

    -

    Useful things that you might want to do could include returning schema information, using a format such as JSON schema, or returning debug information to admin users.

    -

    Example

    -

    The following class could be used to limit the information that is returned to OPTIONS requests.

    -
    class MinimalMetadata(BaseMetadata):
    -    """
    -    Don't include field and other information for `OPTIONS` requests.
    -    Just return the name and description.
    -    """
    -    def determine_metadata(self, request, view):
    -        return {
    -            'name': view.get_view_name(),
    -            'description': view.get_view_description()
    -        }
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/pagination.html b/api-guide/pagination.html deleted file mode 100644 index 0f2365827..000000000 --- a/api-guide/pagination.html +++ /dev/null @@ -1,373 +0,0 @@ - - - - - Pagination - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    pagination.py

    -

    Pagination

    -
    -

    Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.

    -

    Django documentation

    -
    -

    REST framework includes a PaginationSerializer class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.

    -

    Paginating basic data

    -

    Let's start by taking a look at an example from the Django documentation.

    -
    from django.core.paginator import Paginator
    -
    -objects = ['john', 'paul', 'george', 'ringo']
    -paginator = Paginator(objects, 2)
    -page = paginator.page(1)
    -page.object_list
    -# ['john', 'paul']
    -
    -

    At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.

    -
    from rest_framework.pagination import PaginationSerializer
    -
    -serializer = PaginationSerializer(instance=page)
    -serializer.data
    -# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
    -
    -

    The context argument of the PaginationSerializer class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.

    -
    request = RequestFactory().get('/foobar')
    -serializer = PaginationSerializer(instance=page, context={'request': request})
    -serializer.data
    -# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
    -
    -

    We could now return that data in a Response object, and it would be rendered into the correct media type.

    -

    Paginating QuerySets

    -

    Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.

    -

    We can do this using the object_serializer_class attribute on the inner Meta class of the pagination serializer. For example.

    -
    class UserSerializer(serializers.ModelSerializer):
    -    """
    -    Serializes user querysets.
    -    """
    -    class Meta:
    -        model = User
    -        fields = ('username', 'email')
    -
    -class PaginatedUserSerializer(pagination.PaginationSerializer):
    -    """
    -    Serializes page objects of user querysets.
    -    """
    -    class Meta:
    -        object_serializer_class = UserSerializer
    -
    -

    We could now use our pagination serializer in a view like this.

    -
    @api_view('GET')
    -def user_list(request):
    -    queryset = User.objects.all()
    -    paginator = Paginator(queryset, 20)
    -
    -    page = request.QUERY_PARAMS.get('page')
    -    try:
    -        users = paginator.page(page)
    -    except PageNotAnInteger:
    -        # If page is not an integer, deliver first page.
    -        users = paginator.page(1)
    -    except EmptyPage:
    -        # If page is out of range (e.g. 9999),
    -        # deliver last page of results.
    -        users = paginator.page(paginator.num_pages)
    -
    -    serializer_context = {'request': request}
    -    serializer = PaginatedUserSerializer(users,
    -                                         context=serializer_context)
    -    return Response(serializer.data)
    -
    -

    Pagination in the generic views

    -

    The generic class based views ListAPIView and ListCreateAPIView provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.

    -

    The default pagination style may be set globally, using the DEFAULT_PAGINATION_SERIALIZER_CLASS, PAGINATE_BY, PAGINATE_BY_PARAM, and MAX_PAGINATE_BY settings. For example.

    -
    REST_FRAMEWORK = {
    -    'PAGINATE_BY': 10,                 # Default to 10
    -    'PAGINATE_BY_PARAM': 'page_size',  # Allow client to override, using `?page_size=xxx`.
    -    'MAX_PAGINATE_BY': 100             # Maximum limit allowed when using `?page_size=xxx`.
    -}
    -
    -

    You can also set the pagination style on a per-view basis, using the ListAPIView generic class-based view.

    -
    class PaginatedListView(ListAPIView):
    -    queryset = ExampleModel.objects.all()
    -    serializer_class = ExampleModelSerializer
    -    paginate_by = 10
    -    paginate_by_param = 'page_size'
    -    max_paginate_by = 100
    -
    -

    Note that using a paginate_by value of None will turn off pagination for the view. -Note if you use the PAGINATE_BY_PARAM settings, you also have to set the paginate_by_param attribute in your view to None in order to turn off pagination for those requests that contain the paginate_by_param parameter.

    -

    For more complex requirements such as serialization that differs depending on the requested media type you can override the .get_paginate_by() and .get_pagination_serializer_class() methods.

    -
    -

    Custom pagination serializers

    -

    To create a custom pagination serializer class you should override pagination.BasePaginationSerializer and set the fields that you want the serializer to return.

    -

    You can also override the name used for the object list field, by setting the results_field attribute, which defaults to 'results'.

    -

    Example

    -

    For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.

    -
    from rest_framework import pagination
    -from rest_framework import serializers
    -
    -class LinksSerializer(serializers.Serializer):
    -    next = pagination.NextPageField(source='*')
    -    prev = pagination.PreviousPageField(source='*')
    -
    -class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    -    links = LinksSerializer(source='*')  # Takes the page object as the source
    -    total_results = serializers.Field(source='paginator.count')
    -
    -    results_field = 'objects'
    -
    -

    Using your custom pagination serializer

    -

    To have your custom pagination serializer be used by default, use the DEFAULT_PAGINATION_SERIALIZER_CLASS setting:

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_PAGINATION_SERIALIZER_CLASS':
    -        'example_app.pagination.CustomPaginationSerializer',
    -}
    -
    -

    Alternatively, to set your custom pagination serializer on a per-view basis, use the pagination_serializer_class attribute on a generic class based view:

    -
    class PaginatedListView(generics.ListAPIView):
    -    model = ExampleModel
    -    pagination_serializer_class = CustomPaginationSerializer
    -    paginate_by = 10
    -
    -

    Third party packages

    -

    The following third party packages are also available.

    -

    DRF-extensions

    -

    The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html new file mode 100644 index 000000000..95173edb8 --- /dev/null +++ b/api-guide/pagination/index.html @@ -0,0 +1,581 @@ + + + + + + + Pagination - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + pagination.py + + + + +

    Pagination

    +
    +

    Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.

    +

    Django documentation

    +
    +

    REST framework includes a PaginationSerializer class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.

    +

    Paginating basic data

    +

    Let's start by taking a look at an example from the Django documentation.

    +
    from django.core.paginator import Paginator
    +
    +objects = ['john', 'paul', 'george', 'ringo']
    +paginator = Paginator(objects, 2)
    +page = paginator.page(1)
    +page.object_list
    +# ['john', 'paul']
    +
    +

    At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.

    +
    from rest_framework.pagination import PaginationSerializer
    +
    +serializer = PaginationSerializer(instance=page)
    +serializer.data
    +# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
    +
    +

    The context argument of the PaginationSerializer class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.

    +
    request = RequestFactory().get('/foobar')
    +serializer = PaginationSerializer(instance=page, context={'request': request})
    +serializer.data
    +# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
    +
    +

    We could now return that data in a Response object, and it would be rendered into the correct media type.

    +

    Paginating QuerySets

    +

    Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.

    +

    We can do this using the object_serializer_class attribute on the inner Meta class of the pagination serializer. For example.

    +
    class UserSerializer(serializers.ModelSerializer):
    +    """
    +    Serializes user querysets.
    +    """
    +    class Meta:
    +        model = User
    +        fields = ('username', 'email')
    +
    +class PaginatedUserSerializer(pagination.PaginationSerializer):
    +    """
    +    Serializes page objects of user querysets.
    +    """
    +    class Meta:
    +        object_serializer_class = UserSerializer
    +
    +

    We could now use our pagination serializer in a view like this.

    +
    @api_view('GET')
    +def user_list(request):
    +    queryset = User.objects.all()
    +    paginator = Paginator(queryset, 20)
    +
    +    page = request.QUERY_PARAMS.get('page')
    +    try:
    +        users = paginator.page(page)
    +    except PageNotAnInteger:
    +        # If page is not an integer, deliver first page.
    +        users = paginator.page(1)
    +    except EmptyPage:
    +        # If page is out of range (e.g. 9999),
    +        # deliver last page of results.
    +        users = paginator.page(paginator.num_pages)
    +
    +    serializer_context = {'request': request}
    +    serializer = PaginatedUserSerializer(users,
    +                                         context=serializer_context)
    +    return Response(serializer.data)
    +
    +

    Pagination in the generic views

    +

    The generic class based views ListAPIView and ListCreateAPIView provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.

    +

    The default pagination style may be set globally, using the DEFAULT_PAGINATION_SERIALIZER_CLASS, PAGINATE_BY, PAGINATE_BY_PARAM, and MAX_PAGINATE_BY settings. For example.

    +
    REST_FRAMEWORK = {
    +    'PAGINATE_BY': 10,                 # Default to 10
    +    'PAGINATE_BY_PARAM': 'page_size',  # Allow client to override, using `?page_size=xxx`.
    +    'MAX_PAGINATE_BY': 100             # Maximum limit allowed when using `?page_size=xxx`.
    +}
    +
    +

    You can also set the pagination style on a per-view basis, using the ListAPIView generic class-based view.

    +
    class PaginatedListView(ListAPIView):
    +    queryset = ExampleModel.objects.all()
    +    serializer_class = ExampleModelSerializer
    +    paginate_by = 10
    +    paginate_by_param = 'page_size'
    +    max_paginate_by = 100
    +
    +

    Note that using a paginate_by value of None will turn off pagination for the view. +Note if you use the PAGINATE_BY_PARAM settings, you also have to set the paginate_by_param attribute in your view to None in order to turn off pagination for those requests that contain the paginate_by_param parameter.

    +

    For more complex requirements such as serialization that differs depending on the requested media type you can override the .get_paginate_by() and .get_pagination_serializer_class() methods.

    +
    +

    Custom pagination serializers

    +

    To create a custom pagination serializer class you should override pagination.BasePaginationSerializer and set the fields that you want the serializer to return.

    +

    You can also override the name used for the object list field, by setting the results_field attribute, which defaults to 'results'.

    +

    Example

    +

    For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.

    +
    from rest_framework import pagination
    +from rest_framework import serializers
    +
    +class LinksSerializer(serializers.Serializer):
    +    next = pagination.NextPageField(source='*')
    +    prev = pagination.PreviousPageField(source='*')
    +
    +class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    +    links = LinksSerializer(source='*')  # Takes the page object as the source
    +    total_results = serializers.Field(source='paginator.count')
    +
    +    results_field = 'objects'
    +
    +

    Using your custom pagination serializer

    +

    To have your custom pagination serializer be used by default, use the DEFAULT_PAGINATION_SERIALIZER_CLASS setting:

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_PAGINATION_SERIALIZER_CLASS':
    +        'example_app.pagination.CustomPaginationSerializer',
    +}
    +
    +

    Alternatively, to set your custom pagination serializer on a per-view basis, use the pagination_serializer_class attribute on a generic class based view:

    +
    class PaginatedListView(generics.ListAPIView):
    +    model = ExampleModel
    +    pagination_serializer_class = CustomPaginationSerializer
    +    paginate_by = 10
    +
    +

    Third party packages

    +

    The following third party packages are also available.

    +

    DRF-extensions

    +

    The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/parsers.html b/api-guide/parsers.html deleted file mode 100644 index 125c3b36d..000000000 --- a/api-guide/parsers.html +++ /dev/null @@ -1,379 +0,0 @@ - - - - - Parsers - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    parsers.py

    -

    Parsers

    -
    -

    Machine interacting web services tend to use more -structured formats for sending data than form-encoded, since they're -sending more complex data than simple forms

    -

    — Malcom Tredinnick, Django developers group

    -
    -

    REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.

    -

    How the parser is determined

    -

    The set of valid parsers for a view is always defined as a list of classes. When either request.DATA or request.FILES is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.

    -
    -

    Note: When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request.

    -

    If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded', which may not be what you wanted.

    -

    As an example, if you are sending json encoded data using jQuery with the .ajax() method, you should make sure to include the contentType: 'application/json' setting.

    -
    -

    Setting the parsers

    -

    The default set of parsers may be set globally, using the DEFAULT_PARSER_CLASSES setting. For example, the following settings would allow requests with YAML content.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_PARSER_CLASSES': (
    -        'rest_framework.parsers.YAMLParser',
    -    )
    -}
    -
    -

    You can also set the parsers used for an individual view, or viewset, -using the APIView class based views.

    -
    from rest_framework.parsers import YAMLParser
    -from rest_framework.response import Response
    -from rest_framework.views import APIView
    -
    -class ExampleView(APIView):
    -    """
    -    A view that can accept POST requests with YAML content.
    -    """
    -    parser_classes = (YAMLParser,)
    -
    -    def post(self, request, format=None):
    -        return Response({'received data': request.DATA})
    -
    -

    Or, if you're using the @api_view decorator with function based views.

    -
    @api_view(['POST'])
    -@parser_classes((YAMLParser,))
    -def example_view(request, format=None):
    -    """
    -    A view that can accept POST requests with YAML content.
    -    """
    -    return Response({'received data': request.DATA})
    -
    -
    -

    API Reference

    -

    JSONParser

    -

    Parses JSON request content.

    -

    .media_type: application/json

    -

    YAMLParser

    -

    Parses YAML request content.

    -

    Requires the pyyaml package to be installed.

    -

    .media_type: application/yaml

    -

    XMLParser

    -

    Parses REST framework's default style of XML request content.

    -

    Note that the XML markup language is typically used as the base language for more strictly defined domain-specific languages, such as RSS, Atom, and XHTML.

    -

    If you are considering using XML for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.

    -

    Requires the defusedxml package to be installed.

    -

    .media_type: application/xml

    -

    FormParser

    -

    Parses HTML form content. request.DATA will be populated with a QueryDict of data, request.FILES will be populated with an empty QueryDict of data.

    -

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    -

    .media_type: application/x-www-form-urlencoded

    -

    MultiPartParser

    -

    Parses multipart HTML form content, which supports file uploads. Both request.DATA and request.FILES will be populated with a QueryDict.

    -

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    -

    .media_type: multipart/form-data

    -

    FileUploadParser

    -

    Parses raw file upload content. The request.DATA property will be an empty QueryDict, and request.FILES will be a dictionary with a single key 'file' containing the uploaded file.

    -

    If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

    -

    .media_type: */*

    -
    Notes:
    -
      -
    • The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser parser instead.
    • -
    • Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view.
    • -
    • FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details.
    • -
    -
    Basic usage example:
    -
    class FileUploadView(views.APIView):
    -    parser_classes = (FileUploadParser,)
    -
    -    def put(self, request, filename, format=None):
    -        file_obj = request.FILES['file']
    -        # ...
    -        # do some staff with uploaded file
    -        # ...
    -        return Response(status=204)
    -
    -
    -

    Custom parsers

    -

    To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method.

    -

    The method should return the data that will be used to populate the request.DATA property.

    -

    The arguments passed to .parse() are:

    -

    stream

    -

    A stream-like object representing the body of the request.

    -

    media_type

    -

    Optional. If provided, this is the media type of the incoming request content.

    -

    Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "text/plain; charset=utf-8".

    -

    parser_context

    -

    Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.

    -

    By default this will include the following keys: view, request, args, kwargs.

    -

    Example

    -

    The following is an example plaintext parser that will populate the request.DATA property with a string representing the body of the request.

    -
    class PlainTextParser(BaseParser):
    -"""
    -Plain text parser.
    -"""
    -
    -media_type = 'text/plain'
    -
    -def parse(self, stream, media_type=None, parser_context=None):
    -    """
    -    Simply return a string representing the body of the request.
    -    """
    -    return stream.read()
    -
    -
    -

    Third party packages

    -

    The following third party packages are also available.

    -

    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.

    -

    CamelCase JSON

    -

    djangorestframework-camel-case 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 Vitaly Babiy.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html new file mode 100644 index 000000000..b606f6faf --- /dev/null +++ b/api-guide/parsers/index.html @@ -0,0 +1,621 @@ + + + + + + + Parsers - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + parsers.py + + + + +

    Parsers

    +
    +

    Machine interacting web services tend to use more +structured formats for sending data than form-encoded, since they're +sending more complex data than simple forms

    +

    — Malcom Tredinnick, Django developers group

    +
    +

    REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.

    +

    How the parser is determined

    +

    The set of valid parsers for a view is always defined as a list of classes. When either request.DATA or request.FILES is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.

    +
    +

    Note: When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request.

    +

    If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded', which may not be what you wanted.

    +

    As an example, if you are sending json encoded data using jQuery with the .ajax() method, you should make sure to include the contentType: 'application/json' setting.

    +
    +

    Setting the parsers

    +

    The default set of parsers may be set globally, using the DEFAULT_PARSER_CLASSES setting. For example, the following settings would allow requests with YAML content.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_PARSER_CLASSES': (
    +        'rest_framework.parsers.YAMLParser',
    +    )
    +}
    +
    +

    You can also set the parsers used for an individual view, or viewset, +using the APIView class based views.

    +
    from rest_framework.parsers import YAMLParser
    +from rest_framework.response import Response
    +from rest_framework.views import APIView
    +
    +class ExampleView(APIView):
    +    """
    +    A view that can accept POST requests with YAML content.
    +    """
    +    parser_classes = (YAMLParser,)
    +
    +    def post(self, request, format=None):
    +        return Response({'received data': request.DATA})
    +
    +

    Or, if you're using the @api_view decorator with function based views.

    +
    @api_view(['POST'])
    +@parser_classes((YAMLParser,))
    +def example_view(request, format=None):
    +    """
    +    A view that can accept POST requests with YAML content.
    +    """
    +    return Response({'received data': request.DATA})
    +
    +
    +

    API Reference

    +

    JSONParser

    +

    Parses JSON request content.

    +

    .media_type: application/json

    +

    YAMLParser

    +

    Parses YAML request content.

    +

    Requires the pyyaml package to be installed.

    +

    .media_type: application/yaml

    +

    XMLParser

    +

    Parses REST framework's default style of XML request content.

    +

    Note that the XML markup language is typically used as the base language for more strictly defined domain-specific languages, such as RSS, Atom, and XHTML.

    +

    If you are considering using XML for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.

    +

    Requires the defusedxml package to be installed.

    +

    .media_type: application/xml

    +

    FormParser

    +

    Parses HTML form content. request.DATA will be populated with a QueryDict of data, request.FILES will be populated with an empty QueryDict of data.

    +

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    +

    .media_type: application/x-www-form-urlencoded

    +

    MultiPartParser

    +

    Parses multipart HTML form content, which supports file uploads. Both request.DATA and request.FILES will be populated with a QueryDict.

    +

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    +

    .media_type: multipart/form-data

    +

    FileUploadParser

    +

    Parses raw file upload content. The request.DATA property will be an empty QueryDict, and request.FILES will be a dictionary with a single key 'file' containing the uploaded file.

    +

    If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

    +

    .media_type: */*

    +
    Notes:
    +
      +
    • The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser parser instead.
    • +
    • Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view.
    • +
    • FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details.
    • +
    +
    Basic usage example:
    +
    class FileUploadView(views.APIView):
    +    parser_classes = (FileUploadParser,)
    +
    +    def put(self, request, filename, format=None):
    +        file_obj = request.FILES['file']
    +        # ...
    +        # do some staff with uploaded file
    +        # ...
    +        return Response(status=204)
    +
    +
    +

    Custom parsers

    +

    To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method.

    +

    The method should return the data that will be used to populate the request.DATA property.

    +

    The arguments passed to .parse() are:

    +

    stream

    +

    A stream-like object representing the body of the request.

    +

    media_type

    +

    Optional. If provided, this is the media type of the incoming request content.

    +

    Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "text/plain; charset=utf-8".

    +

    parser_context

    +

    Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.

    +

    By default this will include the following keys: view, request, args, kwargs.

    +

    Example

    +

    The following is an example plaintext parser that will populate the request.DATA property with a string representing the body of the request.

    +
    class PlainTextParser(BaseParser):
    +"""
    +Plain text parser.
    +"""
    +
    +media_type = 'text/plain'
    +
    +def parse(self, stream, media_type=None, parser_context=None):
    +    """
    +    Simply return a string representing the body of the request.
    +    """
    +    return stream.read()
    +
    +
    +

    Third party packages

    +

    The following third party packages are also available.

    +

    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.

    +

    CamelCase JSON

    +

    djangorestframework-camel-case 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 Vitaly Babiy.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/permissions.html b/api-guide/permissions.html deleted file mode 100644 index 70d706044..000000000 --- a/api-guide/permissions.html +++ /dev/null @@ -1,429 +0,0 @@ - - - - - Permissions - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    permissions.py

    -

    Permissions

    -
    -

    Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.

    -

    Apple Developer Documentation

    -
    -

    Together with authentication and throttling, permissions determine whether a request should be granted or denied access.

    -

    Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.

    -

    How permissions are determined

    -

    Permissions in REST framework are always defined as a list of permission classes.

    -

    Before running the main body of the view each permission in the list is checked. -If any permission check fails an exceptions.PermissionDenied exception will be raised, and the main body of the view will not run.

    -

    Object level permissions

    -

    REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.

    -

    Object level permissions are run by REST framework's generic views when .get_object() is called. -As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object.

    -

    If you're writing your own views and want to enforce object level permissions, -or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.

    -

    This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions.

    -

    For example:

    -
    def get_object(self):
    -    obj = get_object_or_404(self.get_queryset())
    -    self.check_object_permissions(self.request, obj)
    -    return obj
    -
    -

    Limitations of object level permissions

    -

    For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.

    -

    Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.

    -

    Setting the permission policy

    -

    The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_PERMISSION_CLASSES': (
    -        'rest_framework.permissions.IsAuthenticated',
    -    )
    -}
    -
    -

    If not specified, this setting defaults to allowing unrestricted access:

    -
    'DEFAULT_PERMISSION_CLASSES': (
    -   'rest_framework.permissions.AllowAny',
    -)
    -
    -

    You can also set the authentication policy on a per-view, or per-viewset basis, -using the APIView class based views.

    -
    from rest_framework.permissions import IsAuthenticated
    -from rest_framework.response import Response
    -from rest_framework.views import APIView
    -
    -class ExampleView(APIView):
    -    permission_classes = (IsAuthenticated,)
    -
    -    def get(self, request, format=None):
    -        content = {
    -            'status': 'request was permitted'
    -        }
    -        return Response(content)
    -
    -

    Or, if you're using the @api_view decorator with function based views.

    -
    @api_view('GET')
    -@permission_classes((IsAuthenticated, ))
    -def example_view(request, format=None):
    -    content = {
    -        'status': 'request was permitted'
    -    }
    -    return Response(content)
    -
    -
    -

    API Reference

    -

    AllowAny

    -

    The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.

    -

    This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

    -

    IsAuthenticated

    -

    The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise.

    -

    This permission is suitable if you want your API to only be accessible to registered users.

    -

    IsAdminUser

    -

    The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.

    -

    This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.

    -

    IsAuthenticatedOrReadOnly

    -

    The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GET, HEAD or OPTIONS.

    -

    This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.

    -

    DjangoModelPermissions

    -

    This permission class ties into Django's standard django.contrib.auth model permissions. This permission must only be applied to views that has a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.

    -
      -
    • POST requests require the user to have the add permission on the model.
    • -
    • PUT and PATCH requests require the user to have the change permission on the model.
    • -
    • DELETE requests require the user to have the delete permission on the model.
    • -
    -

    The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests.

    -

    To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details.

    -

    Using with views that do not include a queryset attribute.

    -

    If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example:

    -
    queryset = User.objects.none()  # Required for DjangoModelPermissions
    -
    -

    DjangoModelPermissionsOrAnonReadOnly

    -

    Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.

    -

    DjangoObjectPermissions

    -

    This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian.

    -

    As with DjangoModelPermissions, this permission must only be applied to views that have a .queryset property. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned.

    -
      -
    • POST requests require the user to have the add permission on the model instance.
    • -
    • PUT and PATCH requests require the user to have the change permission on the model instance.
    • -
    • DELETE requests require the user to have the delete permission on the model instance.
    • -
    -

    Note that DjangoObjectPermissions does not require the django-guardian package, and should support other object-level backends equally well.

    -

    As with DjangoModelPermissions you can use custom model permissions by overriding DjangoModelPermissions and setting the .perms_map property. Refer to the source code for details. Note that if you add a custom view permission for GET, HEAD and OPTIONS requests, you'll probably also want to consider adding the DjangoObjectPermissionsFilter class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.

    -

    TokenHasReadWriteScope

    -

    This permission class is intended for use with either of the OAuthAuthentication and OAuth2Authentication classes, and ties into the scoping that their backends provide.

    -

    Requests with a safe methods of GET, OPTIONS or HEAD will be allowed if the authenticated token has read permission.

    -

    Requests for POST, PUT, PATCH and DELETE will be allowed if the authenticated token has write permission.

    -

    This permission class relies on the implementations of the django-oauth-plus and django-oauth2-provider libraries, which both provide limited support for controlling the scope of access tokens:

    -
      -
    • django-oauth-plus: Tokens are associated with a Resource class which has a name, url and is_readonly properties.
    • -
    • django-oauth2-provider: Tokens are associated with a bitwise scope attribute, that defaults to providing bitwise values for read and/or write.
    • -
    -

    If you require more advanced scoping for your API, such as restricting tokens to accessing a subset of functionality of your API then you will need to provide a custom permission class. See the source of the django-oauth-plus or django-oauth2-provider package for more details on scoping token access.

    -
    -

    Custom permissions

    -

    To implement a custom permission, override BasePermission and implement either, or both, of the following methods:

    -
      -
    • .has_permission(self, request, view)
    • -
    • .has_object_permission(self, request, view, obj)
    • -
    -

    The methods should return True if the request should be granted access, and False otherwise.

    -

    If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS, which is a tuple containing 'GET', 'OPTIONS' and 'HEAD'. For example:

    -
    if request.method in permissions.SAFE_METHODS:
    -    # Check permissions for read-only request
    -else:
    -    # Check permissions for write request
    -
    -
    -

    Note: In versions 2.0 and 2.1, the signature for the permission checks always included an optional obj parameter, like so: .has_permission(self, request, view, obj=None). The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.

    -

    As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a PendingDeprecationWarning, which is silent by default. In 2.3 this will be escalated to a DeprecationWarning, and in 2.4 the old-style signature will be removed.

    -

    For more details see the 2.2 release announcement.

    -
    -

    Examples

    -

    The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.

    -
    from rest_framework import permissions
    -
    -class BlacklistPermission(permissions.BasePermission):
    -    """
    -    Global permission check for blacklisted IPs.
    -    """
    -
    -    def has_permission(self, request, view):
    -        ip_addr = request.META['REMOTE_ADDR']
    -        blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
    -        return not blacklisted
    -
    -

    As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:

    -
    class IsOwnerOrReadOnly(permissions.BasePermission):
    -    """
    -    Object-level permission to only allow owners of an object to edit it.
    -    Assumes the model instance has an `owner` attribute.
    -    """
    -
    -    def has_object_permission(self, request, view, obj):
    -        # Read permissions are allowed to any request,
    -        # so we'll always allow GET, HEAD or OPTIONS requests.
    -        if request.method in permissions.SAFE_METHODS:            
    -            return True
    -
    -        # Instance must have an attribute named `owner`.
    -        return obj.owner == request.user
    -
    -

    Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return.

    -

    Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.

    -
    -

    Third party packages

    -

    The following third party packages are also available.

    -

    DRF Any Permissions

    -

    The DRF Any Permissions packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.

    -

    Composed Permissions

    -

    The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.

    -

    REST Condition

    -

    The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/permissions/index.html b/api-guide/permissions/index.html new file mode 100644 index 000000000..85b5985c0 --- /dev/null +++ b/api-guide/permissions/index.html @@ -0,0 +1,673 @@ + + + + + + + Permissions - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + + + permissions.py + + + + +

    Permissions

    +
    +

    Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.

    +

    Apple Developer Documentation

    +
    +

    Together with authentication and throttling, permissions determine whether a request should be granted or denied access.

    +

    Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.

    +

    How permissions are determined

    +

    Permissions in REST framework are always defined as a list of permission classes.

    +

    Before running the main body of the view each permission in the list is checked. +If any permission check fails an exceptions.PermissionDenied exception will be raised, and the main body of the view will not run.

    +

    Object level permissions

    +

    REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.

    +

    Object level permissions are run by REST framework's generic views when .get_object() is called. +As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object.

    +

    If you're writing your own views and want to enforce object level permissions, +or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.

    +

    This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions.

    +

    For example:

    +
    def get_object(self):
    +    obj = get_object_or_404(self.get_queryset())
    +    self.check_object_permissions(self.request, obj)
    +    return obj
    +
    +

    Limitations of object level permissions

    +

    For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.

    +

    Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.

    +

    Setting the permission policy

    +

    The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_PERMISSION_CLASSES': (
    +        'rest_framework.permissions.IsAuthenticated',
    +    )
    +}
    +
    +

    If not specified, this setting defaults to allowing unrestricted access:

    +
    'DEFAULT_PERMISSION_CLASSES': (
    +   'rest_framework.permissions.AllowAny',
    +)
    +
    +

    You can also set the authentication policy on a per-view, or per-viewset basis, +using the APIView class based views.

    +
    from rest_framework.permissions import IsAuthenticated
    +from rest_framework.response import Response
    +from rest_framework.views import APIView
    +
    +class ExampleView(APIView):
    +    permission_classes = (IsAuthenticated,)
    +
    +    def get(self, request, format=None):
    +        content = {
    +            'status': 'request was permitted'
    +        }
    +        return Response(content)
    +
    +

    Or, if you're using the @api_view decorator with function based views.

    +
    @api_view('GET')
    +@permission_classes((IsAuthenticated, ))
    +def example_view(request, format=None):
    +    content = {
    +        'status': 'request was permitted'
    +    }
    +    return Response(content)
    +
    +
    +

    API Reference

    +

    AllowAny

    +

    The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.

    +

    This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

    +

    IsAuthenticated

    +

    The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise.

    +

    This permission is suitable if you want your API to only be accessible to registered users.

    +

    IsAdminUser

    +

    The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.

    +

    This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.

    +

    IsAuthenticatedOrReadOnly

    +

    The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GET, HEAD or OPTIONS.

    +

    This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.

    +

    DjangoModelPermissions

    +

    This permission class ties into Django's standard django.contrib.auth model permissions. This permission must only be applied to views that has a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.

    +
      +
    • POST requests require the user to have the add permission on the model.
    • +
    • PUT and PATCH requests require the user to have the change permission on the model.
    • +
    • DELETE requests require the user to have the delete permission on the model.
    • +
    +

    The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests.

    +

    To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details.

    +

    Using with views that do not include a queryset attribute.

    +

    If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example:

    +
    queryset = User.objects.none()  # Required for DjangoModelPermissions
    +
    +

    DjangoModelPermissionsOrAnonReadOnly

    +

    Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.

    +

    DjangoObjectPermissions

    +

    This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian.

    +

    As with DjangoModelPermissions, this permission must only be applied to views that have a .queryset property. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned.

    +
      +
    • POST requests require the user to have the add permission on the model instance.
    • +
    • PUT and PATCH requests require the user to have the change permission on the model instance.
    • +
    • DELETE requests require the user to have the delete permission on the model instance.
    • +
    +

    Note that DjangoObjectPermissions does not require the django-guardian package, and should support other object-level backends equally well.

    +

    As with DjangoModelPermissions you can use custom model permissions by overriding DjangoModelPermissions and setting the .perms_map property. Refer to the source code for details.

    +
    +

    Note: If you need object level view permissions for GET, HEAD and OPTIONS requests, you'll want to consider also adding the DjangoObjectPermissionsFilter class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.

    +
    +

    TokenHasReadWriteScope

    +

    This permission class is intended for use with either of the OAuthAuthentication and OAuth2Authentication classes, and ties into the scoping that their backends provide.

    +

    Requests with a safe methods of GET, OPTIONS or HEAD will be allowed if the authenticated token has read permission.

    +

    Requests for POST, PUT, PATCH and DELETE will be allowed if the authenticated token has write permission.

    +

    This permission class relies on the implementations of the django-oauth-plus and django-oauth2-provider libraries, which both provide limited support for controlling the scope of access tokens:

    +
      +
    • django-oauth-plus: Tokens are associated with a Resource class which has a name, url and is_readonly properties.
    • +
    • django-oauth2-provider: Tokens are associated with a bitwise scope attribute, that defaults to providing bitwise values for read and/or write.
    • +
    +

    If you require more advanced scoping for your API, such as restricting tokens to accessing a subset of functionality of your API then you will need to provide a custom permission class. See the source of the django-oauth-plus or django-oauth2-provider package for more details on scoping token access.

    +
    +

    Custom permissions

    +

    To implement a custom permission, override BasePermission and implement either, or both, of the following methods:

    +
      +
    • .has_permission(self, request, view)
    • +
    • .has_object_permission(self, request, view, obj)
    • +
    +

    The methods should return True if the request should be granted access, and False otherwise.

    +

    If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS, which is a tuple containing 'GET', 'OPTIONS' and 'HEAD'. For example:

    +
    if request.method in permissions.SAFE_METHODS:
    +    # Check permissions for read-only request
    +else:
    +    # Check permissions for write request
    +
    +
    +

    Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj). If you are using the generic views then this will be handled for you by default.

    +
    +

    Examples

    +

    The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.

    +
    from rest_framework import permissions
    +
    +class BlacklistPermission(permissions.BasePermission):
    +    """
    +    Global permission check for blacklisted IPs.
    +    """
    +
    +    def has_permission(self, request, view):
    +        ip_addr = request.META['REMOTE_ADDR']
    +        blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
    +        return not blacklisted
    +
    +

    As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:

    +
    class IsOwnerOrReadOnly(permissions.BasePermission):
    +    """
    +    Object-level permission to only allow owners of an object to edit it.
    +    Assumes the model instance has an `owner` attribute.
    +    """
    +
    +    def has_object_permission(self, request, view, obj):
    +        # Read permissions are allowed to any request,
    +        # so we'll always allow GET, HEAD or OPTIONS requests.
    +        if request.method in permissions.SAFE_METHODS:
    +            return True
    +
    +        # Instance must have an attribute named `owner`.
    +        return obj.owner == request.user
    +
    +

    Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return.

    +

    Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.

    +
    +

    Third party packages

    +

    The following third party packages are also available.

    +

    DRF Any Permissions

    +

    The DRF Any Permissions packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.

    +

    Composed Permissions

    +

    The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.

    +

    REST Condition

    +

    The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/relations.html b/api-guide/relations/index.html similarity index 55% rename from api-guide/relations.html rename to api-guide/relations/index.html index 64e5d9890..ea662ba88 100644 --- a/api-guide/relations.html +++ b/api-guide/relations/index.html @@ -1,65 +1,74 @@ - - - Serializer relations - Django REST framework - - - - - - - - - - + + + + Serializer relations - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    -

    relations.py

    -

    Serializer relations

    + + + + relations.py + + + + +

    Serializer relations

    Bad programmers worry about the code. Good programmers worry about data structures and their relationships.

    @@ -228,7 +468,7 @@ Good programmers worry about data structures and their relationships.


    API Reference

    In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.

    -
    class Album(models.Model):
    +
    class Album(models.Model):
         album_name = models.CharField(max_length=100)
         artist = models.CharField(max_length=100)
     
    @@ -248,7 +488,7 @@ class Track(models.Model):
     

    RelatedField

    RelatedField may be used to represent the target of the relationship using its __unicode__ method.

    For example, the following serializer.

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         tracks = serializers.RelatedField(many=True)
     
         class Meta:
    @@ -256,7 +496,7 @@ class Track(models.Model):
             fields = ('album_name', 'artist', 'tracks')
     

    Would serialize to the following representation.

    -
    {
    +
    {
         'album_name': 'Things We Lost In The Fire',
         'artist': 'Low',
         'tracks': [
    @@ -275,7 +515,7 @@ class Track(models.Model):
     

    PrimaryKeyRelatedField

    PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key.

    For example, the following serializer:

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
     
         class Meta:
    @@ -283,7 +523,7 @@ class Track(models.Model):
             fields = ('album_name', 'artist', 'tracks')
     

    Would serialize to a representation like this:

    -
    {
    +
    {
         'album_name': 'The Roots',
         'artist': 'Undun',
         'tracks': [
    @@ -304,7 +544,7 @@ class Track(models.Model):
     

    HyperlinkedRelatedField

    HyperlinkedRelatedField may be used to represent the target of the relationship using a hyperlink.

    For example, the following serializer:

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
                                                      view_name='track-detail')
     
    @@ -313,7 +553,7 @@ class Track(models.Model):
             fields = ('album_name', 'artist', 'tracks')
     

    Would serialize to a representation like this:

    -
    {
    +
    {
         'album_name': 'Graceland',
         'artist': 'Paul Simon',
         'tracks': [
    @@ -337,7 +577,7 @@ class Track(models.Model):
     

    SlugRelatedField

    SlugRelatedField may be used to represent the target of the relationship using a field on the target.

    For example, the following serializer:

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         tracks = serializers.SlugRelatedField(many=True, read_only=True,
                                               slug_field='title')
     
    @@ -346,7 +586,7 @@ class Track(models.Model):
             fields = ('album_name', 'artist', 'tracks')
     

    Would serialize to a representation like this:

    -
    {
    +
    {
         'album_name': 'Dear John',
         'artist': 'Loney Dear',
         'tracks': [
    @@ -368,7 +608,7 @@ class Track(models.Model):
     
     

    HyperlinkedIdentityField

    This field can be applied as an identity relationship, such as the 'url' field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:

    -
    class AlbumSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AlbumSerializer(serializers.HyperlinkedModelSerializer):
         track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
     
         class Meta:
    @@ -376,7 +616,7 @@ class Track(models.Model):
             fields = ('album_name', 'artist', 'track_listing')
     

    Would serialize to a representation like this:

    -
    {
    +
    {
         'album_name': 'The Eraser',
         'artist': 'Thom Yorke',
         'track_listing': 'http://www.example.com/api/track_list/12/',
    @@ -385,7 +625,7 @@ class Track(models.Model):
     

    This field is always read-only.

    Arguments:

      -
    • view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this wil be a string with the format <model_name>-detail. required.
    • +
    • view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <model_name>-detail. required.
    • lookup_field - 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 'pk'.
    • format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.
    @@ -395,7 +635,7 @@ class Track(models.Model):

    If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field.

    Example

    For example, the following serializer:

    -
    class TrackSerializer(serializers.ModelSerializer):
    +
    class TrackSerializer(serializers.ModelSerializer):
         class Meta:
             model = Track
             fields = ('order', 'title')
    @@ -408,7 +648,7 @@ class AlbumSerializer(serializers.ModelSerializer):
             fields = ('album_name', 'artist', 'tracks')
     

    Would serialize to a nested representation like this:

    -
    {
    +
    {
         'album_name': 'The Grey Album',
         'artist': 'Danger Mouse',
         'tracks': [
    @@ -424,7 +664,7 @@ class AlbumSerializer(serializers.ModelSerializer):
     

    If you want to implement a read-write relational field, you must also implement the .from_native(self, data) method, and add read_only = False to the class definition.

    Example

    For, example, we could define a relational field, to serialize a track to a custom string representation, using its ordering, title, and duration.

    -
    import time
    +
    import time
     
     class TrackListingField(serializers.RelatedField):
         def to_native(self, value):
    @@ -439,7 +679,7 @@ class AlbumSerializer(serializers.ModelSerializer):
             fields = ('album_name', 'artist', 'tracks')
     

    This custom field would then serialize to the following representation.

    -
    {
    +
    {
         'album_name': 'Sometimes I Wish We Were an Eagle',
         'artist': 'Bill Callahan',
         'tracks': [
    @@ -454,17 +694,17 @@ class AlbumSerializer(serializers.ModelSerializer):
     

    Further notes

    Reverse relations

    Note that reverse relationships are not automatically included by the ModelSerializer and HyperlinkedModelSerializer classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         class Meta:
             fields = ('tracks', ...)
     

    You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. For example:

    -
    class Track(models.Model):
    +
    class Track(models.Model):
         album = models.ForeignKey(Album, related_name='tracks')
         ...
     

    If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the fields argument. For example:

    -
    class AlbumSerializer(serializers.ModelSerializer):
    +
    class AlbumSerializer(serializers.ModelSerializer):
         class Meta:
             fields = ('track_set', ...)
     
    @@ -472,7 +712,7 @@ class AlbumSerializer(serializers.ModelSerializer):

    Generic relationships

    If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.

    For example, given the following model for a tag, which has a generic relationship with other arbitrary models:

    -
    class TaggedItem(models.Model):
    +
    class TaggedItem(models.Model):
         """
         Tags arbitrary model instances using a generic relation.
     
    @@ -487,7 +727,7 @@ class AlbumSerializer(serializers.ModelSerializer):
             return self.tag
     

    And the following two models, which may be have associated tags:

    -
    class Bookmark(models.Model):
    +
    class Bookmark(models.Model):
         """
         A bookmark consists of a URL, and 0 or more descriptive tags.
         """
    @@ -503,7 +743,7 @@ class Note(models.Model):
         tags = GenericRelation(TaggedItem)
     

    We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.

    -
    class TaggedObjectRelatedField(serializers.RelatedField):
    +
    class TaggedObjectRelatedField(serializers.RelatedField):
         """
         A custom field to use for the `tagged_object` generic relationship.
         """
    @@ -511,7 +751,7 @@ class Note(models.Model):
         def to_native(self, value):
             """
             Serialize tagged objects to a simple textual representation.
    -        """                            
    +        """
             if isinstance(value, Bookmark):
                 return 'Bookmark: ' + value.url
             elif isinstance(value, Note):
    @@ -519,11 +759,11 @@ class Note(models.Model):
             raise Exception('Unexpected type of tagged object')
     

    If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_native() method:

    -
        def to_native(self, value):
    +
        def to_native(self, value):
             """
             Serialize bookmark instances using a bookmark serializer,
             and note instances using a note serializer.
    -        """                            
    +        """
             if isinstance(value, Bookmark):
                 serializer = BookmarkSerializer(value)
             elif isinstance(value, Note):
    @@ -542,7 +782,7 @@ class Note(models.Model):
     ManyToManyField with a through model, be sure to set read_only
     to True.

    Advanced Hyperlinked fields

    -

    If you have very specific requirements for the style of your hyperlinked relationships you can override HyperlinkedRelatedField.

    +

    If you have very specific requirements for the style of your hyperlinked relationships you can override HyperlinkedRelatedField.

    There are two methods you'll need to override.

    get_url(self, obj, view_name, request, format)

    This method should return the URL that corresponds to the given object.

    @@ -552,8 +792,8 @@ attributes are not configured to correctly match the URL conf.

    This method should the object that corresponds to the matched URL conf arguments.

    May raise an ObjectDoesNotExist exception.

    Example

    -

    For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:

    -
    class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
    +

    For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:

    +
    class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
         def get_url(self, obj, view_name, request, format):
             kwargs = {'account': obj.account, 'slug': obj.slug}
             return reverse(view_name, kwargs=kwargs, request=request, format=format)
    @@ -576,48 +816,58 @@ They continue to function, but their usage will raise a PendingDeprecation
     

    The null=<bool> flag has been deprecated in favor of the required=<bool> flag. It will continue to function, but will raise a PendingDeprecationWarning.

    In the 2.3 release, these warnings will be escalated to a DeprecationWarning, which is loud by default. In the 2.4 release, these parts of the API will be removed entirely.

    -

    For more details see the 2.2 release announcement.

    +

    For more details see the 2.2 release announcement.


    Third Party Packages

    The following third party packages are also available.

    DRF Nested Routers

    The drf-nested-routers package provides routers and relationship fields for working with nested resources.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/renderers.html b/api-guide/renderers/index.html similarity index 58% rename from api-guide/renderers.html rename to api-guide/renderers/index.html index 3ce83b72d..b29a88bf3 100644 --- a/api-guide/renderers.html +++ b/api-guide/renderers/index.html @@ -1,65 +1,74 @@ - - - Renderers - Django REST framework - - - - - - - - - - + + + + Renderers - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,48 +335,176 @@ a.fusion-poweredby { -->
    -

    renderers.py

    -

    Renderers

    + + + + renderers.py + + + + +

    Renderers

    Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.

    Django documentation

    @@ -236,10 +513,10 @@ a.fusion-poweredby {

    How the renderer is determined

    The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.

    The basic process of content negotiation involves examining the request's Accept 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 http://example.com/api/users_count.json might be an endpoint that always returns JSON data.

    -

    For more information see the documentation on content negotiation.

    +

    For more information see the documentation on content negotiation.

    Setting the renderers

    The default set of renderers may be set globally, using the DEFAULT_RENDERER_CLASSES setting. For example, the following settings would use YAML as the main media type and also include the self describing API.

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         'DEFAULT_RENDERER_CLASSES': (
             'rest_framework.renderers.YAMLRenderer',
             'rest_framework.renderers.BrowsableAPIRenderer',
    @@ -248,7 +525,7 @@ a.fusion-poweredby {
     

    You can also set the renderers used for an individual view, or viewset, using the APIView class based views.

    -
    from django.contrib.auth.models import User
    +
    from django.contrib.auth.models import User
     from rest_framework.renderers import JSONRenderer, YAMLRenderer
     from rest_framework.response import Response
     from rest_framework.views import APIView
    @@ -265,7 +542,7 @@ class UserCountView(APIView):
             return Response(content)
     

    Or, if you're using the @api_view decorator with function based views.

    -
    @api_view(['GET'])
    +
    @api_view(['GET'])
     @renderer_classes((JSONRenderer, JSONPRenderer))
     def user_count_view(request, format=None):
         """
    @@ -283,28 +560,16 @@ def user_count_view(request, format=None):
     

    API Reference

    JSONRenderer

    Renders the request data into JSON, using utf-8 encoding.

    -

    Note that non-ascii characters will be rendered using JSON's \uXXXX character escape. For example:

    -
    {"unicode black star": "\u2605"}
    +

    Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:

    +
    {"unicode black star":"★","value":999}
     

    The client may additionally include an 'indent' media type parameter, in which case the returned JSON will be indented. For example Accept: application/json; indent=4.

    -
    {
    -    "unicode black star": "\u2605"
    +
    {
    +    "unicode black star": "★",
    +    "value": 999
     }
     
    -

    .media_type: application/json

    -

    .format: '.json'

    -

    .charset: None

    -

    UnicodeJSONRenderer

    -

    Renders the request data into JSON, using utf-8 encoding.

    -

    Note that non-ascii characters will not be character escaped. For example:

    -
    {"unicode black star": "★"}
    -
    -

    The client may additionally include an 'indent' media type parameter, in which case the returned JSON will be indented. For example Accept: application/json; indent=4.

    -
    {
    -    "unicode black star": "★"
    -}
    -
    -

    Both the JSONRenderer and UnicodeJSONRenderer styles conform to RFC 4627, and are syntactically valid JSON.

    +

    The default JSON encoding style can be altered using the UNICODE_JSON and COMPACT_JSON settings keys.

    .media_type: application/json

    .format: '.json'

    .charset: None

    @@ -312,26 +577,26 @@ def user_count_view(request, format=None):

    Renders the request data into JSONP. The JSONP media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a JSON response in a javascript callback.

    The javascript callback function must be set by the client including a callback URL query parameter. For example http://example.com/api/users?callback=jsonpCallback. If the callback function is not explicitly set by the client it will default to 'callback'.


    -

    Warning: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of CORS as an alternative to JSONP. See the CORS documentation for more details.

    +

    Warning: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of CORS as an alternative to JSONP. See the CORS documentation for more details.

    The jsonp approach is essentially a browser hack, and is only appropriate for globally readable API endpoints, where GET requests are unauthenticated and do not require any user permissions.


    .media_type: application/javascript

    .format: '.jsonp'

    .charset: utf-8

    YAMLRenderer

    -

    Renders the request data into YAML.

    +

    Renders the request data into YAML.

    Requires the pyyaml package to be installed.

    Note that non-ascii characters will be rendered using \uXXXX character escape. For example:

    -
    unicode black star: "\u2605"
    +
    unicode black star: "\u2605"
     

    .media_type: application/yaml

    .format: '.yaml'

    .charset: utf-8

    UnicodeYAMLRenderer

    -

    Renders the request data into YAML.

    +

    Renders the request data into YAML.

    Requires the pyyaml package to be installed.

    Note that non-ascii characters will not be character escaped. For example:

    -
    unicode black star: ★
    +
    unicode black star: ★
     

    .media_type: application/yaml

    .format: '.yaml'

    @@ -354,7 +619,7 @@ Unlike other renderers, the data passed to the Response does not ne
  • The return result of calling view.get_template_names().
  • An example of a view that uses TemplateHTMLRenderer:

    -
    class UserDetail(generics.RetrieveAPIView):
    +
    class UserDetail(generics.RetrieveAPIView):
         """
         A view that returns a templated HTML representations of a given user.
         """
    @@ -374,9 +639,9 @@ Unlike other renderers, the data passed to the Response does not ne
     

    StaticHTMLRenderer

    A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.

    An example of a view that uses TemplateHTMLRenderer:

    -
    @api_view(('GET',))
    +
    @api_view(('GET',))
     @renderer_classes((StaticHTMLRenderer,))
    -def simple_html_view(request): 
    +def simple_html_view(request):
         data = '<html><body><h1>Hello, world</h1></body></html>'
         return Response(data)
     
    @@ -400,12 +665,12 @@ def simple_html_view(request):

    .template: 'rest_framework/api.html'

    Customizing BrowsableAPIRenderer

    By default the response content will be rendered with the highest priority renderer apart from BrowseableAPIRenderer. 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 get_default_renderer() method. For example:

    -
    class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
    +
    class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
         def get_default_renderer(self, view):
             return JSONRenderer()
     

    MultiPartRenderer

    -

    This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory.

    +

    This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory.

    .media_type: multipart/form-data; boundary=BoUnDaRyStRiNg

    .format: '.multipart'

    .charset: utf-8

    @@ -424,7 +689,7 @@ def simple_html_view(request):

    By default this will include the following keys: view, request, response, args, kwargs.

    Example

    The following is an example plaintext renderer that will return a response with the data parameter as the content of the response.

    -
    from django.utils.encoding import smart_unicode
    +
    from django.utils.encoding import smart_unicode
     from rest_framework import renderers
     
     
    @@ -437,7 +702,7 @@ class PlainTextRenderer(renderers.BaseRenderer):
     

    Setting the character set

    By default renderer classes are assumed to be using the UTF-8 encoding. To use a different encoding, set the charset attribute on the renderer.

    -
    class PlainTextRenderer(renderers.BaseRenderer):
    +
    class PlainTextRenderer(renderers.BaseRenderer):
         media_type = 'text/plain'
         format = 'txt'
         charset = 'iso-8859-1'
    @@ -448,7 +713,7 @@ class PlainTextRenderer(renderers.BaseRenderer):
     

    Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the Response class, with the charset attribute set on the renderer used to determine the encoding.

    If the renderer returns a bytestring representing raw binary content, you should set a charset value of None, which will ensure the Content-Type header of the response will not have a charset value set.

    In some cases you may also want to set the render_style attribute to 'binary'. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.

    -
    class JPEGRenderer(renderers.BaseRenderer):
    +
    class JPEGRenderer(renderers.BaseRenderer):
         media_type = 'image/jpeg'
         format = 'jpg'
         charset = None
    @@ -464,12 +729,12 @@ class PlainTextRenderer(renderers.BaseRenderer):
     
  • Provide either flat or nested representations from the same endpoint, depending on the requested media type.
  • Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
  • Specify multiple types of HTML representation for API clients to use.
  • -
  • Underspecify a renderer's media type, such as using media_type = 'image/*', and use the Accept header to vary the encoding of the response.
  • +
  • Underspecify a renderer's media type, such as using media_type = 'image/*', and use the Accept header to vary the encoding of the response.
  • Varying behaviour by media type

    In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access request.accepted_renderer to determine the negotiated renderer that will be used for the response.

    For example:

    -
    @api_view(('GET',))
    +
    @api_view(('GET',))
     @renderer_classes((TemplateHTMLRenderer, JSONRenderer))
     def list_users(request):
         """
    @@ -494,7 +759,7 @@ def list_users(request):
     

    In some cases you might want a renderer to serve a range of media types. In this case you can underspecify the media types it should respond to, by using a media_type value such as image/*, or */*.

    If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the content_type attribute. For example:

    -
    return Response(data, content_type='image/png')
    +
    return Response(data, content_type='image/png')
     

    Designing your media types

    For the purposes of many Web APIs, simple JSON responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and HATEOAS you'll need to consider the design and usage of your media types in more detail.

    @@ -524,42 +789,52 @@ In this case you can underspecify the media types it should respond to, by using

    djangorestframework-camel-case 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 Vitaly Babiy.

    Pandas (CSV, Excel, PNG)

    Django REST Pandas provides a serializer and renderers that support additional data processing and output via the Pandas DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both .xls and .xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/requests.html b/api-guide/requests.html deleted file mode 100644 index 50f40a539..000000000 --- a/api-guide/requests.html +++ /dev/null @@ -1,321 +0,0 @@ - - - - - Requests - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    request.py

    -

    Requests

    -
    -

    If you're doing REST-based web service stuff ... you should ignore request.POST.

    -

    — Malcom Tredinnick, Django developers group

    -
    -

    REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication.

    -
    -

    Request parsing

    -

    REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.

    -

    .DATA

    -

    request.DATA returns the parsed content of the request body. This is similar to the standard request.POST attribute except that:

    -
      -
    • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
    • -
    • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
    • -
    -

    For more details see the parsers documentation.

    -

    .FILES

    -

    request.FILES returns any uploaded files that may be present in the content of the request body. This is the same as the standard HttpRequest behavior, except that the same flexible request parsing is used for request.DATA.

    -

    For more details see the parsers documentation.

    -

    .QUERY_PARAMS

    -

    request.QUERY_PARAMS is a more correctly named synonym for request.GET.

    -

    For clarity inside your code, we recommend using request.QUERY_PARAMS instead of the usual request.GET, as any HTTP method type may include query parameters.

    -

    .parsers

    -

    The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting.

    -

    You won't typically need to access this property.

    -
    -

    Note: If a client sends malformed content, then accessing request.DATA or request.FILES may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response.

    -

    If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response.

    -
    -

    Authentication

    -

    REST framework provides flexible, per-request authentication, that gives you the ability to:

    -
      -
    • Use different authentication policies for different parts of your API.
    • -
    • Support the use of multiple authentication policies.
    • -
    • Provide both user and token information associated with the incoming request.
    • -
    -

    .user

    -

    request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used.

    -

    If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser.

    -

    For more details see the authentication documentation.

    -

    .auth

    -

    request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.

    -

    If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None.

    -

    For more details see the authentication documentation.

    -

    .authenticators

    -

    The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting.

    -

    You won't typically need to access this property.

    -
    -

    Browser enhancements

    -

    REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms.

    -

    .method

    -

    request.method returns the uppercased string representation of the request's HTTP method.

    -

    Browser-based PUT, PATCH and DELETE forms are transparently supported.

    -

    For more information see the browser enhancements documentation.

    -

    .content_type

    -

    request.content_type, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.

    -

    You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.

    -

    If you do need to access the content type of the request you should use the .content_type property in preference to using request.META.get('HTTP_CONTENT_TYPE'), as it provides transparent support for browser-based non-form content.

    -

    For more information see the browser enhancements documentation.

    -

    .stream

    -

    request.stream returns a stream representing the content of the request body.

    -

    You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.

    -

    If you do need to access the raw content directly, you should use the .stream property in preference to using request.content, as it provides transparent support for browser-based non-form content.

    -

    For more information see the browser enhancements documentation.

    -
    -

    Standard HttpRequest attributes

    -

    As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.

    -

    Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html new file mode 100644 index 000000000..1649b0ba6 --- /dev/null +++ b/api-guide/requests/index.html @@ -0,0 +1,578 @@ + + + + + + + Requests - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + request.py + + + + +

    Requests

    +
    +

    If you're doing REST-based web service stuff ... you should ignore request.POST.

    +

    — Malcom Tredinnick, Django developers group

    +
    +

    REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication.

    +
    +

    Request parsing

    +

    REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.

    +

    .DATA

    +

    request.DATA returns the parsed content of the request body. This is similar to the standard request.POST attribute except that:

    +
      +
    • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
    • +
    • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
    • +
    +

    For more details see the parsers documentation.

    +

    .FILES

    +

    request.FILES returns any uploaded files that may be present in the content of the request body. This is the same as the standard HttpRequest behavior, except that the same flexible request parsing is used for request.DATA.

    +

    For more details see the parsers documentation.

    +

    .QUERY_PARAMS

    +

    request.QUERY_PARAMS is a more correctly named synonym for request.GET.

    +

    For clarity inside your code, we recommend using request.QUERY_PARAMS instead of the usual request.GET, as any HTTP method type may include query parameters.

    +

    .parsers

    +

    The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting.

    +

    You won't typically need to access this property.

    +
    +

    Note: If a client sends malformed content, then accessing request.DATA or request.FILES may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response.

    +

    If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response.

    +
    +

    Content negotiation

    +

    The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.

    +

    .accepted_renderer

    +

    The renderer instance what was selected by the content negotiation stage.

    +

    .accepted_media_type

    +

    A string representing the media type that was accepted by the content negotiation stage.

    +
    +

    Authentication

    +

    REST framework provides flexible, per-request authentication, that gives you the ability to:

    +
      +
    • Use different authentication policies for different parts of your API.
    • +
    • Support the use of multiple authentication policies.
    • +
    • Provide both user and token information associated with the incoming request.
    • +
    +

    .user

    +

    request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used.

    +

    If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser.

    +

    For more details see the authentication documentation.

    +

    .auth

    +

    request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.

    +

    If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None.

    +

    For more details see the authentication documentation.

    +

    .authenticators

    +

    The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting.

    +

    You won't typically need to access this property.

    +
    +

    Browser enhancements

    +

    REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms.

    +

    .method

    +

    request.method returns the uppercased string representation of the request's HTTP method.

    +

    Browser-based PUT, PATCH and DELETE forms are transparently supported.

    +

    For more information see the browser enhancements documentation.

    +

    .content_type

    +

    request.content_type, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.

    +

    You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.

    +

    If you do need to access the content type of the request you should use the .content_type property in preference to using request.META.get('HTTP_CONTENT_TYPE'), as it provides transparent support for browser-based non-form content.

    +

    For more information see the browser enhancements documentation.

    +

    .stream

    +

    request.stream returns a stream representing the content of the request body.

    +

    You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.

    +

    If you do need to access the raw content directly, you should use the .stream property in preference to using request.content, as it provides transparent support for browser-based non-form content.

    +

    For more information see the browser enhancements documentation.

    +
    +

    Standard HttpRequest attributes

    +

    As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.

    +

    Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/responses.html b/api-guide/responses.html deleted file mode 100644 index 5bc21986b..000000000 --- a/api-guide/responses.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - Responses - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    response.py

    -

    Responses

    -
    -

    Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.

    -

    Django documentation

    -
    -

    REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.

    -

    The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.

    -

    There's no requirement for you to use the Response class, you can also return regular HttpResponse or StreamingHttpResponse objects from your views if required. Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.

    -

    Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.

    -
    -

    Creating responses

    -

    Response()

    -

    Signature: Response(data, status=None, template_name=None, headers=None, content_type=None)

    -

    Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.

    -

    The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object.

    -

    You can use REST framework's Serializer classes to perform this data serialization, or use your own custom serialization.

    -

    Arguments:

    -
      -
    • data: The serialized data for the response.
    • -
    • status: A status code for the response. Defaults to 200. See also status codes.
    • -
    • template_name: A template name to use if HTMLRenderer is selected.
    • -
    • headers: A dictionary of HTTP headers to use in the response.
    • -
    • content_type: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.
    • -
    -
    -

    Attributes

    -

    .data

    -

    The unrendered content of a Request object.

    -

    .status_code

    -

    The numeric status code of the HTTP response.

    -

    .content

    -

    The rendered content of the response. The .render() method must have been called before .content can be accessed.

    -

    .template_name

    -

    The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.

    -

    .accepted_renderer

    -

    The renderer instance that will be used to render the response.

    -

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    -

    .accepted_media_type

    -

    The media type that was selected by the content negotiation stage.

    -

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    -

    .renderer_context

    -

    A dictionary of additional context information that will be passed to the renderer's .render() method.

    -

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    -
    -

    Standard HttpResponse attributes

    -

    The Response class extends SimpleTemplateResponse, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:

    -
    response = Response()
    -response['Cache-Control'] = 'no-cache'
    -
    -

    .render()

    -

    Signature: .render()

    -

    As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance.

    -

    You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/responses/index.html b/api-guide/responses/index.html new file mode 100644 index 000000000..a6f946665 --- /dev/null +++ b/api-guide/responses/index.html @@ -0,0 +1,528 @@ + + + + + + + Responses - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + response.py + + + + +

    Responses

    +
    +

    Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.

    +

    Django documentation

    +
    +

    REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.

    +

    The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.

    +

    There's no requirement for you to use the Response class, you can also return regular HttpResponse or StreamingHttpResponse objects from your views if required. Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.

    +

    Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.

    +
    +

    Creating responses

    +

    Response()

    +

    Signature: Response(data, status=None, template_name=None, headers=None, content_type=None)

    +

    Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.

    +

    The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object.

    +

    You can use REST framework's Serializer classes to perform this data serialization, or use your own custom serialization.

    +

    Arguments:

    +
      +
    • data: The serialized data for the response.
    • +
    • status: A status code for the response. Defaults to 200. See also status codes.
    • +
    • template_name: A template name to use if HTMLRenderer is selected.
    • +
    • headers: A dictionary of HTTP headers to use in the response.
    • +
    • content_type: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.
    • +
    +
    +

    Attributes

    +

    .data

    +

    The unrendered content of a Request object.

    +

    .status_code

    +

    The numeric status code of the HTTP response.

    +

    .content

    +

    The rendered content of the response. The .render() method must have been called before .content can be accessed.

    +

    .template_name

    +

    The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.

    +

    .accepted_renderer

    +

    The renderer instance that will be used to render the response.

    +

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    +

    .accepted_media_type

    +

    The media type that was selected by the content negotiation stage.

    +

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    +

    .renderer_context

    +

    A dictionary of additional context information that will be passed to the renderer's .render() method.

    +

    Set automatically by the APIView or @api_view immediately before the response is returned from the view.

    +
    +

    Standard HttpResponse attributes

    +

    The Response class extends SimpleTemplateResponse, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:

    +
    response = Response()
    +response['Cache-Control'] = 'no-cache'
    +
    +

    .render()

    +

    Signature: .render()

    +

    As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance.

    +

    You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/reverse.html b/api-guide/reverse.html deleted file mode 100644 index 48c8b3c51..000000000 --- a/api-guide/reverse.html +++ /dev/null @@ -1,279 +0,0 @@ - - - - - Returning URLs - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - -
    - -
    - - -
    -
    - -
    -

    reverse.py

    -

    Returning URLs

    -
    -

    The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.

    -

    — Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures

    -
    -

    As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as http://example.com/foobar, rather than returning relative URIs, such as /foobar.

    -

    The advantages of doing so are:

    -
      -
    • It's more explicit.
    • -
    • It leaves less work for your API clients.
    • -
    • There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
    • -
    • It makes it easy to do things like markup HTML representations with hyperlinks.
    • -
    -

    REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.

    -

    There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.

    -

    reverse

    -

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

    -

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

    -

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

    -
    from rest_framework.reverse import reverse
    -from rest_framework.views import APIView
    -from django.utils.timezone import now
    -
    -class APIRootView(APIView):
    -    def get(self, request):
    -        year = now().year
    -        data = {
    -            ...
    -            'year-summary-url': reverse('year-summary', args=[year], request=request)
    -        }
    -        return Response(data)
    -
    -

    reverse_lazy

    -

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

    -

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

    -

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

    -
    api_root = reverse_lazy('api-root', request=request)
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/reverse/index.html b/api-guide/reverse/index.html new file mode 100644 index 000000000..2d50b9d89 --- /dev/null +++ b/api-guide/reverse/index.html @@ -0,0 +1,461 @@ + + + + + + + Returning URLs - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + reverse.py + + + + +

    Returning URLs

    +
    +

    The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.

    +

    — Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures

    +
    +

    As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as http://example.com/foobar, rather than returning relative URIs, such as /foobar.

    +

    The advantages of doing so are:

    +
      +
    • It's more explicit.
    • +
    • It leaves less work for your API clients.
    • +
    • There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
    • +
    • It makes it easy to do things like markup HTML representations with hyperlinks.
    • +
    +

    REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.

    +

    There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.

    +

    reverse

    +

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

    +

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

    +

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

    +
    from rest_framework.reverse import reverse
    +from rest_framework.views import APIView
    +from django.utils.timezone import now
    +
    +class APIRootView(APIView):
    +    def get(self, request):
    +        year = now().year
    +        data = {
    +            ...
    +            'year-summary-url': reverse('year-summary', args=[year], request=request)
    +        }
    +        return Response(data)
    +
    +

    reverse_lazy

    +

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

    +

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

    +

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

    +
    api_root = reverse_lazy('api-root', request=request)
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/routers.html b/api-guide/routers/index.html similarity index 52% rename from api-guide/routers.html rename to api-guide/routers/index.html index a578fcfc6..18ad04d54 100644 --- a/api-guide/routers.html +++ b/api-guide/routers/index.html @@ -1,65 +1,74 @@ - - - Routers - Django REST framework - - - - - - - - - - + + + + Routers - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,31 +335,96 @@ a.fusion-poweredby { -->
    -

    routers.py

    -

    Routers

    + + + + routers.py + + + + +

    Routers

    Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.

    Ruby on Rails Documentation

    @@ -219,7 +433,7 @@ a.fusion-poweredby {

    REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

    Usage

    Here's an example of a simple URL conf, that uses SimpleRouter.

    -
    from rest_framework import routers
    +
    from rest_framework import routers
     
     router = routers.SimpleRouter()
     router.register(r'users', UserViewSet)
    @@ -245,14 +459,14 @@ urlpatterns = router.urls
     

    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.
    +
    '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.


    Any methods on the viewset decorated with @detail_route or @list_route will also be routed. For example, given a method like this on the UserViewSet class:

    -
    from myapp.permissions import IsAdminOrIsSelf
    +
    from myapp.permissions import IsAdminOrIsSelf
     from rest_framework.decorators import detail_route
     
     class UserViewSet(ModelViewSet):
    @@ -266,7 +480,7 @@ class UserViewSet(ModelViewSet):
     
    • URL pattern: ^users/{pk}/set_password/$ Name: 'user-set-password'
    -

    For more information see the viewset documentation on marking extra actions for routing.

    +

    For more information see the viewset documentation on marking extra actions for routing.

    API Guide

    SimpleRouter

    This router includes routes for the standard set of list, create, retrieve, update, partial_update and destroy actions. The viewset can also mark additional methods to be routed, using the @detail_route or @list_route decorators.

    @@ -284,11 +498,11 @@ class UserViewSet(ModelViewSet):

    By default the URLs created by SimpleRouter are appended with a trailing slash. This behavior can be modified by setting the trailing_slash argument to False when instantiating the router. For example:

    -
    router = SimpleRouter(trailing_slash=False)
    +
    router = SimpleRouter(trailing_slash=False)
     

    Trailing 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.

    The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the lookup_value_regex attribute on the viewset. For example, you can limit the lookup to valid UUIDs:

    -
    class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    +
    class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
         lookup_field = 'my_model_id'
         lookup_value_regex = '[0-9a-f]{32}'
     
    @@ -308,7 +522,7 @@ This behavior can be modified by setting the trailing_slash argumen

    As with SimpleRouter the trailing slashes on the URL routes can be removed by setting the trailing_slash argument to False when instantiating the router.

    -
    router = DefaultRouter(trailing_slash=False)
    +
    router = DefaultRouter(trailing_slash=False)
     

    Custom Routers

    Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.

    @@ -335,7 +549,7 @@ To route either or both of these decorators, include a DynamicListRouteinitkwargs: A dictionary of any additional arguments that should be passed when instantiating the view.

    Example

    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, DynamicDetailRoute, SimpleRouter
    +
    from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter
     
     class CustomReadOnlyRouter(SimpleRouter):
         """
    @@ -363,7 +577,7 @@ class CustomReadOnlyRouter(SimpleRouter):
     

    Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.

    views.py:

    -
    class UserViewSet(viewsets.ReadOnlyModelViewSet):
    +
    class UserViewSet(viewsets.ReadOnlyModelViewSet):
         """
         A viewset that provides the standard actions
         """
    @@ -382,7 +596,7 @@ class CustomReadOnlyRouter(SimpleRouter):
             return Response([group.name for group in groups])
     

    urls.py:

    -
    router = CustomReadOnlyRouter()
    +
    router = CustomReadOnlyRouter()
     router.register('users', UserViewSet)
     urlpatterns = router.urls
     
    @@ -396,7 +610,7 @@ urlpatterns = router.urls

    For another example of setting the .routes attribute, see the source code for the SimpleRouter class.

    Advanced custom routers

    -

    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.

    +

    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.

    Third Party Packages

    The following third party packages are also available.

    @@ -404,49 +618,59 @@ urlpatterns = router.urls

    The drf-nested-routers package provides routers and relationship fields for working with nested resources.

    wq.db

    The wq.db package provides an advanced Router class (and singleton instance) that extends DefaultRouter with a register_model() API. Much like Django's admin.site.register, the only required argument to app.router.register_model is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration.

    -
    from wq.db.rest import app
    +
    from wq.db.rest import app
     from myapp.models import MyModel
     
     app.router.register_model(MyModel)
     

    DRF-extensions

    The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/serializers.html b/api-guide/serializers/index.html similarity index 62% rename from api-guide/serializers.html rename to api-guide/serializers/index.html index b6ac381a6..237240959 100644 --- a/api-guide/serializers.html +++ b/api-guide/serializers/index.html @@ -1,65 +1,74 @@ - - - Serializers - Django REST framework - - - - - - - - - - + + + + Serializers - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,44 +335,156 @@ a.fusion-poweredby { -->
    + + + + +
  • + Serializers +
  • + + +
  • + Declaring Serializers +
  • + +
  • + Serializing objects +
  • + +
  • + Deserializing objects +
  • + +
  • + Validation +
  • + +
  • + Saving object state +
  • + +
  • + Dealing with nested objects +
  • + +
  • + Dealing with multiple objects +
  • + +
  • + Including extra context +
  • + + + + +
  • + ModelSerializer +
  • + + +
  • + Specifying which fields should be included +
  • + +
  • + Specifying nested serialization +
  • + +
  • + Specifying which fields should be read-only +
  • + +
  • + Specifying which fields should be write-only +
  • + +
  • + Specifying fields explicitly +
  • + +
  • + Relational fields +
  • + +
  • + Inheritance of the 'Meta' class +
  • + + + + +
  • + HyperlinkedModelSerializer +
  • + + +
  • + How hyperlinked views are determined +
  • + +
  • + Overriding the URL field behavior +
  • + + + + +
  • + Advanced serializer usage +
  • + + +
  • + Dynamically modifying fields +
  • + +
  • + Customising the default fields +
  • + + + + +
  • + Third party packages +
  • + + +
  • + MongoengineModelSerializer +
  • + +
  • + GeoFeatureModelSerializer +
  • + +
  • + HStoreSerializer +
  • + + + + + + +
    -

    serializers.py

    -

    Serializers

    + + + + serializers.py + + + + +

    Serializers

    Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it @@ -234,7 +495,7 @@ will take some serious design work.

    REST framework's serializers work very similarly to Django's Form and ModelForm classes. It provides a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.

    Declaring Serializers

    Let's start by creating a simple object we can use for example purposes:

    -
    class Comment(object):
    +
    class Comment(object):
         def __init__(self, email, content, created=None):
             self.email = email
             self.content = content
    @@ -244,7 +505,7 @@ comment = Comment(email='leila@example.com', content='foo bar')
     

    We'll declare a serializer that we can use to serialize and deserialize Comment objects.

    Declaring a serializer looks very similar to declaring a form:

    -
    from rest_framework import serializers
    +
    from rest_framework import serializers
     
     class CommentSerializer(serializers.Serializer):
         email = serializers.EmailField()
    @@ -267,12 +528,12 @@ class CommentSerializer(serializers.Serializer):
     

    The restore_object method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items.

    Serializing objects

    We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class.

    -
    serializer = CommentSerializer(comment)
    +
    serializer = CommentSerializer(comment)
     serializer.data
     # {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
     

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

    -
    from rest_framework.renderers import JSONRenderer
    +
    from rest_framework.renderers import JSONRenderer
     
     json = JSONRenderer().render(serializer.data)
     json
    @@ -281,7 +542,7 @@ json
     

    Customizing field representation

    Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model.

    If you need to customize the serialized value of a particular field, you can do this by creating a transform_<fieldname> method. For example if you needed to render some markdown from a text field:

    -
    description = serializers.CharField()
    +
    description = serializers.CharField()
     description_html = serializers.CharField(source='description', read_only=True)
     
     def transform_description_html(self, obj, value):
    @@ -290,30 +551,30 @@ def transform_description_html(self, obj, value):
     

    These methods are essentially the reverse of validate_<fieldname> (see Validation below.)

    Deserializing objects

    -

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

    -
    from StringIO import StringIO
    +

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

    +
    from StringIO import StringIO
     from rest_framework.parsers import JSONParser
     
     stream = StringIO(json)
     data = JSONParser().parse(stream)
     

    ...then we restore those native datatypes into a fully populated object instance.

    -
    serializer = CommentSerializer(data=data)
    +
    serializer = CommentSerializer(data=data)
     serializer.is_valid()
     # True
     serializer.object
     # <Comment object at 0x10633b2d0>
     

    When deserializing data, we can either create a new instance, or update an existing instance.

    -
    serializer = CommentSerializer(data=data)           # Create new instance
    +
    serializer = CommentSerializer(data=data)           # Create new instance
     serializer = CommentSerializer(comment, data=data)  # Update `comment`
     

    By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the partial argument in order to allow partial updates.

    -
    serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)  # Update `comment` with partial data
    +
    serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)  # Update `comment` with partial data
     

    Validation

    When deserializing data, you always need to call is_valid() before attempting to access the deserialized object. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example:

    -
    serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
    +
    serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
     serializer.is_valid()
     # False
     serializer.errors
    @@ -325,7 +586,7 @@ serializer.errors
     

    You can specify custom field-level validation by adding .validate_<fieldname> methods to your Serializer subclass. These are analogous to .clean_<fieldname> methods on Django forms, but accept slightly different arguments.

    They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the source argument to the field, if one was provided).

    Your validate_<fieldname> methods should either just return the attrs dictionary or raise a ValidationError. For example:

    -
    from rest_framework import serializers
    +
    from rest_framework import serializers
     
     class BlogPostSerializer(serializers.Serializer):
         title = serializers.CharField(max_length=100)
    @@ -342,7 +603,7 @@ class BlogPostSerializer(serializers.Serializer):
     

    Object-level validation

    To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is the attrs dictionary. It should raise a ValidationError if necessary, or just return attrs. For example:

    -
    from rest_framework import serializers
    +
    from rest_framework import serializers
     
     class EventSerializer(serializers.Serializer):
         description = serializers.CharField(max_length=100)
    @@ -359,15 +620,15 @@ class EventSerializer(serializers.Serializer):
     

    Saving object state

    To save the deserialized objects created by a serializer, call the .save() method:

    -
    if serializer.is_valid():
    +
    if serializer.is_valid():
         serializer.save()
     

    The default behavior of the method is to simply call .save() on the deserialized object instance. You can override the default save behaviour by overriding the .save_object(obj) method on the serializer class.

    -

    The generic views provided by REST framework call the .save() method when updating or creating entities.

    +

    The generic views provided by REST framework call the .save() method when updating or creating entities.

    Dealing with nested objects

    The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.

    The Serializer class is itself a type of Field, and can be used to represent relationships where one object type is nested inside another.

    -
    class UserSerializer(serializers.Serializer):
    +
    class UserSerializer(serializers.Serializer):
         email = serializers.EmailField()
         username = serializers.CharField(max_length=100)
     
    @@ -377,20 +638,20 @@ class CommentSerializer(serializers.Serializer):
         created = serializers.DateTimeField()
     

    If a nested representation may optionally accept the None value you should pass the required=False flag to the nested serializer.

    -
    class CommentSerializer(serializers.Serializer):
    +
    class CommentSerializer(serializers.Serializer):
         user = UserSerializer(required=False)  # May be an anonymous user.
         content = serializers.CharField(max_length=200)
         created = serializers.DateTimeField()
     

    Similarly if a nested representation should be a list of items, you should pass the many=True flag to the nested serialized.

    -
    class CommentSerializer(serializers.Serializer):
    +
    class CommentSerializer(serializers.Serializer):
         user = UserSerializer(required=False)
         edits = EditItemSerializer(many=True)  # A nested list of 'edit' items.
         content = serializers.CharField(max_length=200)
         created = serializers.DateTimeField()
     

    Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object.

    -
    serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
    +
    serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
     serializer.is_valid()
     # False
     serializer.errors
    @@ -400,7 +661,7 @@ serializer.errors
     

    The Serializer class can also handle serializing or deserializing lists of objects.

    Serializing multiple objects

    To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

    -
    queryset = Book.objects.all()
    +
    queryset = Book.objects.all()
     serializer = BookSerializer(queryset, many=True)
     serializer.data
     # [
    @@ -413,7 +674,7 @@ serializer.data
     

    To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the many=True flag, and pass a list of data to be deserialized.

    This allows you to write views that create multiple items when a POST request is made.

    For example:

    -
    data = [
    +
    data = [
         {'title': 'The bell jar', 'author': 'Sylvia Plath'},
         {'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'}
     ]
    @@ -426,7 +687,7 @@ serializer.save()  # `.save()` will be called on each deserialized instance
     

    You can also deserialize a list of objects as part of a bulk update of multiple existing items. In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with.

    This allows you to write views that update or create multiple items when a PUT request is made.

    -
    # Capitalizing the titles of the books
    +
    # Capitalizing the titles of the books
     queryset = Book.objects.all()
     data = [
         {'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'},
    @@ -439,7 +700,7 @@ serializer.save()  # `.save()` will be called on each updated or newly created i
     

    By default bulk updates will be limited to updating instances that already exist in the provided queryset.

    When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass allow_add_remove=True to the serializer.

    -
    serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
    +
    serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
     serializer.is_valid()
     # True
     serializer.save()  # `.save()` will be called on updated or newly created instances.
    @@ -449,7 +710,7 @@ serializer.save()  # `.save()` will be called on updated or newly created instan
     

    How identity is determined when performing bulk updates

    Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances.

    By default the serializer class will use the id key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the get_identity method on the Serializer class. For example:

    -
    class AccountSerializer(serializers.Serializer):
    +
    class AccountSerializer(serializers.Serializer):
         slug = serializers.CharField(max_length=100)
         created = serializers.DateTimeField()
         ...  # Various other fields
    @@ -471,7 +732,7 @@ serializer.save()  # `.save()` will be called on updated or newly created instan
     

    Including extra context

    There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.

    You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example:

    -
    serializer = AccountSerializer(account, context={'request': request})
    +
    serializer = AccountSerializer(account, context={'request': request})
     serializer.data
     # {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
     
    @@ -480,7 +741,7 @@ serializer.data

    ModelSerializer

    Often you'll want serializer classes that map closely to model definitions. The ModelSerializer class lets you automatically create a Serializer class with fields that correspond to the Model fields.

    -
    class AccountSerializer(serializers.ModelSerializer):
    +
    class AccountSerializer(serializers.ModelSerializer):
         class Meta:
             model = Account
     
    @@ -492,14 +753,14 @@ The ModelSerializer class lets you automatically create a Serialize

    Specifying which fields should be included

    If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm.

    For example:

    -
    class AccountSerializer(serializers.ModelSerializer):
    +
    class AccountSerializer(serializers.ModelSerializer):
         class Meta:
             model = Account
             fields = ('id', 'account_name', 'users', 'created')
     

    Specifying nested serialization

    The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:

    -
    class AccountSerializer(serializers.ModelSerializer):
    +
    class AccountSerializer(serializers.ModelSerializer):
         class Meta:
             model = Account
             fields = ('id', 'account_name', 'users', 'created')
    @@ -509,16 +770,16 @@ The ModelSerializer class lets you automatically create a Serialize
     

    If you want to customize the way the serialization is done (e.g. using allow_add_remove) you'll need to define the field yourself.

    Specifying which fields should be read-only

    You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you may use the read_only_fields Meta option, like so:

    -
    class AccountSerializer(serializers.ModelSerializer):
    +
    class AccountSerializer(serializers.ModelSerializer):
         class Meta:
             model = Account
             fields = ('id', 'account_name', 'users', 'created')
             read_only_fields = ('account_name',)
     
    -

    Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option.

    +

    Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option.

    Specifying which fields should be write-only

    You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the write_only=True attribute, you may use the write_only_fields Meta option, like so:

    -
    class CreateUserSerializer(serializers.ModelSerializer):
    +
    class CreateUserSerializer(serializers.ModelSerializer):
         class Meta:
             model = User
             fields = ('email', 'username', 'password')
    @@ -528,14 +789,14 @@ The ModelSerializer class lets you automatically create a Serialize
             """
             Instantiate a new User instance.
             """
    -        assert instance is None, 'Cannot update users with CreateUserSerializer'                                
    +        assert instance is None, 'Cannot update users with CreateUserSerializer'
             user = User(email=attrs['email'], username=attrs['username'])
             user.set_password(attrs['password'])
             return user
     

    Specifying fields explicitly

    You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.

    -
    class AccountSerializer(serializers.ModelSerializer):
    +
    class AccountSerializer(serializers.ModelSerializer):
         url = serializers.CharField(source='get_absolute_url', read_only=True)
         groups = serializers.PrimaryKeyRelatedField(many=True)
     
    @@ -546,14 +807,21 @@ The ModelSerializer class lets you automatically create a Serialize
     

    Relational fields

    When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for ModelSerializer is to use the primary keys of the related instances.

    Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.

    -

    For full details see the serializer relations documentation.

    +

    For full details see the serializer relations documentation.

    +

    Inheritance of the 'Meta' class

    +

    The inner Meta class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's Model and ModelForm classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:

    +
    class AccountSerializer(MyBaseSerializer):
    +    class Meta(MyBaseSerializer.Meta):
    +        model = Account
    +
    +

    Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly.


    HyperlinkedModelSerializer

    The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.

    By default the serializer will include a url field instead of a primary key field.

    The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.

    You can explicitly include the primary key by adding it to the fields option, for example:

    -
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             model = Account
             fields = ('url', 'id', 'account_name', 'users', 'created')
    @@ -562,7 +830,7 @@ The ModelSerializer class lets you automatically create a Serialize
     

    There needs to be a way of determining which views should be used for hyperlinking to model instances.

    By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail', and looks up the instance by a pk keyword argument.

    You can change the field that is used for object lookups by setting the lookup_field option. The value of this option should correspond both with a kwarg in the URL conf, and with a field on the model. For example:

    -
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             model = Account
             fields = ('url', 'account_name', 'users', 'created')
    @@ -570,7 +838,7 @@ The ModelSerializer class lets you automatically create a Serialize
     

    Note that the lookup_field will be used as the default on all hyperlinked fields, including both the URL identity, and any hyperlinked relationships.

    For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:

    -
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
         url = serializers.HyperlinkedIdentityField(
             view_name='account_detail',
             lookup_field='account_name'
    @@ -589,7 +857,7 @@ The ModelSerializer class lets you automatically create a Serialize
     

    Overriding the URL field behavior

    The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.

    You can also override this on a per-serializer basis by using the url_field_name option on the serializer, like so:

    -
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             model = Account
             fields = ('account_url', 'account_name', 'users', 'created')
    @@ -597,7 +865,7 @@ The ModelSerializer class lets you automatically create a Serialize
     

    Note: The generic view implementations normally generate a Location header in response to successful POST requests. Serializers using url_field_name option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's get_success_headers() method.

    You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the view_name and lookup_field options, like so:

    -
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
    +
    class AccountSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             model = Account
             fields = ('account_url', 'account_name', 'users', 'created')
    @@ -613,7 +881,7 @@ The ModelSerializer class lets you automatically create a Serialize
     

    Modifying the fields 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.

    Example

    For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:

    -
    class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    +
    class DynamicFieldsModelSerializer(serializers.ModelSerializer):
         """
         A ModelSerializer that takes an additional `fields` argument that
         controls which fields should be displayed.
    @@ -634,7 +902,7 @@ The ModelSerializer class lets you automatically create a Serialize
                     self.fields.pop(field_name)
     

    This would then allow you to do the following:

    -
    >>> class UserSerializer(DynamicFieldsModelSerializer):
    +
    >>> class UserSerializer(DynamicFieldsModelSerializer):
     >>>     class Meta:
     >>>         model = User
     >>>         fields = ('id', 'username', 'email')
    @@ -646,7 +914,7 @@ The ModelSerializer class lets you automatically create a Serialize
     {'id': 2, 'email': 'jon@example.com'}
     

    Customising the default fields

    -

    The field_mapping attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.

    +

    The field_mapping attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.

    For more advanced customization than simply changing the default serializer class you can override various get_<field_type>_field methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or None.

    get_pk_field

    Signature: .get_pk_field(self, model_field)

    @@ -664,7 +932,7 @@ The ModelSerializer class lets you automatically create a Serialize

    Returns the field instance that should be used for non-relational, non-pk fields.

    Example

    The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.

    -
    class NoPKModelSerializer(serializers.ModelSerializer):
    +
    class NoPKModelSerializer(serializers.ModelSerializer):
         def get_pk_field(self, model_field):
             return None
     
    @@ -677,42 +945,52 @@ The ModelSerializer class lets you automatically create a Serialize

    The django-rest-framework-gis package provides a GeoFeatureModelSerializer serializer class that supports GeoJSON both for read and write operations.

    HStoreSerializer

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

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/settings.html b/api-guide/settings/index.html similarity index 50% rename from api-guide/settings.html rename to api-guide/settings/index.html index c0866f02d..2a86a14b2 100644 --- a/api-guide/settings.html +++ b/api-guide/settings/index.html @@ -1,65 +1,74 @@ - - - Settings - Django REST framework - - - - - - - - - - + + + + Settings - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    -

    settings.py

    -

    Settings

    + + + + settings.py + + + + +

    Settings

    Namespaces are one honking great idea - let's do more of those!

    The Zen of Python

    Configuration for REST framework is all namespaced inside a single Django setting, named REST_FRAMEWORK.

    For example your project's settings.py file might include something like this:

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         'DEFAULT_RENDERER_CLASSES': (
             'rest_framework.renderers.YAMLRenderer',
         ),
    @@ -227,7 +431,7 @@ a.fusion-poweredby {
     

    Accessing settings

    If you need to access the values of REST framework's API settings in your project, you should use the api_settings object. For example.

    -
    from rest_framework.settings import api_settings
    +
    from rest_framework.settings import api_settings
     
     print api_settings.DEFAULT_AUTHENTICATION_CLASSES
     
    @@ -239,7 +443,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES

    DEFAULT_RENDERER_CLASSES

    A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object.

    Default:

    -
    (
    +
    (
         'rest_framework.renderers.JSONRenderer',
         'rest_framework.renderers.BrowsableAPIRenderer',
     )
    @@ -247,7 +451,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
     

    DEFAULT_PARSER_CLASSES

    A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.DATA property.

    Default:

    -
    (
    +
    (
         'rest_framework.parsers.JSONParser',
         'rest_framework.parsers.FormParser',
         'rest_framework.parsers.MultiPartParser'
    @@ -256,15 +460,15 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES
     

    DEFAULT_AUTHENTICATION_CLASSES

    A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties.

    Default:

    -
    (
    +
    (
         'rest_framework.authentication.SessionAuthentication',
         'rest_framework.authentication.BasicAuthentication'
     )
     

    DEFAULT_PERMISSION_CLASSES

    -

    A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.

    +

    A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.

    Default:

    -
    (
    +
    (
         'rest_framework.permissions.AllowAny',
     )
     
    @@ -289,33 +493,33 @@ If set to None then generic filtering is disabled.

    PAGINATE_BY_PARAM

    The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to None, clients may not override the default page size.

    For example, given the following settings:

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         'PAGINATE_BY': 10,
         'PAGINATE_BY_PARAM': 'page_size',
     }
     

    A client would be able to modify the pagination size by using the page_size query parameter. For example:

    -
    GET http://example.com/api/accounts?page_size=25
    +
    GET http://example.com/api/accounts?page_size=25
     

    Default: None

    MAX_PAGINATE_BY

    The maximum page size to allow when the page size is specified by the client. If set to None, then no maximum limit is applied.

    For example, given the following settings:

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         'PAGINATE_BY': 10,
         'PAGINATE_BY_PARAM': 'page_size',
         'MAX_PAGINATE_BY': 100
     }
     

    A client request like the following would return a paginated list of up to 100 items.

    -
    GET http://example.com/api/accounts?page_size=999
    +
    GET http://example.com/api/accounts?page_size=999
     

    Default: None

    SEARCH_PARAM

    -

    The name of a query paramater, which can be used to specify the search term used by SearchFilter.

    +

    The name of a query parameter, which can be used to specify the search term used by SearchFilter.

    Default: search

    ORDERING_PARAM

    -

    The name of a query paramater, which can be used to specify the ordering of results returned by OrderingFilter.

    +

    The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter.

    Default: ordering


    Authentication settings

    @@ -337,7 +541,7 @@ If set to None then generic filtering is disabled.

    The renderer classes that are supported when building test requests.

    The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json')

    Default:

    -
    (
    +
    (
         'rest_framework.renderers.MultiPartRenderer',
         'rest_framework.renderers.JSONRenderer'
     )
    @@ -370,7 +574,7 @@ If set to None then generic filtering is disabled.

    DATETIME_FORMAT

    A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.

    May be any of None, 'iso-8601' or a Python strftime format string.

    -

    Default: None

    +

    Default: 'iso-8601'

    DATETIME_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields.

    May be a list including the string 'iso-8601' or Python strftime format strings.

    @@ -378,7 +582,7 @@ If set to None then generic filtering is disabled.

    DATE_FORMAT

    A format string that should be used by default for rendering the output of DateField serializer fields. If None, then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer.

    May be any of None, 'iso-8601' or a Python strftime format string.

    -

    Default: None

    +

    Default: 'iso-8601'

    DATE_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to DateField serializer fields.

    May be a list including the string 'iso-8601' or Python strftime format strings.

    @@ -386,18 +590,42 @@ If set to None then generic filtering is disabled.

    TIME_FORMAT

    A format string that should be used by default for rendering the output of TimeField serializer fields. If None, then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer.

    May be any of None, 'iso-8601' or a Python strftime format string.

    -

    Default: None

    +

    Default: 'iso-8601'

    TIME_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to TimeField serializer fields.

    May be a list including the string 'iso-8601' or Python strftime format strings.

    Default: ['iso-8601']


    +

    Encodings

    +

    UNICODE_JSON

    +

    When set to True, JSON responses will allow unicode characters in responses. For example:

    +
    {"unicode black star":"★"}
    +
    +

    When set to False, JSON responses will escape non-ascii characters, like so:

    +
    {"unicode black star":"\u2605"}
    +
    +

    Both styles conform to RFC 4627, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.

    +

    Default: True

    +

    COMPACT_JSON

    +

    When set to True, JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example:

    +
    {"is_admin":false,"email":"jane@example"}
    +
    +

    When set to False, JSON responses will return slightly more verbose representations, like so:

    +
    {"is_admin": false, "email": "jane@example"}
    +
    +

    The default style is to return minified responses, in line with Heroku's API design guidelines.

    +

    Default: True

    +

    COERCE_DECIMAL_TO_STRING

    +

    When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.

    +

    When set to True, the serializer DecimalField class will return strings instead of Decimal objects. When set to False, serializers will return Decimal objects, which the default JSON encoder will return as floats.

    +

    Default: True

    +

    View names and descriptions

    The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API.

    VIEW_NAME_FUNCTION

    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)
    +
    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__.
    • @@ -408,7 +636,7 @@ If set to None then generic filtering is disabled.

      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)
      +
      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__
      • @@ -421,12 +649,15 @@ If set to None then generic filtering is disabled.

        A string representing the function that should be used when returning a response for any given exception. If the function returns None, a 500 error will be raised.

        This setting can be changed to support error responses other than the default {"detail": "Failure..."} responses. For example, you can use it to provide API responses like {"errors": [{"message": "Failure...", "code": ""} ...]}.

        This should be a function with the following signature:

        -
        exception_handler(exc)
        +
        exception_handler(exc)
         
        • exc: The exception.

        Default: 'rest_framework.views.exception_handler'

        +

        NON_FIELD_ERRORS_KEY

        +

        A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.

        +

        Default: 'non_field_errors'

        URL_FIELD_NAME

        A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer.

        Default: 'url'

        @@ -436,42 +667,52 @@ If set to None then generic filtering is disabled.

        NUM_PROXIES

        An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes.

        Default: None

        -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/api-guide/status-codes.html b/api-guide/status-codes.html deleted file mode 100644 index 2daa0edf7..000000000 --- a/api-guide/status-codes.html +++ /dev/null @@ -1,339 +0,0 @@ - - - - - Status Codes - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    status.py

    -

    Status Codes

    -
    -

    418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

    -

    RFC 2324, Hyper Text Coffee Pot Control Protocol

    -
    -

    Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.

    -
    from rest_framework import status
    -from rest_framework.response import Response
    -
    -def empty_view(self):
    -    content = {'please move along': 'nothing to see here'}
    -    return Response(content, status=status.HTTP_404_NOT_FOUND)
    -
    -

    The full set of HTTP status codes included in the status module is listed below.

    -

    The module also includes a set of helper functions for testing if a status code is in a given range.

    -
    from rest_framework import status
    -from rest_framework.test import APITestCase
    -
    -class ExampleTestCase(APITestCase):
    -    def test_url_root(self):
    -        url = reverse('index')
    -        response = self.client.get(url)
    -        self.assertTrue(status.is_success(response.status_code))
    -
    -

    For more information on proper usage of HTTP status codes see RFC 2616 -and RFC 6585.

    -

    Informational - 1xx

    -

    This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.

    -
    HTTP_100_CONTINUE
    -HTTP_101_SWITCHING_PROTOCOLS
    -
    -

    Successful - 2xx

    -

    This class of status code indicates that the client's request was successfully received, understood, and accepted.

    -
    HTTP_200_OK
    -HTTP_201_CREATED
    -HTTP_202_ACCEPTED
    -HTTP_203_NON_AUTHORITATIVE_INFORMATION
    -HTTP_204_NO_CONTENT
    -HTTP_205_RESET_CONTENT
    -HTTP_206_PARTIAL_CONTENT
    -
    -

    Redirection - 3xx

    -

    This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.

    -
    HTTP_300_MULTIPLE_CHOICES
    -HTTP_301_MOVED_PERMANENTLY
    -HTTP_302_FOUND
    -HTTP_303_SEE_OTHER
    -HTTP_304_NOT_MODIFIED
    -HTTP_305_USE_PROXY
    -HTTP_306_RESERVED
    -HTTP_307_TEMPORARY_REDIRECT
    -
    -

    Client Error - 4xx

    -

    The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

    -
    HTTP_400_BAD_REQUEST
    -HTTP_401_UNAUTHORIZED
    -HTTP_402_PAYMENT_REQUIRED
    -HTTP_403_FORBIDDEN
    -HTTP_404_NOT_FOUND
    -HTTP_405_METHOD_NOT_ALLOWED
    -HTTP_406_NOT_ACCEPTABLE
    -HTTP_407_PROXY_AUTHENTICATION_REQUIRED
    -HTTP_408_REQUEST_TIMEOUT
    -HTTP_409_CONFLICT
    -HTTP_410_GONE
    -HTTP_411_LENGTH_REQUIRED
    -HTTP_412_PRECONDITION_FAILED
    -HTTP_413_REQUEST_ENTITY_TOO_LARGE
    -HTTP_414_REQUEST_URI_TOO_LONG
    -HTTP_415_UNSUPPORTED_MEDIA_TYPE
    -HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
    -HTTP_417_EXPECTATION_FAILED
    -HTTP_428_PRECONDITION_REQUIRED
    -HTTP_429_TOO_MANY_REQUESTS
    -HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
    -
    -

    Server Error - 5xx

    -

    Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

    -
    HTTP_500_INTERNAL_SERVER_ERROR
    -HTTP_501_NOT_IMPLEMENTED
    -HTTP_502_BAD_GATEWAY
    -HTTP_503_SERVICE_UNAVAILABLE
    -HTTP_504_GATEWAY_TIMEOUT
    -HTTP_505_HTTP_VERSION_NOT_SUPPORTED
    -HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
    -
    -

    Helper functions

    -

    The following helper functions are available for identifying the category of the response code.

    -
    is_informational()  # 1xx
    -is_success()        # 2xx
    -is_redirect()       # 3xx
    -is_client_error()   # 4xx
    -is_server_error()   # 5xx
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/status-codes/index.html b/api-guide/status-codes/index.html new file mode 100644 index 000000000..b7d71887f --- /dev/null +++ b/api-guide/status-codes/index.html @@ -0,0 +1,533 @@ + + + + + + + Status codes - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + status.py + + + + +

    Status Codes

    +
    +

    418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

    +

    RFC 2324, Hyper Text Coffee Pot Control Protocol

    +
    +

    Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.

    +
    from rest_framework import status
    +from rest_framework.response import Response
    +
    +def empty_view(self):
    +    content = {'please move along': 'nothing to see here'}
    +    return Response(content, status=status.HTTP_404_NOT_FOUND)
    +
    +

    The full set of HTTP status codes included in the status module is listed below.

    +

    The module also includes a set of helper functions for testing if a status code is in a given range.

    +
    from rest_framework import status
    +from rest_framework.test import APITestCase
    +
    +class ExampleTestCase(APITestCase):
    +    def test_url_root(self):
    +        url = reverse('index')
    +        response = self.client.get(url)
    +        self.assertTrue(status.is_success(response.status_code))
    +
    +

    For more information on proper usage of HTTP status codes see RFC 2616 +and RFC 6585.

    +

    Informational - 1xx

    +

    This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.

    +
    HTTP_100_CONTINUE
    +HTTP_101_SWITCHING_PROTOCOLS
    +
    +

    Successful - 2xx

    +

    This class of status code indicates that the client's request was successfully received, understood, and accepted.

    +
    HTTP_200_OK
    +HTTP_201_CREATED
    +HTTP_202_ACCEPTED
    +HTTP_203_NON_AUTHORITATIVE_INFORMATION
    +HTTP_204_NO_CONTENT
    +HTTP_205_RESET_CONTENT
    +HTTP_206_PARTIAL_CONTENT
    +
    +

    Redirection - 3xx

    +

    This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.

    +
    HTTP_300_MULTIPLE_CHOICES
    +HTTP_301_MOVED_PERMANENTLY
    +HTTP_302_FOUND
    +HTTP_303_SEE_OTHER
    +HTTP_304_NOT_MODIFIED
    +HTTP_305_USE_PROXY
    +HTTP_306_RESERVED
    +HTTP_307_TEMPORARY_REDIRECT
    +
    +

    Client Error - 4xx

    +

    The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

    +
    HTTP_400_BAD_REQUEST
    +HTTP_401_UNAUTHORIZED
    +HTTP_402_PAYMENT_REQUIRED
    +HTTP_403_FORBIDDEN
    +HTTP_404_NOT_FOUND
    +HTTP_405_METHOD_NOT_ALLOWED
    +HTTP_406_NOT_ACCEPTABLE
    +HTTP_407_PROXY_AUTHENTICATION_REQUIRED
    +HTTP_408_REQUEST_TIMEOUT
    +HTTP_409_CONFLICT
    +HTTP_410_GONE
    +HTTP_411_LENGTH_REQUIRED
    +HTTP_412_PRECONDITION_FAILED
    +HTTP_413_REQUEST_ENTITY_TOO_LARGE
    +HTTP_414_REQUEST_URI_TOO_LONG
    +HTTP_415_UNSUPPORTED_MEDIA_TYPE
    +HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
    +HTTP_417_EXPECTATION_FAILED
    +HTTP_428_PRECONDITION_REQUIRED
    +HTTP_429_TOO_MANY_REQUESTS
    +HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
    +
    +

    Server Error - 5xx

    +

    Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

    +
    HTTP_500_INTERNAL_SERVER_ERROR
    +HTTP_501_NOT_IMPLEMENTED
    +HTTP_502_BAD_GATEWAY
    +HTTP_503_SERVICE_UNAVAILABLE
    +HTTP_504_GATEWAY_TIMEOUT
    +HTTP_505_HTTP_VERSION_NOT_SUPPORTED
    +HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
    +
    +

    Helper functions

    +

    The following helper functions are available for identifying the category of the response code.

    +
    is_informational()  # 1xx
    +is_success()        # 2xx
    +is_redirect()       # 3xx
    +is_client_error()   # 4xx
    +is_server_error()   # 5xx
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/testing.html b/api-guide/testing.html deleted file mode 100644 index b58f46371..000000000 --- a/api-guide/testing.html +++ /dev/null @@ -1,451 +0,0 @@ - - - - - Testing - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    test.py

    -

    Testing

    -
    -

    Code without tests is broken as designed.

    -

    Jacob Kaplan-Moss

    -
    -

    REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.

    -

    APIRequestFactory

    -

    Extends Django's existing RequestFactory class.

    -

    Creating test requests

    -

    The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available.

    -
    from rest_framework.test import APIRequestFactory
    -
    -# Using the standard RequestFactory API to create a form POST request
    -factory = APIRequestFactory()
    -request = factory.post('/notes/', {'title': 'new idea'})
    -
    -

    Using the format argument

    -

    Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a content type other than multipart form data. For example:

    -
    # Create a JSON POST request
    -factory = APIRequestFactory()
    -request = factory.post('/notes/', {'title': 'new idea'}, format='json')
    -
    -

    By default the available formats are 'multipart' and 'json'. For compatibility with Django's existing RequestFactory the default format is 'multipart'.

    -

    To support a wider set of request formats, or change the default format, see the configuration section.

    -

    Explicitly encoding the request body

    -

    If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example:

    -
    request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
    -
    -

    PUT and PATCH with form data

    -

    One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post().

    -

    For example, using APIRequestFactory, you can make a form PUT request like so:

    -
    factory = APIRequestFactory()
    -request = factory.put('/notes/547/', {'title': 'remember to email dave'})
    -
    -

    Using Django's RequestFactory, you'd need to explicitly encode the data yourself:

    -
    from django.test.client import encode_multipart, RequestFactory
    -
    -factory = RequestFactory()
    -data = {'title': 'remember to email dave'}
    -content = encode_multipart('BoUnDaRyStRiNg', data)
    -content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
    -request = factory.put('/notes/547/', content, content_type=content_type)
    -
    -

    Forcing authentication

    -

    When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.

    -

    To forcibly authenticate a request, use the force_authenticate() method.

    -
    factory = APIRequestFactory()
    -user = User.objects.get(username='olivia')
    -view = AccountDetail.as_view()
    -
    -# Make an authenticated request to the view...
    -request = factory.get('/accounts/django-superstars/')
    -force_authenticate(request, user=user)
    -response = view(request)
    -
    -

    The signature for the method is force_authenticate(request, user=None, token=None). When making the call, either or both of the user and token may be set.

    -

    For example, when forcibly authenticating using a token, you might do something like the following:

    -
    user = User.objects.get(username='olivia')
    -request = factory.get('/accounts/django-superstars/')
    -force_authenticate(request, user=user, token=user.token)
    -
    -
    -

    Note: When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.

    -

    This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used.

    -
    # Request will only authenticate if `SessionAuthentication` is in use.
    -request = factory.get('/accounts/django-superstars/')
    -request.user = user
    -response = view(request)
    -
    -
    -

    Forcing CSRF validation

    -

    By default, requests created with APIRequestFactory 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 enforce_csrf_checks flag when instantiating the factory.

    -
    factory = APIRequestFactory(enforce_csrf_checks=True)
    -
    -
    -

    Note: It's worth noting that Django's standard RequestFactory 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.

    -
    -

    APIClient

    -

    Extends Django's existing Client class.

    -

    Making requests

    -

    The APIClient class supports the same request interface as APIRequestFactory. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available. For example:

    -
    from rest_framework.test import APIClient
    -
    -client = APIClient()
    -client.post('/notes/', {'title': 'new idea'}, format='json')
    -
    -

    To support a wider set of request formats, or change the default format, see the configuration section.

    -

    Authenticating

    -

    .login(**kwargs)

    -

    The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication.

    -
    # Make all requests in the context of a logged in session.
    -client = APIClient()
    -client.login(username='lauren', password='secret')
    -
    -

    To logout, call the logout method as usual.

    -
    # Log out
    -client.logout()
    -
    -

    The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.

    -

    .credentials(**kwargs)

    -

    The credentials method can be used to set headers that will then be included on all subsequent requests by the test client.

    -
    from rest_framework.authtoken.models import Token
    -from rest_framework.test import APIClient
    -
    -# Include an appropriate `Authorization:` header on all requests.
    -token = Token.objects.get(user__username='lauren')
    -client = APIClient()
    -client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
    -
    -

    Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.

    -
    # Stop including any credentials
    -client.credentials()
    -
    -

    The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.

    -

    .force_authenticate(user=None, token=None)

    -

    Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.

    -

    This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.

    -
    user = User.objects.get(username='lauren')
    -client = APIClient()
    -client.force_authenticate(user=user)
    -
    -

    To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None.

    -
    client.force_authenticate(user=None)
    -
    -

    CSRF validation

    -

    By default CSRF validation is not applied when using APIClient. If you need to explicitly enable CSRF validation, you can do so by setting the enforce_csrf_checks flag when instantiating the client.

    -
    client = APIClient(enforce_csrf_checks=True)
    -
    -

    As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login().

    -
    -

    Test cases

    -

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

    -
      -
    • APISimpleTestCase
    • -
    • APITransactionTestCase
    • -
    • APITestCase
    • -
    • APILiveServerTestCase
    • -
    -

    Example

    -

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

    -
    from django.core.urlresolvers import reverse
    -from rest_framework import status
    -from rest_framework.test import APITestCase
    -
    -class AccountTests(APITestCase):
    -    def test_create_account(self):
    -        """
    -        Ensure we can create a new account object.
    -        """
    -        url = reverse('account-list')
    -        data = {'name': 'DabApps'}
    -        response = self.client.post(url, data, format='json')
    -        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    -        self.assertEqual(response.data, data)
    -
    -
    -

    Testing responses

    -

    Checking the response data

    -

    When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.

    -

    For example, it's easier to inspect response.data:

    -
    response = self.client.get('/users/4/')
    -self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
    -
    -

    Instead of inspecting the result of parsing response.content:

    -
    response = self.client.get('/users/4/')
    -self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
    -
    -

    Rendering responses

    -

    If you're testing views directly using APIRequestFactory, 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 response.content, you'll first need to render the response.

    -
    view = UserDetail.as_view()
    -request = factory.get('/users/4')
    -response = view(request, pk='4')
    -response.render()  # Cannot access `response.content` without this.
    -self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
    -
    -
    -

    Configuration

    -

    Setting the default format

    -

    The default format used to make test requests may be set using the TEST_REQUEST_DEFAULT_FORMAT setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your settings.py file:

    -
    REST_FRAMEWORK = {
    -    ...
    -    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
    -}
    -
    -

    Setting the available formats

    -

    If you need to test requests using something other than multipart or json requests, you can do so by setting the TEST_REQUEST_RENDERER_CLASSES setting.

    -

    For example, to add support for using format='yaml' in test requests, you might have something like this in your settings.py file.

    -
    REST_FRAMEWORK = {
    -    ...
    -    'TEST_REQUEST_RENDERER_CLASSES': (
    -        'rest_framework.renderers.MultiPartRenderer',
    -        'rest_framework.renderers.JSONRenderer',
    -        'rest_framework.renderers.YAMLRenderer'
    -    )
    -}
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html new file mode 100644 index 000000000..3d9b61b1f --- /dev/null +++ b/api-guide/testing/index.html @@ -0,0 +1,695 @@ + + + + + + + Testing - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + test.py + + + + +

    Testing

    +
    +

    Code without tests is broken as designed.

    +

    Jacob Kaplan-Moss

    +
    +

    REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.

    +

    APIRequestFactory

    +

    Extends Django's existing RequestFactory class.

    +

    Creating test requests

    +

    The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available.

    +
    from rest_framework.test import APIRequestFactory
    +
    +# Using the standard RequestFactory API to create a form POST request
    +factory = APIRequestFactory()
    +request = factory.post('/notes/', {'title': 'new idea'})
    +
    +

    Using the format argument

    +

    Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a content type other than multipart form data. For example:

    +
    # Create a JSON POST request
    +factory = APIRequestFactory()
    +request = factory.post('/notes/', {'title': 'new idea'}, format='json')
    +
    +

    By default the available formats are 'multipart' and 'json'. For compatibility with Django's existing RequestFactory the default format is 'multipart'.

    +

    To support a wider set of request formats, or change the default format, see the configuration section.

    +

    Explicitly encoding the request body

    +

    If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example:

    +
    request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
    +
    +

    PUT and PATCH with form data

    +

    One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post().

    +

    For example, using APIRequestFactory, you can make a form PUT request like so:

    +
    factory = APIRequestFactory()
    +request = factory.put('/notes/547/', {'title': 'remember to email dave'})
    +
    +

    Using Django's RequestFactory, you'd need to explicitly encode the data yourself:

    +
    from django.test.client import encode_multipart, RequestFactory
    +
    +factory = RequestFactory()
    +data = {'title': 'remember to email dave'}
    +content = encode_multipart('BoUnDaRyStRiNg', data)
    +content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
    +request = factory.put('/notes/547/', content, content_type=content_type)
    +
    +

    Forcing authentication

    +

    When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.

    +

    To forcibly authenticate a request, use the force_authenticate() method.

    +
    factory = APIRequestFactory()
    +user = User.objects.get(username='olivia')
    +view = AccountDetail.as_view()
    +
    +# Make an authenticated request to the view...
    +request = factory.get('/accounts/django-superstars/')
    +force_authenticate(request, user=user)
    +response = view(request)
    +
    +

    The signature for the method is force_authenticate(request, user=None, token=None). When making the call, either or both of the user and token may be set.

    +

    For example, when forcibly authenticating using a token, you might do something like the following:

    +
    user = User.objects.get(username='olivia')
    +request = factory.get('/accounts/django-superstars/')
    +force_authenticate(request, user=user, token=user.token)
    +
    +
    +

    Note: When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.

    +

    This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used.

    +
    # Request will only authenticate if `SessionAuthentication` is in use.
    +request = factory.get('/accounts/django-superstars/')
    +request.user = user
    +response = view(request)
    +
    +
    +

    Forcing CSRF validation

    +

    By default, requests created with APIRequestFactory 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 enforce_csrf_checks flag when instantiating the factory.

    +
    factory = APIRequestFactory(enforce_csrf_checks=True)
    +
    +
    +

    Note: It's worth noting that Django's standard RequestFactory 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.

    +
    +

    APIClient

    +

    Extends Django's existing Client class.

    +

    Making requests

    +

    The APIClient class supports the same request interface as APIRequestFactory. This means the that standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available. For example:

    +
    from rest_framework.test import APIClient
    +
    +client = APIClient()
    +client.post('/notes/', {'title': 'new idea'}, format='json')
    +
    +

    To support a wider set of request formats, or change the default format, see the configuration section.

    +

    Authenticating

    +

    .login(**kwargs)

    +

    The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication.

    +
    # Make all requests in the context of a logged in session.
    +client = APIClient()
    +client.login(username='lauren', password='secret')
    +
    +

    To logout, call the logout method as usual.

    +
    # Log out
    +client.logout()
    +
    +

    The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.

    +

    .credentials(**kwargs)

    +

    The credentials method can be used to set headers that will then be included on all subsequent requests by the test client.

    +
    from rest_framework.authtoken.models import Token
    +from rest_framework.test import APIClient
    +
    +# Include an appropriate `Authorization:` header on all requests.
    +token = Token.objects.get(user__username='lauren')
    +client = APIClient()
    +client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
    +
    +

    Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.

    +
    # Stop including any credentials
    +client.credentials()
    +
    +

    The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.

    +

    .force_authenticate(user=None, token=None)

    +

    Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.

    +

    This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.

    +
    user = User.objects.get(username='lauren')
    +client = APIClient()
    +client.force_authenticate(user=user)
    +
    +

    To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None.

    +
    client.force_authenticate(user=None)
    +
    +

    CSRF validation

    +

    By default CSRF validation is not applied when using APIClient. If you need to explicitly enable CSRF validation, you can do so by setting the enforce_csrf_checks flag when instantiating the client.

    +
    client = APIClient(enforce_csrf_checks=True)
    +
    +

    As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login().

    +
    +

    Test cases

    +

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

    +
      +
    • APISimpleTestCase
    • +
    • APITransactionTestCase
    • +
    • APITestCase
    • +
    • APILiveServerTestCase
    • +
    +

    Example

    +

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

    +
    from django.core.urlresolvers import reverse
    +from rest_framework import status
    +from rest_framework.test import APITestCase
    +
    +class AccountTests(APITestCase):
    +    def test_create_account(self):
    +        """
    +        Ensure we can create a new account object.
    +        """
    +        url = reverse('account-list')
    +        data = {'name': 'DabApps'}
    +        response = self.client.post(url, data, format='json')
    +        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    +        self.assertEqual(response.data, data)
    +
    +
    +

    Testing responses

    +

    Checking the response data

    +

    When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.

    +

    For example, it's easier to inspect response.data:

    +
    response = self.client.get('/users/4/')
    +self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
    +
    +

    Instead of inspecting the result of parsing response.content:

    +
    response = self.client.get('/users/4/')
    +self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
    +
    +

    Rendering responses

    +

    If you're testing views directly using APIRequestFactory, 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 response.content, you'll first need to render the response.

    +
    view = UserDetail.as_view()
    +request = factory.get('/users/4')
    +response = view(request, pk='4')
    +response.render()  # Cannot access `response.content` without this.
    +self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
    +
    +
    +

    Configuration

    +

    Setting the default format

    +

    The default format used to make test requests may be set using the TEST_REQUEST_DEFAULT_FORMAT setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your settings.py file:

    +
    REST_FRAMEWORK = {
    +    ...
    +    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
    +}
    +
    +

    Setting the available formats

    +

    If you need to test requests using something other than multipart or json requests, you can do so by setting the TEST_REQUEST_RENDERER_CLASSES setting.

    +

    For example, to add support for using format='yaml' in test requests, you might have something like this in your settings.py file.

    +
    REST_FRAMEWORK = {
    +    ...
    +    'TEST_REQUEST_RENDERER_CLASSES': (
    +        'rest_framework.renderers.MultiPartRenderer',
    +        'rest_framework.renderers.JSONRenderer',
    +        'rest_framework.renderers.YAMLRenderer'
    +    )
    +}
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/throttling.html b/api-guide/throttling.html deleted file mode 100644 index 1978a92a7..000000000 --- a/api-guide/throttling.html +++ /dev/null @@ -1,388 +0,0 @@ - - - - - Throttling - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    throttling.py

    -

    Throttling

    -
    -

    HTTP/1.1 420 Enhance Your Calm

    -

    Twitter API rate limiting response

    -
    -

    Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.

    -

    As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.

    -

    Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.

    -

    Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.

    -

    Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.

    -

    How throttling is determined

    -

    As with permissions and authentication, throttling in REST framework is always defined as a list of classes.

    -

    Before running the main body of the view each throttle in the list is checked. -If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run.

    -

    Setting the throttling policy

    -

    The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_THROTTLE_CLASSES': (
    -        'rest_framework.throttling.AnonRateThrottle',
    -        'rest_framework.throttling.UserRateThrottle'
    -    ),
    -    'DEFAULT_THROTTLE_RATES': {
    -        'anon': '100/day',
    -        'user': '1000/day'
    -    }
    -}
    -
    -

    The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period.

    -

    You can also set the throttling policy on a per-view or per-viewset basis, -using the APIView class based views.

    -
    from rest_framework.response import Response
    -from rest_framework.throttling import UserRateThrottle
    -from rest_framework.views import APIView
    -
    -class ExampleView(APIView):
    -    throttle_classes = (UserRateThrottle,)
    -
    -    def get(self, request, format=None):
    -        content = {
    -            'status': 'request was permitted'
    -        }
    -        return Response(content)
    -
    -

    Or, if you're using the @api_view decorator with function based views.

    -
    @api_view(['GET'])
    -@throttle_classes([UserRateThrottle])
    -def example_view(request, format=None):
    -    content = {
    -        'status': 'request was permitted'
    -    }
    -    return Response(content)
    -
    -

    How clients are identified

    -

    The X-Forwarded-For and Remote-Addr HTTP headers are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the Remote-Addr header will be used.

    -

    If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES 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 X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the Remote-Addr header will always be used as the identifying IP address.

    -

    It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client.

    -

    Further context on how the X-Forwarded-For header works, and identifing a remote client IP can be found here.

    -

    Setting up the cache

    -

    The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details.

    -

    If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example:

    -
    class CustomAnonRateThrottle(AnonRateThrottle):
    -    cache = get_cache('alternate')
    -
    -

    You'll need to rememeber to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute.

    -
    -

    API Reference

    -

    AnonRateThrottle

    -

    The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.

    -

    The allowed request rate is determined from one of the following (in order of preference).

    -
      -
    • The rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property.
    • -
    • The DEFAULT_THROTTLE_RATES['anon'] setting.
    • -
    -

    AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.

    -

    UserRateThrottle

    -

    The UserRateThrottle 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.

    -

    The allowed request rate is determined from one of the following (in order of preference).

    -
      -
    • The rate property on the class, which may be provided by overriding UserRateThrottle and setting the property.
    • -
    • The DEFAULT_THROTTLE_RATES['user'] setting.
    • -
    -

    An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique "scope" for each class.

    -

    For example, multiple user throttle rates could be implemented by using the following classes...

    -
    class BurstRateThrottle(UserRateThrottle):
    -    scope = 'burst'
    -
    -class SustainedRateThrottle(UserRateThrottle):
    -    scope = 'sustained'
    -
    -

    ...and the following settings.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_THROTTLE_CLASSES': (
    -        'example.throttles.BurstRateThrottle',
    -        'example.throttles.SustainedRateThrottle'
    -    ),
    -    'DEFAULT_THROTTLE_RATES': {
    -        'burst': '60/min',
    -        'sustained': '1000/day'
    -    }
    -}
    -
    -

    UserRateThrottle is suitable if you want simple global rate restrictions per-user.

    -

    ScopedRateThrottle

    -

    The ScopedRateThrottle 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 .throttle_scope property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.

    -

    The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request "scope".

    -

    For example, given the following views...

    -
    class ContactListView(APIView):
    -    throttle_scope = 'contacts'
    -    ...
    -
    -class ContactDetailView(ApiView):
    -    throttle_scope = 'contacts'
    -    ...
    -
    -class UploadView(APIView):        
    -    throttle_scope = 'uploads'
    -    ...
    -
    -

    ...and the following settings.

    -
    REST_FRAMEWORK = {
    -    'DEFAULT_THROTTLE_CLASSES': (
    -        'rest_framework.throttling.ScopedRateThrottle',
    -    ),
    -    'DEFAULT_THROTTLE_RATES': {
    -        'contacts': '1000/day',
    -        'uploads': '20/day'
    -    }
    -}
    -
    -

    User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day.

    -
    -

    Custom throttles

    -

    To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise.

    -

    Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False.

    -

    Example

    -

    The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.

    -
    class RandomRateThrottle(throttles.BaseThrottle):
    -    def allow_request(self, request, view):
    -        return random.randint(1, 10) == 1
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/throttling/index.html b/api-guide/throttling/index.html new file mode 100644 index 000000000..be4c727f0 --- /dev/null +++ b/api-guide/throttling/index.html @@ -0,0 +1,604 @@ + + + + + + + Throttling - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + throttling.py + + + + +

    Throttling

    +
    +

    HTTP/1.1 420 Enhance Your Calm

    +

    Twitter API rate limiting response

    +
    +

    Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.

    +

    As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.

    +

    Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.

    +

    Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.

    +

    Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.

    +

    How throttling is determined

    +

    As with permissions and authentication, throttling in REST framework is always defined as a list of classes.

    +

    Before running the main body of the view each throttle in the list is checked. +If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run.

    +

    Setting the throttling policy

    +

    The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_THROTTLE_CLASSES': (
    +        'rest_framework.throttling.AnonRateThrottle',
    +        'rest_framework.throttling.UserRateThrottle'
    +    ),
    +    'DEFAULT_THROTTLE_RATES': {
    +        'anon': '100/day',
    +        'user': '1000/day'
    +    }
    +}
    +
    +

    The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period.

    +

    You can also set the throttling policy on a per-view or per-viewset basis, +using the APIView class based views.

    +
    from rest_framework.response import Response
    +from rest_framework.throttling import UserRateThrottle
    +from rest_framework.views import APIView
    +
    +class ExampleView(APIView):
    +    throttle_classes = (UserRateThrottle,)
    +
    +    def get(self, request, format=None):
    +        content = {
    +            'status': 'request was permitted'
    +        }
    +        return Response(content)
    +
    +

    Or, if you're using the @api_view decorator with function based views.

    +
    @api_view(['GET'])
    +@throttle_classes([UserRateThrottle])
    +def example_view(request, format=None):
    +    content = {
    +        'status': 'request was permitted'
    +    }
    +    return Response(content)
    +
    +

    How clients are identified

    +

    The X-Forwarded-For and Remote-Addr HTTP headers are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the Remote-Addr header will be used.

    +

    If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES 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 X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the Remote-Addr header will always be used as the identifying IP address.

    +

    It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client.

    +

    Further context on how the X-Forwarded-For header works, and identifying a remote client IP can be found here.

    +

    Setting up the cache

    +

    The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details.

    +

    If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example:

    +
    class CustomAnonRateThrottle(AnonRateThrottle):
    +    cache = get_cache('alternate')
    +
    +

    You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute.

    +
    +

    API Reference

    +

    AnonRateThrottle

    +

    The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.

    +

    The allowed request rate is determined from one of the following (in order of preference).

    +
      +
    • The rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property.
    • +
    • The DEFAULT_THROTTLE_RATES['anon'] setting.
    • +
    +

    AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.

    +

    UserRateThrottle

    +

    The UserRateThrottle 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.

    +

    The allowed request rate is determined from one of the following (in order of preference).

    +
      +
    • The rate property on the class, which may be provided by overriding UserRateThrottle and setting the property.
    • +
    • The DEFAULT_THROTTLE_RATES['user'] setting.
    • +
    +

    An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique "scope" for each class.

    +

    For example, multiple user throttle rates could be implemented by using the following classes...

    +
    class BurstRateThrottle(UserRateThrottle):
    +    scope = 'burst'
    +
    +class SustainedRateThrottle(UserRateThrottle):
    +    scope = 'sustained'
    +
    +

    ...and the following settings.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_THROTTLE_CLASSES': (
    +        'example.throttles.BurstRateThrottle',
    +        'example.throttles.SustainedRateThrottle'
    +    ),
    +    'DEFAULT_THROTTLE_RATES': {
    +        'burst': '60/min',
    +        'sustained': '1000/day'
    +    }
    +}
    +
    +

    UserRateThrottle is suitable if you want simple global rate restrictions per-user.

    +

    ScopedRateThrottle

    +

    The ScopedRateThrottle 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 .throttle_scope property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.

    +

    The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request "scope".

    +

    For example, given the following views...

    +
    class ContactListView(APIView):
    +    throttle_scope = 'contacts'
    +    ...
    +
    +class ContactDetailView(ApiView):
    +    throttle_scope = 'contacts'
    +    ...
    +
    +class UploadView(APIView):
    +    throttle_scope = 'uploads'
    +    ...
    +
    +

    ...and the following settings.

    +
    REST_FRAMEWORK = {
    +    'DEFAULT_THROTTLE_CLASSES': (
    +        'rest_framework.throttling.ScopedRateThrottle',
    +    ),
    +    'DEFAULT_THROTTLE_RATES': {
    +        'contacts': '1000/day',
    +        'uploads': '20/day'
    +    }
    +}
    +
    +

    User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day.

    +
    +

    Custom throttles

    +

    To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise.

    +

    Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False.

    +

    If the .wait() method is implemented and the request is throttled, then a Retry-After header will be included in the response.

    +

    Example

    +

    The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.

    +
    class RandomRateThrottle(throttles.BaseThrottle):
    +    def allow_request(self, request, view):
    +        return random.randint(1, 10) == 1
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/validators.html b/api-guide/validators.html deleted file mode 100644 index de19736e1..000000000 --- a/api-guide/validators.html +++ /dev/null @@ -1,388 +0,0 @@ - - - - - Validators - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    validators.py

    -

    Validators

    -
    -

    Validators can be useful for re-using validation logic between different types of fields.

    -

    Django documentation

    -
    -

    Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.

    -

    Sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.

    -

    Validation in REST framework

    -

    Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.

    -

    With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:

    -
      -
    • It introduces a proper separation of concerns, making your code behaviour more obvious.
    • -
    • It is easy to switch between using shortcut ModelSerializer classes and using explicit Serializer classes. Any validation behaviour being used for ModelSerializer is simple to replicate.
    • -
    • Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance.
    • -
    -

    When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using a Serializer classes instead, then you need to define the validation rules explicitly.

    -

    Example

    -

    As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.

    -
    class CustomerReportRecord(models.Model):
    -    time_raised = models.DateTimeField(default=timezone.now, editable=False) 
    -    reference = models.CharField(unique=True, max_length=20)
    -    description = models.TextField()
    -
    -

    Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:

    -
    class CustomerReportSerializer(serializers.ModelSerializer):
    -    class Meta:
    -        model = CustomerReportRecord
    -
    -

    If we open up the Django shell using manage.py shell we can now

    -
    >>> from project.example.serializers import CustomerReportSerializer
    ->>> serializer = CustomerReportSerializer()
    ->>> print(repr(serializer))
    -CustomerReportSerializer():
    -    id = IntegerField(label='ID', read_only=True)
    -    time_raised = DateTimeField(read_only=True)
    -    reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
    -    description = CharField(style={'type': 'textarea'})
    -
    -

    The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.

    -

    Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.

    -
    -

    UniqueValidator

    -

    This validator can be used to enforce the unique=True constraint on model fields. -It takes a single required argument, and an optional messages argument:

    -
      -
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • -
    • message - The error message that should be used when validation fails.
    • -
    -

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

    -
    slug = SlugField(
    -    max_length=100,
    -    validators=[UniqueValidator(queryset=BlogPost.objects.all())]
    -)
    -
    -

    UniqueTogetherValidator

    -

    This validator can be used to enforce unique_together constraints on model instances. -It has two required arguments, and a single optional messages argument:

    -
      -
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • -
    • fields required - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
    • -
    • message - The error message that should be used when validation fails.
    • -
    -

    The validator should be applied to serializer classes, like so:

    -
    class ExampleSerializer(serializers.Serializer):
    -    # ...
    -    class Meta:
    -        # ToDo items belong to a parent list, and have an ordering defined
    -        # by the 'position' field. No two items in a given list may share
    -        # the same position.
    -        validators = [
    -            UniqueTogetherValidator(
    -                queryset=ToDoItem.objects.all(),
    -                fields=('list', 'position')
    -            )
    -        ]
    -
    -

    UniqueForDateValidator

    -

    UniqueForMonthValidator

    -

    UniqueForYearValidator

    -

    These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:

    -
      -
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • -
    • field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
    • -
    • date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
    • -
    • message - The error message that should be used when validation fails.
    • -
    -

    The validator should be applied to serializer classes, like so:

    -
    class ExampleSerializer(serializers.Serializer):
    -    # ...
    -    class Meta:
    -        # Blog posts should have a slug that is unique for the current year.
    -        validators = [
    -            UniqueForYearValidator(
    -                queryset=BlogPostItem.objects.all(),
    -                field='slug',
    -                date_field='published'
    -            )
    -        ]
    -
    -

    The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.

    -

    There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.

    -

    Using with a writable date field.

    -

    If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.

    -
    published = serializers.DateTimeField(required=True)
    -
    -

    Using with a read-only date field.

    -

    If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.

    -
    published = serializers.DateTimeField(read_only=True, default=timezone.now)
    -
    -

    The field will not be writable to the user, but the default value will still be passed through to the validated_data.

    -

    Using with a hidden date field.

    -

    If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer.

    -
    published = serializers.HiddenField(default=timezone.now)
    -
    -
    -

    Writing custom validators

    -

    You can use any of Django's existing validators, or write your own custom validators.

    -

    Function based

    -

    A validator may be any callable that raises a serializers.ValidationError on failure.

    -
    def even_number(value):
    -    if value % 2 != 0:
    -        raise serializers.ValidationError('This field must be an even number.')
    -
    -

    Class based

    -

    To write a class based validator, use the __call__ method. Class based validators are useful as they allow you to parameterize and reuse behavior.

    -
    class MultipleOf:
    -    def __init__(self, base):
    -        self.base = base
    -
    -    def __call__(self, value):
    -        if value % self.base != 0
    -            message = 'This field must be a multiple of %d.' % self.base
    -            raise serializers.ValidationError(message)
    -
    -

    Using set_context()

    -

    In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a set_context method on a class based validator.

    -
    def set_context(self, serializer_field):
    -    # Determine if this is an update or a create operation.
    -    # In `__call__` we can then use that information to modify the validation behavior.
    -    self.is_update = serializer_field.parent.instance is not None
    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html new file mode 100644 index 000000000..7d75da1fb --- /dev/null +++ b/api-guide/validators/index.html @@ -0,0 +1,635 @@ + + + + + + + Validators - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    +

    Validators

    +
    +

    Validators can be useful for re-using validation logic between different types of fields.

    +

    Django documentation

    +
    +

    Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.

    +

    However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.

    +

    Validation in REST framework

    +

    Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.

    +

    With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:

    +
      +
    • It introduces a proper separation of concerns, making your code behavior more obvious.
    • +
    • It is easy to switch between using shortcut ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate.
    • +
    • Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
    • +
    +

    When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using a Serializer classes instead, then you need to define the validation rules explicitly.

    +

    Example

    +

    As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.

    +
    class CustomerReportRecord(models.Model):
    +    time_raised = models.DateTimeField(default=timezone.now, editable=False) 
    +    reference = models.CharField(unique=True, max_length=20)
    +    description = models.TextField()
    +
    +

    Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:

    +
    class CustomerReportSerializer(serializers.ModelSerializer):
    +    class Meta:
    +        model = CustomerReportRecord
    +
    +

    If we open up the Django shell using manage.py shell we can now

    +
    >>> from project.example.serializers import CustomerReportSerializer
    +>>> serializer = CustomerReportSerializer()
    +>>> print(repr(serializer))
    +CustomerReportSerializer():
    +    id = IntegerField(label='ID', read_only=True)
    +    time_raised = DateTimeField(read_only=True)
    +    reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
    +    description = CharField(style={'type': 'textarea'})
    +
    +

    The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.

    +

    Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.

    +
    +

    UniqueValidator

    +

    This validator can be used to enforce the unique=True constraint on model fields. +It takes a single required argument, and an optional messages argument:

    +
      +
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • +
    • message - The error message that should be used when validation fails.
    • +
    +

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

    +
    slug = SlugField(
    +    max_length=100,
    +    validators=[UniqueValidator(queryset=BlogPost.objects.all())]
    +)
    +
    +

    UniqueTogetherValidator

    +

    This validator can be used to enforce unique_together constraints on model instances. +It has two required arguments, and a single optional messages argument:

    +
      +
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • +
    • fields required - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
    • +
    • message - The error message that should be used when validation fails.
    • +
    +

    The validator should be applied to serializer classes, like so:

    +
    class ExampleSerializer(serializers.Serializer):
    +    # ...
    +    class Meta:
    +        # ToDo items belong to a parent list, and have an ordering defined
    +        # by the 'position' field. No two items in a given list may share
    +        # the same position.
    +        validators = [
    +            UniqueTogetherValidator(
    +                queryset=ToDoItem.objects.all(),
    +                fields=('list', 'position')
    +            )
    +        ]
    +
    +
    +

    Note: The UniqueTogetherValidation class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.

    +
    +

    UniqueForDateValidator

    +

    UniqueForMonthValidator

    +

    UniqueForYearValidator

    +

    These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:

    +
      +
    • queryset required - This is the queryset against which uniqueness should be enforced.
    • +
    • field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
    • +
    • date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
    • +
    • message - The error message that should be used when validation fails.
    • +
    +

    The validator should be applied to serializer classes, like so:

    +
    class ExampleSerializer(serializers.Serializer):
    +    # ...
    +    class Meta:
    +        # Blog posts should have a slug that is unique for the current year.
    +        validators = [
    +            UniqueForYearValidator(
    +                queryset=BlogPostItem.objects.all(),
    +                field='slug',
    +                date_field='published'
    +            )
    +        ]
    +
    +

    The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.

    +

    There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.

    +

    Using with a writable date field.

    +

    If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.

    +
    published = serializers.DateTimeField(required=True)
    +
    +

    Using with a read-only date field.

    +

    If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.

    +
    published = serializers.DateTimeField(read_only=True, default=timezone.now)
    +
    +

    The field will not be writable to the user, but the default value will still be passed through to the validated_data.

    +

    Using with a hidden date field.

    +

    If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer.

    +
    published = serializers.HiddenField(default=timezone.now)
    +
    +
    +

    Note: The UniqueFor<Range>Validation classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.

    +
    +

    Advanced 'default' argument usage

    +

    Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator.

    +

    Two patterns that you may want to use for this sort of validation include:

    +
      +
    • Using HiddenField. This field will be present in validated_data but will not be used in the serializer output representation.
    • +
    • Using a standard field with read_only=True, but that also includes a default=… argument. This field will be used in the serializer output representation, but cannot be set directly by the user.
    • +
    +

    REST framework includes a couple of defaults that may be useful in this context.

    +

    CurrentUserDefault

    +

    A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

    +
    owner = serializers.HiddenField(
    +    default=CurrentUserDefault()
    +)
    +
    +

    CreateOnlyDefault

    +

    A default class that can be used to only set a default argument during create operations. During updates the field is omitted.

    +

    It takes a single argument, which is the default value or callable that should be used during create operations.

    +
    created_at = serializers.DateTimeField(
    +    read_only=True,
    +    default=CreateOnlyDefault(timezone.now)
    +)
    +
    +
    +

    Writing custom validators

    +

    You can use any of Django's existing validators, or write your own custom validators.

    +

    Function based

    +

    A validator may be any callable that raises a serializers.ValidationError on failure.

    +
    def even_number(value):
    +    if value % 2 != 0:
    +        raise serializers.ValidationError('This field must be an even number.')
    +
    +

    Class based

    +

    To write a class based validator, use the __call__ method. Class based validators are useful as they allow you to parameterize and reuse behavior.

    +
    class MultipleOf:
    +    def __init__(self, base):
    +        self.base = base
    +
    +    def __call__(self, value):
    +        if value % self.base != 0
    +            message = 'This field must be a multiple of %d.' % self.base
    +            raise serializers.ValidationError(message)
    +
    +

    Using set_context()

    +

    In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a set_context method on a class based validator.

    +
    def set_context(self, serializer_field):
    +    # Determine if this is an update or a create operation.
    +    # In `__call__` we can then use that information to modify the validation behavior.
    +    self.is_update = serializer_field.parent.instance is not None
    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/views.html b/api-guide/views.html deleted file mode 100644 index ef7db67e5..000000000 --- a/api-guide/views.html +++ /dev/null @@ -1,360 +0,0 @@ - - - - - Class Based Views - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    decorators.py views.py

    -

    Class Based Views

    -
    -

    Django's class based views are a welcome departure from the old-style views.

    -

    Reinout van Rees

    -
    -

    REST framework provides an APIView class, which subclasses Django's View class.

    -

    APIView classes are different from regular View classes in the following ways:

    -
      -
    • Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
    • -
    • Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response.
    • -
    • Any APIException exceptions will be caught and mediated into appropriate responses.
    • -
    • Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
    • -
    -

    Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.

    -

    For example:

    -
    from rest_framework.views import APIView
    -from rest_framework.response import Response
    -from rest_framework import authentication, permissions
    -
    -class ListUsers(APIView):
    -    """
    -    View to list all users in the system.
    -
    -    * Requires token authentication.
    -    * Only admin users are able to access this view.
    -    """
    -    authentication_classes = (authentication.TokenAuthentication,)
    -    permission_classes = (permissions.IsAdminUser,)
    -
    -    def get(self, request, format=None):
    -        """
    -        Return a list of all users.
    -        """
    -        usernames = [user.username for user in User.objects.all()]
    -        return Response(usernames)
    -
    -

    API policy attributes

    -

    The following attributes control the pluggable aspects of API views.

    -

    .renderer_classes

    -

    .parser_classes

    -

    .authentication_classes

    -

    .throttle_classes

    -

    .permission_classes

    -

    .content_negotiation_class

    -

    API policy instantiation methods

    -

    The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.

    -

    .get_renderers(self)

    -

    .get_parsers(self)

    -

    .get_authenticators(self)

    -

    .get_throttles(self)

    -

    .get_permissions(self)

    -

    .get_content_negotiator(self)

    -

    API policy implementation methods

    -

    The following methods are called before dispatching to the handler method.

    -

    .check_permissions(self, request)

    -

    .check_throttles(self, request)

    -

    .perform_content_negotiation(self, request, force=False)

    -

    Dispatch methods

    -

    The following methods are called directly by the view's .dispatch() method. -These perform any actions that need to occur before or after calling the handler methods such as .get(), .post(), put(), patch() and .delete().

    -

    .initial(self, request, *args, **kwargs)

    -

    Performs any actions that need to occur before the handler method gets called. -This method is used to enforce permissions and throttling, and perform content negotiation.

    -

    You won't typically need to override this method.

    -

    .handle_exception(self, exc)

    -

    Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception.

    -

    The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.

    -

    If you need to customize the error responses your API returns you should subclass this method.

    -

    .initialize_request(self, request, *args, **kwargs)

    -

    Ensures that the request object that is passed to the handler method is an instance of Request, rather than the usual Django HttpRequest.

    -

    You won't typically need to override this method.

    -

    .finalize_response(self, request, response, *args, **kwargs)

    -

    Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.

    -

    You won't typically need to override this method.

    -
    -

    Function Based Views

    -
    -

    Saying [that Class based views] is always the superior solution is a mistake.

    -

    Nick Coghlan

    -
    -

    REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.

    -

    @api_view()

    -

    Signature: @api_view(http_method_names)

    -

    The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:

    -
    from rest_framework.decorators import api_view
    -
    -@api_view(['GET'])
    -def hello_world(request):
    -    return Response({"message": "Hello, world!"})
    -
    -

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

    -

    API policy decorators

    -

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

    -
    from rest_framework.decorators import api_view, throttle_classes
    -from rest_framework.throttling import UserRateThrottle
    -
    -class OncePerDayUserThrottle(UserRateThrottle):
    -        rate = '1/day'
    -
    -@api_view(['GET'])
    -@throttle_classes([OncePerDayUserThrottle])
    -def view(request):
    -    return Response({"message": "Hello for today! See you tomorrow!"})
    -
    -

    These decorators correspond to the attributes set on APIView subclasses, described above.

    -

    The available decorators are:

    -
      -
    • @renderer_classes(...)
    • -
    • @parser_classes(...)
    • -
    • @authentication_classes(...)
    • -
    • @throttle_classes(...)
    • -
    • @permission_classes(...)
    • -
    -

    Each of these decorators takes a single argument which must be a list or tuple of classes.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/views/index.html b/api-guide/views/index.html new file mode 100644 index 000000000..daec30397 --- /dev/null +++ b/api-guide/views/index.html @@ -0,0 +1,565 @@ + + + + + + + Views - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + + +
    + +
    + + + + decorators.py + + + + views.py + + + + +

    Class Based Views

    +
    +

    Django's class based views are a welcome departure from the old-style views.

    +

    Reinout van Rees

    +
    +

    REST framework provides an APIView class, which subclasses Django's View class.

    +

    APIView classes are different from regular View classes in the following ways:

    +
      +
    • Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
    • +
    • Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response.
    • +
    • Any APIException exceptions will be caught and mediated into appropriate responses.
    • +
    • Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
    • +
    +

    Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.

    +

    For example:

    +
    from rest_framework.views import APIView
    +from rest_framework.response import Response
    +from rest_framework import authentication, permissions
    +
    +class ListUsers(APIView):
    +    """
    +    View to list all users in the system.
    +
    +    * Requires token authentication.
    +    * Only admin users are able to access this view.
    +    """
    +    authentication_classes = (authentication.TokenAuthentication,)
    +    permission_classes = (permissions.IsAdminUser,)
    +
    +    def get(self, request, format=None):
    +        """
    +        Return a list of all users.
    +        """
    +        usernames = [user.username for user in User.objects.all()]
    +        return Response(usernames)
    +
    +

    API policy attributes

    +

    The following attributes control the pluggable aspects of API views.

    +

    .renderer_classes

    +

    .parser_classes

    +

    .authentication_classes

    +

    .throttle_classes

    +

    .permission_classes

    +

    .content_negotiation_class

    +

    API policy instantiation methods

    +

    The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.

    +

    .get_renderers(self)

    +

    .get_parsers(self)

    +

    .get_authenticators(self)

    +

    .get_throttles(self)

    +

    .get_permissions(self)

    +

    .get_content_negotiator(self)

    +

    API policy implementation methods

    +

    The following methods are called before dispatching to the handler method.

    +

    .check_permissions(self, request)

    +

    .check_throttles(self, request)

    +

    .perform_content_negotiation(self, request, force=False)

    +

    Dispatch methods

    +

    The following methods are called directly by the view's .dispatch() method. +These perform any actions that need to occur before or after calling the handler methods such as .get(), .post(), put(), patch() and .delete().

    +

    .initial(self, request, *args, **kwargs)

    +

    Performs any actions that need to occur before the handler method gets called. +This method is used to enforce permissions and throttling, and perform content negotiation.

    +

    You won't typically need to override this method.

    +

    .handle_exception(self, exc)

    +

    Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception.

    +

    The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.

    +

    If you need to customize the error responses your API returns you should subclass this method.

    +

    .initialize_request(self, request, *args, **kwargs)

    +

    Ensures that the request object that is passed to the handler method is an instance of Request, rather than the usual Django HttpRequest.

    +

    You won't typically need to override this method.

    +

    .finalize_response(self, request, response, *args, **kwargs)

    +

    Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.

    +

    You won't typically need to override this method.

    +
    +

    Function Based Views

    +
    +

    Saying [that Class based views] is always the superior solution is a mistake.

    +

    Nick Coghlan

    +
    +

    REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.

    +

    @api_view()

    +

    Signature: @api_view(http_method_names)

    +

    The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:

    +
    from rest_framework.decorators import api_view
    +
    +@api_view(['GET'])
    +def hello_world(request):
    +    return Response({"message": "Hello, world!"})
    +
    +

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

    +

    API policy decorators

    +

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

    +
    from rest_framework.decorators import api_view, throttle_classes
    +from rest_framework.throttling import UserRateThrottle
    +
    +class OncePerDayUserThrottle(UserRateThrottle):
    +        rate = '1/day'
    +
    +@api_view(['GET'])
    +@throttle_classes([OncePerDayUserThrottle])
    +def view(request):
    +    return Response({"message": "Hello for today! See you tomorrow!"})
    +
    +

    These decorators correspond to the attributes set on APIView subclasses, described above.

    +

    The available decorators are:

    +
      +
    • @renderer_classes(...)
    • +
    • @parser_classes(...)
    • +
    • @authentication_classes(...)
    • +
    • @throttle_classes(...)
    • +
    • @permission_classes(...)
    • +
    +

    Each of these decorators takes a single argument which must be a list or tuple of classes.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/viewsets.html b/api-guide/viewsets.html deleted file mode 100644 index f239a2716..000000000 --- a/api-guide/viewsets.html +++ /dev/null @@ -1,445 +0,0 @@ - - - - - ViewSets - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    viewsets.py

    -

    ViewSets

    -
    -

    After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.

    -

    Ruby on Rails Documentation

    -
    -

    Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.

    -

    A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().

    -

    The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.

    -

    Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.

    -

    Example

    -

    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
    -from django.shortcuts import get_object_or_404
    -from myapps.serializers import UserSerializer
    -from rest_framework import viewsets
    -from rest_framework.response import Response
    -
    -class UserViewSet(viewsets.ViewSet):
    -    """
    -    A simple ViewSet that for listing or retrieving users.
    -    """
    -    def list(self, request):
    -        queryset = User.objects.all()
    -        serializer = UserSerializer(queryset, many=True)
    -        return Response(serializer.data)
    -
    -    def retrieve(self, request, pk=None):
    -        queryset = User.objects.all()
    -        user = get_object_or_404(queryset, pk=pk)
    -        serializer = UserSerializer(user)
    -        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'})
    -user_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
    -from rest_framework.routers import DefaultRouter
    -
    -router = DefaultRouter()
    -router.register(r'users', UserViewSet)
    -urlpatterns = 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):
    -    """
    -    A viewset for viewing and editing user instances.
    -    """
    -    serializer_class = UserSerializer
    -    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.

    -

    Marking extra actions for routing

    -

    The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:

    -
    class UserViewSet(viewsets.ViewSet):
    -    """
    -    Example empty viewset demonstrating the standard
    -    actions that will be handled by a router class.
    -
    -    If you're using format suffixes, make sure to also include
    -    the `format=None` keyword argument for each action.
    -    """
    -
    -    def list(self, request):
    -        pass
    -
    -    def create(self, request):
    -        pass
    -
    -    def retrieve(self, request, pk=None):
    -        pass
    -
    -    def update(self, request, pk=None):
    -        pass
    -
    -    def partial_update(self, request, pk=None):
    -        pass
    -
    -    def destroy(self, request, pk=None):
    -        pass
    -
    -

    If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the @detail_route or @list_route decorators.

    -

    The @detail_route decorator contains pk in its URL pattern and is intended for methods which require a single instance. The @list_route decorator is intended for methods which operate on a list of objects.

    -

    For example:

    -
    from django.contrib.auth.models import User
    -from rest_framework import status
    -from rest_framework import viewsets
    -from rest_framework.decorators import detail_route, list_route
    -from rest_framework.response import Response
    -from myapp.serializers import UserSerializer, PasswordSerializer
    -
    -class UserViewSet(viewsets.ModelViewSet):
    -    """
    -    A viewset that provides the standard actions
    -    """
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -    @detail_route(methods=['post'])
    -    def set_password(self, request, pk=None):
    -        user = self.get_object()
    -        serializer = PasswordSerializer(data=request.DATA)
    -        if serializer.is_valid():
    -            user.set_password(serializer.data['password'])
    -            user.save()
    -            return Response({'status': 'password set'})
    -        else:
    -            return Response(serializer.errors,
    -                            status=status.HTTP_400_BAD_REQUEST)
    -
    -    @list_route()
    -    def recent_users(self, request):
    -        recent_users = User.objects.all().order('-last_login')
    -        page = self.paginate_queryset(recent_users)
    -        serializer = self.get_pagination_serializer(page)
    -        return Response(serializer.data)
    -
    -

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

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

    Theses decorators will route GET requests by default, but may also accept other HTTP methods, by using the methods argument. For example:

    -
        @detail_route(methods=['post', 'delete'])
    -    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/$

    -
    -

    API Reference

    -

    ViewSet

    -

    The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset.

    -

    The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly.

    -

    GenericViewSet

    -

    The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.

    -

    In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.

    -

    ModelViewSet

    -

    The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.

    -

    The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), and .destroy().

    -

    Example

    -

    Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes, or the model attribute shortcut. For example:

    -
    class AccountViewSet(viewsets.ModelViewSet):
    -    """
    -    A simple ViewSet for viewing and editing accounts.
    -    """
    -    queryset = Account.objects.all()
    -    serializer_class = AccountSerializer
    -    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):
    -    """
    -    A simple ViewSet for viewing and editing the accounts
    -    associated with the user.
    -    """
    -    serializer_class = AccountSerializer
    -    permission_classes = [IsAccountAdminOrReadOnly]
    -
    -    def get_queryset(self):
    -        return self.request.user.accounts.all()
    -
    -

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

    -

    Example

    -

    As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example:

    -
    class AccountViewSet(viewsets.ReadOnlyModelViewSet):
    -    """
    -    A simple ViewSet for viewing accounts.
    -    """
    -    queryset = Account.objects.all()
    -    serializer_class = AccountSerializer
    -
    -

    Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView.

    -

    Custom ViewSet base classes

    -

    You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.

    -

    Example

    -

    To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions:

    -
    class CreateListRetrieveViewSet(mixins.CreateModelMixin,
    -                                mixins.ListModelMixin,
    -                                mixins.RetrieveModelMixin,
    -                                viewsets.GenericViewSet):
    -    """
    -    A viewset that provides `retrieve`, `create`, and `list` actions.
    -
    -    To use it, override the class and set the `.queryset` and
    -    `.serializer_class` attributes.
    -    """
    -    pass
    -
    -

    By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/api-guide/viewsets/index.html b/api-guide/viewsets/index.html new file mode 100644 index 000000000..6e0e84e25 --- /dev/null +++ b/api-guide/viewsets/index.html @@ -0,0 +1,656 @@ + + + + + + + Viewsets - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + + + viewsets.py + + + + +

    ViewSets

    +
    +

    After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.

    +

    Ruby on Rails Documentation

    +
    +

    Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.

    +

    A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().

    +

    The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.

    +

    Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.

    +

    Example

    +

    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
    +from django.shortcuts import get_object_or_404
    +from myapps.serializers import UserSerializer
    +from rest_framework import viewsets
    +from rest_framework.response import Response
    +
    +class UserViewSet(viewsets.ViewSet):
    +    """
    +    A simple ViewSet that for listing or retrieving users.
    +    """
    +    def list(self, request):
    +        queryset = User.objects.all()
    +        serializer = UserSerializer(queryset, many=True)
    +        return Response(serializer.data)
    +
    +    def retrieve(self, request, pk=None):
    +        queryset = User.objects.all()
    +        user = get_object_or_404(queryset, pk=pk)
    +        serializer = UserSerializer(user)
    +        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'})
    +user_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
    +from rest_framework.routers import DefaultRouter
    +
    +router = DefaultRouter()
    +router.register(r'users', UserViewSet)
    +urlpatterns = 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):
    +    """
    +    A viewset for viewing and editing user instances.
    +    """
    +    serializer_class = UserSerializer
    +    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.

    +

    Marking extra actions for routing

    +

    The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:

    +
    class UserViewSet(viewsets.ViewSet):
    +    """
    +    Example empty viewset demonstrating the standard
    +    actions that will be handled by a router class.
    +
    +    If you're using format suffixes, make sure to also include
    +    the `format=None` keyword argument for each action.
    +    """
    +
    +    def list(self, request):
    +        pass
    +
    +    def create(self, request):
    +        pass
    +
    +    def retrieve(self, request, pk=None):
    +        pass
    +
    +    def update(self, request, pk=None):
    +        pass
    +
    +    def partial_update(self, request, pk=None):
    +        pass
    +
    +    def destroy(self, request, pk=None):
    +        pass
    +
    +

    If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the @detail_route or @list_route decorators.

    +

    The @detail_route decorator contains pk in its URL pattern and is intended for methods which require a single instance. The @list_route decorator is intended for methods which operate on a list of objects.

    +

    For example:

    +
    from django.contrib.auth.models import User
    +from rest_framework import status
    +from rest_framework import viewsets
    +from rest_framework.decorators import detail_route, list_route
    +from rest_framework.response import Response
    +from myapp.serializers import UserSerializer, PasswordSerializer
    +
    +class UserViewSet(viewsets.ModelViewSet):
    +    """
    +    A viewset that provides the standard actions
    +    """
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +
    +    @detail_route(methods=['post'])
    +    def set_password(self, request, pk=None):
    +        user = self.get_object()
    +        serializer = PasswordSerializer(data=request.DATA)
    +        if serializer.is_valid():
    +            user.set_password(serializer.data['password'])
    +            user.save()
    +            return Response({'status': 'password set'})
    +        else:
    +            return Response(serializer.errors,
    +                            status=status.HTTP_400_BAD_REQUEST)
    +
    +    @list_route()
    +    def recent_users(self, request):
    +        recent_users = User.objects.all().order('-last_login')
    +        page = self.paginate_queryset(recent_users)
    +        serializer = self.get_pagination_serializer(page)
    +        return Response(serializer.data)
    +
    +

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

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

    Theses decorators will route GET requests by default, but may also accept other HTTP methods, by using the methods argument. For example:

    +
        @detail_route(methods=['post', 'delete'])
    +    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/$

    +
    +

    API Reference

    +

    ViewSet

    +

    The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset.

    +

    The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly.

    +

    GenericViewSet

    +

    The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.

    +

    In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.

    +

    ModelViewSet

    +

    The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.

    +

    The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), and .destroy().

    +

    Example

    +

    Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes, or the model attribute shortcut. For example:

    +
    class AccountViewSet(viewsets.ModelViewSet):
    +    """
    +    A simple ViewSet for viewing and editing accounts.
    +    """
    +    queryset = Account.objects.all()
    +    serializer_class = AccountSerializer
    +    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):
    +    """
    +    A simple ViewSet for viewing and editing the accounts
    +    associated with the user.
    +    """
    +    serializer_class = AccountSerializer
    +    permission_classes = [IsAccountAdminOrReadOnly]
    +
    +    def get_queryset(self):
    +        return self.request.user.accounts.all()
    +
    +

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

    +

    Example

    +

    As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example:

    +
    class AccountViewSet(viewsets.ReadOnlyModelViewSet):
    +    """
    +    A simple ViewSet for viewing accounts.
    +    """
    +    queryset = Account.objects.all()
    +    serializer_class = AccountSerializer
    +
    +

    Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView.

    +

    Custom ViewSet base classes

    +

    You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.

    +

    Example

    +

    To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions:

    +
    class CreateListRetrieveViewSet(mixins.CreateModelMixin,
    +                                mixins.ListModelMixin,
    +                                mixins.RetrieveModelMixin,
    +                                viewsets.GenericViewSet):
    +    """
    +    A viewset that provides `retrieve`, `create`, and `list` actions.
    +
    +    To use it, override the class and set the `.queryset` and
    +    `.serializer_class` attributes.
    +    """
    +    pass
    +
    +

    By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/css/base.css b/css/base.css new file mode 100644 index 000000000..f73f308ce --- /dev/null +++ b/css/base.css @@ -0,0 +1,169 @@ +body { + padding-top: 70px; + background: url(../img/grid.png) repeat-x; + background-attachment: fixed; + background-color: #f8f8f8; +} + +body > div.container { + min-height: 400px; +} + +ul.nav li.main { + font-weight: bold; +} + +div.col-md-3 { + padding-left: 0; +} + +div.source-links { + float: right; +} + +div.col-md-9 img { + max-width: 100%; + display: block; + padding: 4px; + line-height: 1.428571429; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + margin: 20px auto 30px auto; +} + +h1, h2, h3 { + color: #444; +} + +h1 { + font-weight: 400; + font-size: 42px; +} + +h2, h3, h4, h5, h6 { + font-weight: 300; +} + +hr { + border-top: 1px solid #aaa; +} + +pre, .rst-content tt { + max-width: 100%; + background: #fff; + border: solid 1px #e1e4e5; + color: #e74c3c; + overflow-x: auto; +} + +code.code-large, .rst-content tt.code-large { + font-size: 90%; +} + +code { + padding: 2px 5px; + color: #c7254e; + background-color: #f9f2f4; + font-size: 75%; +} + +code, kbd, pre, samp { + font-family: monospace,serif; + font-size: 12px !important; +} + +footer { + margin-top: 30px; + margin-bottom: 10px; + text-align: center; + font-weight: 200; +} + +.modal-dialog { + margin-top: 60px; +} + +/* + * Side navigation + * + * Scrollspy and affixed enhanced navigation to highlight sections and secondary + * sections of docs content. + */ + +/* By default it's not affixed in mobile views, so undo that */ +.bs-sidebar.affix { + position: static; +} + +.bs-sidebar.well { + padding: 0; +} + +/* First level of nav */ +.bs-sidenav { + padding-top: 10px; + padding-bottom: 10px; + border-radius: 5px; +} + +/* All levels of nav */ +.bs-sidebar .nav > li > a { + display: block; + padding: 5px 20px; +} +.bs-sidebar .nav > li > a:hover, +.bs-sidebar .nav > li > a:focus { + text-decoration: none; + border-right: 1px solid; +} +.bs-sidebar .nav > .active > a, +.bs-sidebar .nav > .active:hover > a, +.bs-sidebar .nav > .active:focus > a { + font-weight: bold; + background-color: transparent; + border-right: 1px solid; +} + +/* Nav: second level (shown on .active) */ +.bs-sidebar .nav .nav { + display: none; /* Hide by default, but at >768px, show it */ + margin-bottom: 8px; +} +.bs-sidebar .nav .nav > li > a { + padding-top: 3px; + padding-bottom: 3px; + padding-left: 30px; + font-size: 90%; +} + +/* Show and affix the side nav when space allows it */ +@media (min-width: 992px) { + .bs-sidebar .nav > .active > ul { + display: block; + } + /* Widen the fixed sidebar */ + .bs-sidebar.affix, + .bs-sidebar.affix-bottom { + width: 213px; + } + .bs-sidebar.affix { + position: fixed; /* Undo the static from mobile first approach */ + top: 80px; + } + .bs-sidebar.affix-bottom { + position: absolute; /* Undo the static from mobile first approach */ + } + .bs-sidebar.affix-bottom .bs-sidenav, + .bs-sidebar.affix .bs-sidenav { + margin-top: 0; + margin-bottom: 0; + } +} +@media (min-width: 1200px) { + /* Widen the fixed sidebar again */ + .bs-sidebar.affix-bottom, + .bs-sidebar.affix { + width: 263px; + } +} \ No newline at end of file diff --git a/css/bootstrap-custom.min.css b/css/bootstrap-custom.min.css new file mode 100644 index 000000000..d85b1dcdf --- /dev/null +++ b/css/bootstrap-custom.min.css @@ -0,0 +1 @@ +/*! normalize.css v2.1.3 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden],template{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a{background:transparent}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#555;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#2fa4e7;text-decoration:none}a:hover,a:focus{color:#157ab5;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1;color:#317eac}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h1 small,h2 small,h3 small,h1 .small,h2 .small,h3 .small{font-size:65%}h4,h5,h6{margin-top:10px;margin-bottom:10px}h4 small,h5 small,h6 small,h4 .small,h5 .small,h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#2fa4e7}.text-primary:hover{color:#178acc}.text-warning{color:#c09853}.text-warning:hover{color:#a47e3c}.text-danger{color:#b94a48}.text-danger:hover{color:#953b39}.text-success{color:#468847}.text-success:hover{color:#356635}.text-info{color:#3a87ad}.text-info:hover{color:#2d6987}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}.list-inline>li:first-child{padding-left:0}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}@media(min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small,blockquote .small{display:block;line-height:1.428571429;color:#999}blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small,blockquote.pull-right .small{text-align:right}blockquote.pull-right small:before,blockquote.pull-right .small:before{content:''}blockquote.pull-right small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:20px;font-style:normal;line-height:1.428571429}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}@media(min-width:768px){.container{width:750px}}@media(min-width:992px){.container{width:970px}}@media(min-width:1200px){.container{width:1170px}}.row{margin-right:-15px;margin-left:-15px}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666666666666%}.col-xs-10{width:83.33333333333334%}.col-xs-9{width:75%}.col-xs-8{width:66.66666666666666%}.col-xs-7{width:58.333333333333336%}.col-xs-6{width:50%}.col-xs-5{width:41.66666666666667%}.col-xs-4{width:33.33333333333333%}.col-xs-3{width:25%}.col-xs-2{width:16.666666666666664%}.col-xs-1{width:8.333333333333332%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666666666666%}.col-xs-pull-10{right:83.33333333333334%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666666666666%}.col-xs-pull-7{right:58.333333333333336%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666666666667%}.col-xs-pull-4{right:33.33333333333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.666666666666664%}.col-xs-pull-1{right:8.333333333333332%}.col-xs-pull-0{right:0}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666666666666%}.col-xs-push-10{left:83.33333333333334%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666666666666%}.col-xs-push-7{left:58.333333333333336%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666666666667%}.col-xs-push-4{left:33.33333333333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.666666666666664%}.col-xs-push-1{left:8.333333333333332%}.col-xs-push-0{left:0}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666666666666%}.col-xs-offset-10{margin-left:83.33333333333334%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666666666666%}.col-xs-offset-7{margin-left:58.333333333333336%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666666666667%}.col-xs-offset-4{margin-left:33.33333333333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.666666666666664%}.col-xs-offset-1{margin-left:8.333333333333332%}.col-xs-offset-0{margin-left:0}@media(min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666666666666%}.col-sm-10{width:83.33333333333334%}.col-sm-9{width:75%}.col-sm-8{width:66.66666666666666%}.col-sm-7{width:58.333333333333336%}.col-sm-6{width:50%}.col-sm-5{width:41.66666666666667%}.col-sm-4{width:33.33333333333333%}.col-sm-3{width:25%}.col-sm-2{width:16.666666666666664%}.col-sm-1{width:8.333333333333332%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666666666666%}.col-sm-pull-10{right:83.33333333333334%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666666666666%}.col-sm-pull-7{right:58.333333333333336%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666666666667%}.col-sm-pull-4{right:33.33333333333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.666666666666664%}.col-sm-pull-1{right:8.333333333333332%}.col-sm-pull-0{right:0}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666666666666%}.col-sm-push-10{left:83.33333333333334%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666666666666%}.col-sm-push-7{left:58.333333333333336%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666666666667%}.col-sm-push-4{left:33.33333333333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.666666666666664%}.col-sm-push-1{left:8.333333333333332%}.col-sm-push-0{left:0}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666666666666%}.col-sm-offset-10{margin-left:83.33333333333334%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666666666666%}.col-sm-offset-7{margin-left:58.333333333333336%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666666666667%}.col-sm-offset-4{margin-left:33.33333333333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.666666666666664%}.col-sm-offset-1{margin-left:8.333333333333332%}.col-sm-offset-0{margin-left:0}}@media(min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666666666666%}.col-md-10{width:83.33333333333334%}.col-md-9{width:75%}.col-md-8{width:66.66666666666666%}.col-md-7{width:58.333333333333336%}.col-md-6{width:50%}.col-md-5{width:41.66666666666667%}.col-md-4{width:33.33333333333333%}.col-md-3{width:25%}.col-md-2{width:16.666666666666664%}.col-md-1{width:8.333333333333332%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666666666666%}.col-md-pull-10{right:83.33333333333334%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666666666666%}.col-md-pull-7{right:58.333333333333336%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666666666667%}.col-md-pull-4{right:33.33333333333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.666666666666664%}.col-md-pull-1{right:8.333333333333332%}.col-md-pull-0{right:0}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666666666666%}.col-md-push-10{left:83.33333333333334%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666666666666%}.col-md-push-7{left:58.333333333333336%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666666666667%}.col-md-push-4{left:33.33333333333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.666666666666664%}.col-md-push-1{left:8.333333333333332%}.col-md-push-0{left:0}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666666666666%}.col-md-offset-10{margin-left:83.33333333333334%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666666666666%}.col-md-offset-7{margin-left:58.333333333333336%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666666666667%}.col-md-offset-4{margin-left:33.33333333333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.666666666666664%}.col-md-offset-1{margin-left:8.333333333333332%}.col-md-offset-0{margin-left:0}}@media(min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666666666666%}.col-lg-10{width:83.33333333333334%}.col-lg-9{width:75%}.col-lg-8{width:66.66666666666666%}.col-lg-7{width:58.333333333333336%}.col-lg-6{width:50%}.col-lg-5{width:41.66666666666667%}.col-lg-4{width:33.33333333333333%}.col-lg-3{width:25%}.col-lg-2{width:16.666666666666664%}.col-lg-1{width:8.333333333333332%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666666666666%}.col-lg-pull-10{right:83.33333333333334%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666666666666%}.col-lg-pull-7{right:58.333333333333336%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666666666667%}.col-lg-pull-4{right:33.33333333333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.666666666666664%}.col-lg-pull-1{right:8.333333333333332%}.col-lg-pull-0{right:0}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666666666666%}.col-lg-push-10{left:83.33333333333334%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666666666666%}.col-lg-push-7{left:58.333333333333336%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666666666667%}.col-lg-push-4{left:33.33333333333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.666666666666664%}.col-lg-push-1{left:8.333333333333332%}.col-lg-push-0{left:0}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666666666666%}.col-lg-offset-10{margin-left:83.33333333333334%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666666666666%}.col-lg-offset-7{margin-left:58.333333333333336%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666666666667%}.col-lg-offset-4{margin-left:33.33333333333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.666666666666664%}.col-lg-offset-1{margin-left:8.333333333333332%}.col-lg-offset-0{margin-left:0}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*="col-"]{position:static;display:table-column;float:none}table td[class*="col-"],table th[class*="col-"]{display:table-cell;float:none}.table>thead>tr>.active,.table>tbody>tr>.active,.table>tfoot>tr>.active,.table>thead>.active>td,.table>tbody>.active>td,.table>tfoot>.active>td,.table>thead>.active>th,.table>tbody>.active>th,.table>tfoot>.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>.active:hover,.table-hover>tbody>.active:hover>td,.table-hover>tbody>.active:hover>th{background-color:#e8e8e8}.table>thead>tr>.success,.table>tbody>tr>.success,.table>tfoot>tr>.success,.table>thead>.success>td,.table>tbody>.success>td,.table>tfoot>.success>td,.table>thead>.success>th,.table>tbody>.success>th,.table>tfoot>.success>th{background-color:#dff0d8}.table-hover>tbody>tr>.success:hover,.table-hover>tbody>.success:hover>td,.table-hover>tbody>.success:hover>th{background-color:#d0e9c6}.table>thead>tr>.danger,.table>tbody>tr>.danger,.table>tfoot>tr>.danger,.table>thead>.danger>td,.table>tbody>.danger>td,.table>tfoot>.danger>td,.table>thead>.danger>th,.table>tbody>.danger>th,.table>tfoot>.danger>th{background-color:#f2dede}.table-hover>tbody>tr>.danger:hover,.table-hover>tbody>.danger:hover>td,.table-hover>tbody>.danger:hover>th{background-color:#ebcccc}.table>thead>tr>.warning,.table>tbody>tr>.warning,.table>tfoot>tr>.warning,.table>thead>.warning>td,.table>tbody>.warning>td,.table>tfoot>.warning>td,.table>thead>.warning>th,.table>tbody>.warning>th,.table>tfoot>.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>.warning:hover,.table-hover>tbody>.warning:hover>td,.table-hover>tbody>.warning:hover>th{background-color:#faf2cc}@media(max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:scroll;overflow-y:hidden;border:1px solid #ddd;-ms-overflow-style:-ms-autohiding-scrollbar;-webkit-overflow-scrolling:touch}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#555;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}output{display:block;padding-top:9px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6)}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="checkbox"][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm{height:auto}.input-lg{height:54px;padding:14px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:54px;line-height:54px}textarea.input-lg{height:auto}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#c09853}.has-warning .form-control{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#b94a48}.has-error .form-control{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#468847}.has-success .form-control{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.form-control-static{margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#959595}@media(min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block}.form-inline select.form-control{width:auto}.form-inline .radio,.form-inline .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:none;margin-left:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:9px;margin-top:0;margin-bottom:0}.form-horizontal .radio,.form-horizontal .checkbox{min-height:29px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-control-static{padding-top:9px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#555;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#555;background-color:#fff;border-color:rgba(0,0,0,0.1)}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#555;background-color:#ebebeb;border-color:rgba(0,0,0,0.1)}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:rgba(0,0,0,0.1)}.btn-default .badge{color:#fff;background-color:#fff}.btn-primary{color:#fff;background-color:#2fa4e7;border-color:#2fa4e7}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#1990d5;border-color:#1684c2}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#2fa4e7;border-color:#2fa4e7}.btn-primary .badge{color:#2fa4e7;background-color:#fff}.btn-warning{color:#fff;background-color:#dd5600;border-color:#dd5600}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#b44600;border-color:#a03e00}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#dd5600;border-color:#dd5600}.btn-warning .badge{color:#dd5600;background-color:#fff}.btn-danger{color:#fff;background-color:#c71c22;border-color:#c71c22}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#a3171c;border-color:#911419}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#c71c22;border-color:#c71c22}.btn-danger .badge{color:#c71c22;background-color:#fff}.btn-success{color:#fff;background-color:#73a839;border-color:#73a839}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#5e8a2f;border-color:#547a29}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#73a839;border-color:#73a839}.btn-success .badge{color:#73a839;background-color:#fff}.btn-info{color:#fff;background-color:#033c73;border-color:#033c73}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#02274b;border-color:#011d37}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#033c73;border-color:#033c73}.btn-info .badge{color:#033c73;background-color:#fff}.btn-link{font-weight:normal;color:#2fa4e7;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#157ab5;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg{padding:14px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';-webkit-font-smoothing:antialiased;font-style:normal;font-weight:normal;line-height:1;-moz-osx-font-smoothing:grayscale}.glyphicon:empty{width:1em}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#2fa4e7}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#2fa4e7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media(min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-lg>.btn{padding:14px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-right-radius:0;border-bottom-left-radius:4px;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child>.btn:last-child,.btn-group-vertical>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;border-collapse:separate;table-layout:fixed}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}[data-toggle="buttons"]>.btn>input[type="radio"],[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*="col-"]{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:54px;padding:14px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:54px;line-height:54px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:14px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn:first-child>.btn{margin-right:-1px}.input-group-btn:last-child>.btn{margin-left:-1px}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#2fa4e7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media(min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media(min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#2fa4e7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media(min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media(min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}@media(min-width:768px){.navbar{border-radius:4px}}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}@media(min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;padding-right:15px;padding-left:15px;overflow-x:visible;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,0.1);-webkit-overflow-scrolling:touch}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse.in{overflow-y:auto}@media(min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-right:0;padding-left:0}}.container>.navbar-header,.container>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.container>.navbar-header,.container>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media(min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030}@media(min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media(min-width:768px){.navbar>.container .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media(min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media(max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media(min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media(min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:6px;margin-right:-15px;margin-bottom:6px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}@media(min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block}.navbar-form select.form-control{width:auto}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"]{float:none;margin-left:0}}@media(max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media(min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-btn{margin-top:6px;margin-bottom:6px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media(min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#2fa4e7;border-color:#1995dc}.navbar-default .navbar-brand{color:#fff}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#fff;background-color:none}.navbar-default .navbar-text{color:#ddd}.navbar-default .navbar-nav>li>a{color:#fff}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#fff;background-color:#178acc}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#fff;background-color:#178acc}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ddd;background-color:transparent}.navbar-default .navbar-toggle{border-color:#178acc}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#178acc}.navbar-default .navbar-toggle .icon-bar{background-color:#fff}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#1995dc}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#fff;background-color:#178acc}@media(max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#fff}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:#178acc}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#178acc}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ddd;background-color:transparent}}.navbar-default .navbar-link{color:#fff}.navbar-default .navbar-link:hover{color:#fff}.navbar-inverse{background-color:#033c73;border-color:#022f5a}.navbar-inverse .navbar-brand{color:#fff}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:none}.navbar-inverse .navbar-text{color:#fff}.navbar-inverse .navbar-nav>li>a{color:#fff}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:#022f5a}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#022f5a}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#022f5a}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#022f5a}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#022a50}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#022f5a}@media(max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#022f5a}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#022f5a}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#fff}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:#022f5a}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#022f5a}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-inverse .navbar-link{color:#fff}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:8px 12px;margin-left:-1px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{background-color:#eee}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#999;cursor:default;background-color:#f5f5f5;border-color:#f5f5f5}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:14px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:#808080}.label-primary{background-color:#2fa4e7}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#178acc}.label-success{background-color:#73a839}.label-success[href]:hover,.label-success[href]:focus{background-color:#59822c}.label-info{background-color:#033c73}.label-info[href]:hover,.label-info[href]:focus{background-color:#022241}.label-warning{background-color:#dd5600}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#aa4200}.label-danger{background-color:#c71c22}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#9a161a}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#999;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#2fa4e7;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}.container .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{display:block;height:auto;max-width:100%;margin-right:auto;margin-left:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#2fa4e7}.thumbnail .caption{padding:9px;color:#555}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:bold}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-warning{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.alert-warning hr{border-top-color:#f8e5be}.alert-warning .alert-link{color:#a47e3c}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#2fa4e7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#73a839}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#033c73}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#dd5600}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#c71c22}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active,a.list-group-item.active:hover,a.list-group-item.active:focus{z-index:2;color:#fff;background-color:#2fa4e7;border-color:#2fa4e7}a.list-group-item.active .list-group-item-heading,a.list-group-item.active:hover .list-group-item-heading,a.list-group-item.active:focus .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text,a.list-group-item.active:hover .list-group-item-text,a.list-group-item.active:focus .list-group-item-text{color:#e6f4fc}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-body{padding:15px}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0}.panel>.list-group .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.panel>.list-group .list-group-item:last-child{border-bottom:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child th,.panel>.table>tbody:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:last-child>th,.panel>.table-responsive>.table-bordered>thead>tr:last-child>th,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th,.panel>.table-bordered>thead>tr:last-child>td,.panel>.table-responsive>.table-bordered>thead>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-group .panel{margin-bottom:0;overflow:hidden;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#555;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#ddd}.panel-primary>.panel-heading{color:#fff;background-color:#2fa4e7;border-color:#ddd}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-success{border-color:#ddd}.panel-success>.panel-heading{color:#468847;background-color:#73a839;border-color:#ddd}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-warning{border-color:#ddd}.panel-warning>.panel-heading{color:#c09853;background-color:#dd5600;border-color:#ddd}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-danger{border-color:#ddd}.panel-danger>.panel-heading{color:#b94a48;background-color:#c71c22;border-color:#ddd}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-info{border-color:#ddd}.panel-info>.panel-heading{color:#3a87ad;background-color:#033c73;border-color:#ddd}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;z-index:1050;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;outline:0;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicons-chevron-left,.carousel-control .glyphicons-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-xs,tr.visible-xs,th.visible-xs,td.visible-xs{display:none!important}@media(max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-xs.visible-sm{display:block!important}table.visible-xs.visible-sm{display:table}tr.visible-xs.visible-sm{display:table-row!important}th.visible-xs.visible-sm,td.visible-xs.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-xs.visible-md{display:block!important}table.visible-xs.visible-md{display:table}tr.visible-xs.visible-md{display:table-row!important}th.visible-xs.visible-md,td.visible-xs.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-xs.visible-lg{display:block!important}table.visible-xs.visible-lg{display:table}tr.visible-xs.visible-lg{display:table-row!important}th.visible-xs.visible-lg,td.visible-xs.visible-lg{display:table-cell!important}}.visible-sm,tr.visible-sm,th.visible-sm,td.visible-sm{display:none!important}@media(max-width:767px){.visible-sm.visible-xs{display:block!important}table.visible-sm.visible-xs{display:table}tr.visible-sm.visible-xs{display:table-row!important}th.visible-sm.visible-xs,td.visible-sm.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-sm.visible-md{display:block!important}table.visible-sm.visible-md{display:table}tr.visible-sm.visible-md{display:table-row!important}th.visible-sm.visible-md,td.visible-sm.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-sm.visible-lg{display:block!important}table.visible-sm.visible-lg{display:table}tr.visible-sm.visible-lg{display:table-row!important}th.visible-sm.visible-lg,td.visible-sm.visible-lg{display:table-cell!important}}.visible-md,tr.visible-md,th.visible-md,td.visible-md{display:none!important}@media(max-width:767px){.visible-md.visible-xs{display:block!important}table.visible-md.visible-xs{display:table}tr.visible-md.visible-xs{display:table-row!important}th.visible-md.visible-xs,td.visible-md.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-md.visible-sm{display:block!important}table.visible-md.visible-sm{display:table}tr.visible-md.visible-sm{display:table-row!important}th.visible-md.visible-sm,td.visible-md.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-md.visible-lg{display:block!important}table.visible-md.visible-lg{display:table}tr.visible-md.visible-lg{display:table-row!important}th.visible-md.visible-lg,td.visible-md.visible-lg{display:table-cell!important}}.visible-lg,tr.visible-lg,th.visible-lg,td.visible-lg{display:none!important}@media(max-width:767px){.visible-lg.visible-xs{display:block!important}table.visible-lg.visible-xs{display:table}tr.visible-lg.visible-xs{display:table-row!important}th.visible-lg.visible-xs,td.visible-lg.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-lg.visible-sm{display:block!important}table.visible-lg.visible-sm{display:table}tr.visible-lg.visible-sm{display:table-row!important}th.visible-lg.visible-sm,td.visible-lg.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-lg.visible-md{display:block!important}table.visible-lg.visible-md{display:table}tr.visible-lg.visible-md{display:table-row!important}th.visible-lg.visible-md,td.visible-lg.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}.hidden-xs{display:block!important}table.hidden-xs{display:table}tr.hidden-xs{display:table-row!important}th.hidden-xs,td.hidden-xs{display:table-cell!important}@media(max-width:767px){.hidden-xs,tr.hidden-xs,th.hidden-xs,td.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-xs.hidden-sm,tr.hidden-xs.hidden-sm,th.hidden-xs.hidden-sm,td.hidden-xs.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-xs.hidden-md,tr.hidden-xs.hidden-md,th.hidden-xs.hidden-md,td.hidden-xs.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-xs.hidden-lg,tr.hidden-xs.hidden-lg,th.hidden-xs.hidden-lg,td.hidden-xs.hidden-lg{display:none!important}}.hidden-sm{display:block!important}table.hidden-sm{display:table}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}@media(max-width:767px){.hidden-sm.hidden-xs,tr.hidden-sm.hidden-xs,th.hidden-sm.hidden-xs,td.hidden-sm.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-sm,tr.hidden-sm,th.hidden-sm,td.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-sm.hidden-md,tr.hidden-sm.hidden-md,th.hidden-sm.hidden-md,td.hidden-sm.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-sm.hidden-lg,tr.hidden-sm.hidden-lg,th.hidden-sm.hidden-lg,td.hidden-sm.hidden-lg{display:none!important}}.hidden-md{display:block!important}table.hidden-md{display:table}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}@media(max-width:767px){.hidden-md.hidden-xs,tr.hidden-md.hidden-xs,th.hidden-md.hidden-xs,td.hidden-md.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-md.hidden-sm,tr.hidden-md.hidden-sm,th.hidden-md.hidden-sm,td.hidden-md.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-md,tr.hidden-md,th.hidden-md,td.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-md.hidden-lg,tr.hidden-md.hidden-lg,th.hidden-md.hidden-lg,td.hidden-md.hidden-lg{display:none!important}}.hidden-lg{display:block!important}table.hidden-lg{display:table}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(max-width:767px){.hidden-lg.hidden-xs,tr.hidden-lg.hidden-xs,th.hidden-lg.hidden-xs,td.hidden-lg.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-lg.hidden-sm,tr.hidden-lg.hidden-sm,th.hidden-lg.hidden-sm,td.hidden-lg.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-lg.hidden-md,tr.hidden-lg.hidden-md,th.hidden-lg.hidden-md,td.hidden-lg.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-lg,tr.hidden-lg,th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print,tr.visible-print,th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print,tr.hidden-print,th.hidden-print,td.hidden-print{display:none!important}}.navbar{background-image:-webkit-linear-gradient(#54b4eb,#2fa4e7 60%,#1d9ce5);background-image:linear-gradient(#54b4eb,#2fa4e7 60%,#1d9ce5);background-repeat:no-repeat;border-bottom:1px solid #178acc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff54b4eb',endColorstr='#ff1d9ce5',GradientType=0);filter:none;-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar .navbar-nav>li>a,.navbar-brand{text-shadow:0 1px 0 rgba(0,0,0,0.1)}.navbar-inverse{background-image:-webkit-linear-gradient(#04519b,#044687 60%,#033769);background-image:linear-gradient(#04519b,#044687 60%,#033769);background-repeat:no-repeat;border-bottom:1px solid #022241;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff04519b',endColorstr='#ff033769',GradientType=0);filter:none}.btn{text-shadow:0 1px 0 rgba(0,0,0,0.1)}.btn .caret{border-top-color:#fff}.btn-default{background-image:-webkit-linear-gradient(#fff,#fff 60%,#f5f5f5);background-image:linear-gradient(#fff,#fff 60%,#f5f5f5);background-repeat:no-repeat;border-bottom:1px solid #e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff5f5f5',GradientType=0);filter:none}.btn-default:hover{color:#555}.btn-default .caret{border-top-color:#555}.btn-default{background-image:-webkit-linear-gradient(#fff,#fff 60%,#f5f5f5);background-image:linear-gradient(#fff,#fff 60%,#f5f5f5);background-repeat:no-repeat;border-bottom:1px solid #e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff5f5f5',GradientType=0);filter:none}.btn-primary{background-image:-webkit-linear-gradient(#54b4eb,#2fa4e7 60%,#1d9ce5);background-image:linear-gradient(#54b4eb,#2fa4e7 60%,#1d9ce5);background-repeat:no-repeat;border-bottom:1px solid #178acc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff54b4eb',endColorstr='#ff1d9ce5',GradientType=0);filter:none}.btn-success{background-image:-webkit-linear-gradient(#88c149,#73a839 60%,#699934);background-image:linear-gradient(#88c149,#73a839 60%,#699934);background-repeat:no-repeat;border-bottom:1px solid #59822c;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff88c149',endColorstr='#ff699934',GradientType=0);filter:none}.btn-info{background-image:-webkit-linear-gradient(#04519b,#033c73 60%,#02325f);background-image:linear-gradient(#04519b,#033c73 60%,#02325f);background-repeat:no-repeat;border-bottom:1px solid #022241;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff04519b',endColorstr='#ff02325f',GradientType=0);filter:none}.btn-warning{background-image:-webkit-linear-gradient(#ff6707,#dd5600 60%,#c94e00);background-image:linear-gradient(#ff6707,#dd5600 60%,#c94e00);background-repeat:no-repeat;border-bottom:1px solid #aa4200;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff6707',endColorstr='#ffc94e00',GradientType=0);filter:none}.btn-danger{background-image:-webkit-linear-gradient(#e12b31,#c71c22 60%,#b5191f);background-image:linear-gradient(#e12b31,#c71c22 60%,#b5191f);background-repeat:no-repeat;border-bottom:1px solid #9a161a;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe12b31',endColorstr='#ffb5191f',GradientType=0);filter:none}.pagination .active>a,.pagination .active>a:hover{border-color:#ddd}.panel-primary .panel-heading,.panel-success .panel-heading,.panel-warning .panel-heading,.panel-danger .panel-heading,.panel-info .panel-heading,.panel-primary .panel-title,.panel-success .panel-title,.panel-warning .panel-title,.panel-danger .panel-title,.panel-info .panel-title{color:#fff}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed} \ No newline at end of file diff --git a/css/bootstrap-responsive.css b/css/bootstrap-responsive.css old mode 100755 new mode 100644 diff --git a/css/bootstrap.css b/css/bootstrap.css old mode 100755 new mode 100644 diff --git a/css/default.css b/css/default.css index 7f3acfed2..8c9cd5363 100644 --- a/css/default.css +++ b/css/default.css @@ -181,7 +181,7 @@ body{ } .navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{ - color: white; + color: white; } .nav-list > .active > a, .navbar .navbar-inner .nav li a:hover { @@ -190,8 +190,20 @@ body{ } .navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{ - color: #A30000; + color: #A30000; } + +.dropdown-menu .active > a, +.dropdown-menu .active > a:hover { + background-image: none; +} + +.navbar-inverse .nav .dropdown .active > a, +.navbar-inverse .nav .dropdown .active > a:hover, +.navbar-inverse .nav .dropdown .active > a:focus { + background-color: #eeeeee; +} + .navbar .navbar-inner .dropdown-menu li a:hover{ background: #eeeeee; color: #c20000; diff --git a/css/font-awesome-4.0.3.css b/css/font-awesome-4.0.3.css new file mode 100644 index 000000000..048cff973 --- /dev/null +++ b/css/font-awesome-4.0.3.css @@ -0,0 +1,1338 @@ +/*! + * Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */ +/* FONT PATH + * -------------------------- */ +@font-face { + font-family: 'FontAwesome'; + src: url('../fonts/fontawesome-webfont.eot?v=4.0.3'); + src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg'); + font-weight: normal; + font-style: normal; +} +.fa { + display: inline-block; + font-family: FontAwesome; + font-style: normal; + font-weight: normal; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +/* makes the font 33% larger relative to the icon container */ +.fa-lg { + font-size: 1.3333333333333333em; + line-height: 0.75em; + vertical-align: -15%; +} +.fa-2x { + font-size: 2em; +} +.fa-3x { + font-size: 3em; +} +.fa-4x { + font-size: 4em; +} +.fa-5x { + font-size: 5em; +} +.fa-fw { + width: 1.2857142857142858em; + text-align: center; +} +.fa-ul { + padding-left: 0; + margin-left: 2.142857142857143em; + list-style-type: none; +} +.fa-ul > li { + position: relative; +} +.fa-li { + position: absolute; + left: -2.142857142857143em; + width: 2.142857142857143em; + top: 0.14285714285714285em; + text-align: center; +} +.fa-li.fa-lg { + left: -1.8571428571428572em; +} +.fa-border { + padding: .2em .25em .15em; + border: solid 0.08em #eeeeee; + border-radius: .1em; +} +.pull-right { + float: right; +} +.pull-left { + float: left; +} +.fa.pull-left { + margin-right: .3em; +} +.fa.pull-right { + margin-left: .3em; +} +.fa-spin { + -webkit-animation: spin 2s infinite linear; + -moz-animation: spin 2s infinite linear; + -o-animation: spin 2s infinite linear; + animation: spin 2s infinite linear; +} +@-moz-keyframes spin { + 0% { + -moz-transform: rotate(0deg); + } + 100% { + -moz-transform: rotate(359deg); + } +} +@-webkit-keyframes spin { + 0% { + -webkit-transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + } +} +@-o-keyframes spin { + 0% { + -o-transform: rotate(0deg); + } + 100% { + -o-transform: rotate(359deg); + } +} +@-ms-keyframes spin { + 0% { + -ms-transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); + } +} +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(359deg); + } +} +.fa-rotate-90 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); + -webkit-transform: rotate(90deg); + -moz-transform: rotate(90deg); + -ms-transform: rotate(90deg); + -o-transform: rotate(90deg); + transform: rotate(90deg); +} +.fa-rotate-180 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); + -webkit-transform: rotate(180deg); + -moz-transform: rotate(180deg); + -ms-transform: rotate(180deg); + -o-transform: rotate(180deg); + transform: rotate(180deg); +} +.fa-rotate-270 { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -webkit-transform: rotate(270deg); + -moz-transform: rotate(270deg); + -ms-transform: rotate(270deg); + -o-transform: rotate(270deg); + transform: rotate(270deg); +} +.fa-flip-horizontal { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1); + -webkit-transform: scale(-1, 1); + -moz-transform: scale(-1, 1); + -ms-transform: scale(-1, 1); + -o-transform: scale(-1, 1); + transform: scale(-1, 1); +} +.fa-flip-vertical { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1); + -webkit-transform: scale(1, -1); + -moz-transform: scale(1, -1); + -ms-transform: scale(1, -1); + -o-transform: scale(1, -1); + transform: scale(1, -1); +} +.fa-stack { + position: relative; + display: inline-block; + width: 2em; + height: 2em; + line-height: 2em; + vertical-align: middle; +} +.fa-stack-1x, +.fa-stack-2x { + position: absolute; + left: 0; + width: 100%; + text-align: center; +} +.fa-stack-1x { + line-height: inherit; +} +.fa-stack-2x { + font-size: 2em; +} +.fa-inverse { + color: #ffffff; +} +/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen + readers do not read off random characters that represent icons */ +.fa-glass:before { + content: "\f000"; +} +.fa-music:before { + content: "\f001"; +} +.fa-search:before { + content: "\f002"; +} +.fa-envelope-o:before { + content: "\f003"; +} +.fa-heart:before { + content: "\f004"; +} +.fa-star:before { + content: "\f005"; +} +.fa-star-o:before { + content: "\f006"; +} +.fa-user:before { + content: "\f007"; +} +.fa-film:before { + content: "\f008"; +} +.fa-th-large:before { + content: "\f009"; +} +.fa-th:before { + content: "\f00a"; +} +.fa-th-list:before { + content: "\f00b"; +} +.fa-check:before { + content: "\f00c"; +} +.fa-times:before { + content: "\f00d"; +} +.fa-search-plus:before { + content: "\f00e"; +} +.fa-search-minus:before { + content: "\f010"; +} +.fa-power-off:before { + content: "\f011"; +} +.fa-signal:before { + content: "\f012"; +} +.fa-gear:before, +.fa-cog:before { + content: "\f013"; +} +.fa-trash-o:before { + content: "\f014"; +} +.fa-home:before { + content: "\f015"; +} +.fa-file-o:before { + content: "\f016"; +} +.fa-clock-o:before { + content: "\f017"; +} +.fa-road:before { + content: "\f018"; +} +.fa-download:before { + content: "\f019"; +} +.fa-arrow-circle-o-down:before { + content: "\f01a"; +} +.fa-arrow-circle-o-up:before { + content: "\f01b"; +} +.fa-inbox:before { + content: "\f01c"; +} +.fa-play-circle-o:before { + content: "\f01d"; +} +.fa-rotate-right:before, +.fa-repeat:before { + content: "\f01e"; +} +.fa-refresh:before { + content: "\f021"; +} +.fa-list-alt:before { + content: "\f022"; +} +.fa-lock:before { + content: "\f023"; +} +.fa-flag:before { + content: "\f024"; +} +.fa-headphones:before { + content: "\f025"; +} +.fa-volume-off:before { + content: "\f026"; +} +.fa-volume-down:before { + content: "\f027"; +} +.fa-volume-up:before { + content: "\f028"; +} +.fa-qrcode:before { + content: "\f029"; +} +.fa-barcode:before { + content: "\f02a"; +} +.fa-tag:before { + content: "\f02b"; +} +.fa-tags:before { + content: "\f02c"; +} +.fa-book:before { + content: "\f02d"; +} +.fa-bookmark:before { + content: "\f02e"; +} +.fa-print:before { + content: "\f02f"; +} +.fa-camera:before { + content: "\f030"; +} +.fa-font:before { + content: "\f031"; +} +.fa-bold:before { + content: "\f032"; +} +.fa-italic:before { + content: "\f033"; +} +.fa-text-height:before { + content: "\f034"; +} +.fa-text-width:before { + content: "\f035"; +} +.fa-align-left:before { + content: "\f036"; +} +.fa-align-center:before { + content: "\f037"; +} +.fa-align-right:before { + content: "\f038"; +} +.fa-align-justify:before { + content: "\f039"; +} +.fa-list:before { + content: "\f03a"; +} +.fa-dedent:before, +.fa-outdent:before { + content: "\f03b"; +} +.fa-indent:before { + content: "\f03c"; +} +.fa-video-camera:before { + content: "\f03d"; +} +.fa-picture-o:before { + content: "\f03e"; +} +.fa-pencil:before { + content: "\f040"; +} +.fa-map-marker:before { + content: "\f041"; +} +.fa-adjust:before { + content: "\f042"; +} +.fa-tint:before { + content: "\f043"; +} +.fa-edit:before, +.fa-pencil-square-o:before { + content: "\f044"; +} +.fa-share-square-o:before { + content: "\f045"; +} +.fa-check-square-o:before { + content: "\f046"; +} +.fa-arrows:before { + content: "\f047"; +} +.fa-step-backward:before { + content: "\f048"; +} +.fa-fast-backward:before { + content: "\f049"; +} +.fa-backward:before { + content: "\f04a"; +} +.fa-play:before { + content: "\f04b"; +} +.fa-pause:before { + content: "\f04c"; +} +.fa-stop:before { + content: "\f04d"; +} +.fa-forward:before { + content: "\f04e"; +} +.fa-fast-forward:before { + content: "\f050"; +} +.fa-step-forward:before { + content: "\f051"; +} +.fa-eject:before { + content: "\f052"; +} +.fa-chevron-left:before { + content: "\f053"; +} +.fa-chevron-right:before { + content: "\f054"; +} +.fa-plus-circle:before { + content: "\f055"; +} +.fa-minus-circle:before { + content: "\f056"; +} +.fa-times-circle:before { + content: "\f057"; +} +.fa-check-circle:before { + content: "\f058"; +} +.fa-question-circle:before { + content: "\f059"; +} +.fa-info-circle:before { + content: "\f05a"; +} +.fa-crosshairs:before { + content: "\f05b"; +} +.fa-times-circle-o:before { + content: "\f05c"; +} +.fa-check-circle-o:before { + content: "\f05d"; +} +.fa-ban:before { + content: "\f05e"; +} +.fa-arrow-left:before { + content: "\f060"; +} +.fa-arrow-right:before { + content: "\f061"; +} +.fa-arrow-up:before { + content: "\f062"; +} +.fa-arrow-down:before { + content: "\f063"; +} +.fa-mail-forward:before, +.fa-share:before { + content: "\f064"; +} +.fa-expand:before { + content: "\f065"; +} +.fa-compress:before { + content: "\f066"; +} +.fa-plus:before { + content: "\f067"; +} +.fa-minus:before { + content: "\f068"; +} +.fa-asterisk:before { + content: "\f069"; +} +.fa-exclamation-circle:before { + content: "\f06a"; +} +.fa-gift:before { + content: "\f06b"; +} +.fa-leaf:before { + content: "\f06c"; +} +.fa-fire:before { + content: "\f06d"; +} +.fa-eye:before { + content: "\f06e"; +} +.fa-eye-slash:before { + content: "\f070"; +} +.fa-warning:before, +.fa-exclamation-triangle:before { + content: "\f071"; +} +.fa-plane:before { + content: "\f072"; +} +.fa-calendar:before { + content: "\f073"; +} +.fa-random:before { + content: "\f074"; +} +.fa-comment:before { + content: "\f075"; +} +.fa-magnet:before { + content: "\f076"; +} +.fa-chevron-up:before { + content: "\f077"; +} +.fa-chevron-down:before { + content: "\f078"; +} +.fa-retweet:before { + content: "\f079"; +} +.fa-shopping-cart:before { + content: "\f07a"; +} +.fa-folder:before { + content: "\f07b"; +} +.fa-folder-open:before { + content: "\f07c"; +} +.fa-arrows-v:before { + content: "\f07d"; +} +.fa-arrows-h:before { + content: "\f07e"; +} +.fa-bar-chart-o:before { + content: "\f080"; +} +.fa-twitter-square:before { + content: "\f081"; +} +.fa-facebook-square:before { + content: "\f082"; +} +.fa-camera-retro:before { + content: "\f083"; +} +.fa-key:before { + content: "\f084"; +} +.fa-gears:before, +.fa-cogs:before { + content: "\f085"; +} +.fa-comments:before { + content: "\f086"; +} +.fa-thumbs-o-up:before { + content: "\f087"; +} +.fa-thumbs-o-down:before { + content: "\f088"; +} +.fa-star-half:before { + content: "\f089"; +} +.fa-heart-o:before { + content: "\f08a"; +} +.fa-sign-out:before { + content: "\f08b"; +} +.fa-linkedin-square:before { + content: "\f08c"; +} +.fa-thumb-tack:before { + content: "\f08d"; +} +.fa-external-link:before { + content: "\f08e"; +} +.fa-sign-in:before { + content: "\f090"; +} +.fa-trophy:before { + content: "\f091"; +} +.fa-github-square:before { + content: "\f092"; +} +.fa-upload:before { + content: "\f093"; +} +.fa-lemon-o:before { + content: "\f094"; +} +.fa-phone:before { + content: "\f095"; +} +.fa-square-o:before { + content: "\f096"; +} +.fa-bookmark-o:before { + content: "\f097"; +} +.fa-phone-square:before { + content: "\f098"; +} +.fa-twitter:before { + content: "\f099"; +} +.fa-facebook:before { + content: "\f09a"; +} +.fa-github:before { + content: "\f09b"; +} +.fa-unlock:before { + content: "\f09c"; +} +.fa-credit-card:before { + content: "\f09d"; +} +.fa-rss:before { + content: "\f09e"; +} +.fa-hdd-o:before { + content: "\f0a0"; +} +.fa-bullhorn:before { + content: "\f0a1"; +} +.fa-bell:before { + content: "\f0f3"; +} +.fa-certificate:before { + content: "\f0a3"; +} +.fa-hand-o-right:before { + content: "\f0a4"; +} +.fa-hand-o-left:before { + content: "\f0a5"; +} +.fa-hand-o-up:before { + content: "\f0a6"; +} +.fa-hand-o-down:before { + content: "\f0a7"; +} +.fa-arrow-circle-left:before { + content: "\f0a8"; +} +.fa-arrow-circle-right:before { + content: "\f0a9"; +} +.fa-arrow-circle-up:before { + content: "\f0aa"; +} +.fa-arrow-circle-down:before { + content: "\f0ab"; +} +.fa-globe:before { + content: "\f0ac"; +} +.fa-wrench:before { + content: "\f0ad"; +} +.fa-tasks:before { + content: "\f0ae"; +} +.fa-filter:before { + content: "\f0b0"; +} +.fa-briefcase:before { + content: "\f0b1"; +} +.fa-arrows-alt:before { + content: "\f0b2"; +} +.fa-group:before, +.fa-users:before { + content: "\f0c0"; +} +.fa-chain:before, +.fa-link:before { + content: "\f0c1"; +} +.fa-cloud:before { + content: "\f0c2"; +} +.fa-flask:before { + content: "\f0c3"; +} +.fa-cut:before, +.fa-scissors:before { + content: "\f0c4"; +} +.fa-copy:before, +.fa-files-o:before { + content: "\f0c5"; +} +.fa-paperclip:before { + content: "\f0c6"; +} +.fa-save:before, +.fa-floppy-o:before { + content: "\f0c7"; +} +.fa-square:before { + content: "\f0c8"; +} +.fa-bars:before { + content: "\f0c9"; +} +.fa-list-ul:before { + content: "\f0ca"; +} +.fa-list-ol:before { + content: "\f0cb"; +} +.fa-strikethrough:before { + content: "\f0cc"; +} +.fa-underline:before { + content: "\f0cd"; +} +.fa-table:before { + content: "\f0ce"; +} +.fa-magic:before { + content: "\f0d0"; +} +.fa-truck:before { + content: "\f0d1"; +} +.fa-pinterest:before { + content: "\f0d2"; +} +.fa-pinterest-square:before { + content: "\f0d3"; +} +.fa-google-plus-square:before { + content: "\f0d4"; +} +.fa-google-plus:before { + content: "\f0d5"; +} +.fa-money:before { + content: "\f0d6"; +} +.fa-caret-down:before { + content: "\f0d7"; +} +.fa-caret-up:before { + content: "\f0d8"; +} +.fa-caret-left:before { + content: "\f0d9"; +} +.fa-caret-right:before { + content: "\f0da"; +} +.fa-columns:before { + content: "\f0db"; +} +.fa-unsorted:before, +.fa-sort:before { + content: "\f0dc"; +} +.fa-sort-down:before, +.fa-sort-asc:before { + content: "\f0dd"; +} +.fa-sort-up:before, +.fa-sort-desc:before { + content: "\f0de"; +} +.fa-envelope:before { + content: "\f0e0"; +} +.fa-linkedin:before { + content: "\f0e1"; +} +.fa-rotate-left:before, +.fa-undo:before { + content: "\f0e2"; +} +.fa-legal:before, +.fa-gavel:before { + content: "\f0e3"; +} +.fa-dashboard:before, +.fa-tachometer:before { + content: "\f0e4"; +} +.fa-comment-o:before { + content: "\f0e5"; +} +.fa-comments-o:before { + content: "\f0e6"; +} +.fa-flash:before, +.fa-bolt:before { + content: "\f0e7"; +} +.fa-sitemap:before { + content: "\f0e8"; +} +.fa-umbrella:before { + content: "\f0e9"; +} +.fa-paste:before, +.fa-clipboard:before { + content: "\f0ea"; +} +.fa-lightbulb-o:before { + content: "\f0eb"; +} +.fa-exchange:before { + content: "\f0ec"; +} +.fa-cloud-download:before { + content: "\f0ed"; +} +.fa-cloud-upload:before { + content: "\f0ee"; +} +.fa-user-md:before { + content: "\f0f0"; +} +.fa-stethoscope:before { + content: "\f0f1"; +} +.fa-suitcase:before { + content: "\f0f2"; +} +.fa-bell-o:before { + content: "\f0a2"; +} +.fa-coffee:before { + content: "\f0f4"; +} +.fa-cutlery:before { + content: "\f0f5"; +} +.fa-file-text-o:before { + content: "\f0f6"; +} +.fa-building-o:before { + content: "\f0f7"; +} +.fa-hospital-o:before { + content: "\f0f8"; +} +.fa-ambulance:before { + content: "\f0f9"; +} +.fa-medkit:before { + content: "\f0fa"; +} +.fa-fighter-jet:before { + content: "\f0fb"; +} +.fa-beer:before { + content: "\f0fc"; +} +.fa-h-square:before { + content: "\f0fd"; +} +.fa-plus-square:before { + content: "\f0fe"; +} +.fa-angle-double-left:before { + content: "\f100"; +} +.fa-angle-double-right:before { + content: "\f101"; +} +.fa-angle-double-up:before { + content: "\f102"; +} +.fa-angle-double-down:before { + content: "\f103"; +} +.fa-angle-left:before { + content: "\f104"; +} +.fa-angle-right:before { + content: "\f105"; +} +.fa-angle-up:before { + content: "\f106"; +} +.fa-angle-down:before { + content: "\f107"; +} +.fa-desktop:before { + content: "\f108"; +} +.fa-laptop:before { + content: "\f109"; +} +.fa-tablet:before { + content: "\f10a"; +} +.fa-mobile-phone:before, +.fa-mobile:before { + content: "\f10b"; +} +.fa-circle-o:before { + content: "\f10c"; +} +.fa-quote-left:before { + content: "\f10d"; +} +.fa-quote-right:before { + content: "\f10e"; +} +.fa-spinner:before { + content: "\f110"; +} +.fa-circle:before { + content: "\f111"; +} +.fa-mail-reply:before, +.fa-reply:before { + content: "\f112"; +} +.fa-github-alt:before { + content: "\f113"; +} +.fa-folder-o:before { + content: "\f114"; +} +.fa-folder-open-o:before { + content: "\f115"; +} +.fa-smile-o:before { + content: "\f118"; +} +.fa-frown-o:before { + content: "\f119"; +} +.fa-meh-o:before { + content: "\f11a"; +} +.fa-gamepad:before { + content: "\f11b"; +} +.fa-keyboard-o:before { + content: "\f11c"; +} +.fa-flag-o:before { + content: "\f11d"; +} +.fa-flag-checkered:before { + content: "\f11e"; +} +.fa-terminal:before { + content: "\f120"; +} +.fa-code:before { + content: "\f121"; +} +.fa-reply-all:before { + content: "\f122"; +} +.fa-mail-reply-all:before { + content: "\f122"; +} +.fa-star-half-empty:before, +.fa-star-half-full:before, +.fa-star-half-o:before { + content: "\f123"; +} +.fa-location-arrow:before { + content: "\f124"; +} +.fa-crop:before { + content: "\f125"; +} +.fa-code-fork:before { + content: "\f126"; +} +.fa-unlink:before, +.fa-chain-broken:before { + content: "\f127"; +} +.fa-question:before { + content: "\f128"; +} +.fa-info:before { + content: "\f129"; +} +.fa-exclamation:before { + content: "\f12a"; +} +.fa-superscript:before { + content: "\f12b"; +} +.fa-subscript:before { + content: "\f12c"; +} +.fa-eraser:before { + content: "\f12d"; +} +.fa-puzzle-piece:before { + content: "\f12e"; +} +.fa-microphone:before { + content: "\f130"; +} +.fa-microphone-slash:before { + content: "\f131"; +} +.fa-shield:before { + content: "\f132"; +} +.fa-calendar-o:before { + content: "\f133"; +} +.fa-fire-extinguisher:before { + content: "\f134"; +} +.fa-rocket:before { + content: "\f135"; +} +.fa-maxcdn:before { + content: "\f136"; +} +.fa-chevron-circle-left:before { + content: "\f137"; +} +.fa-chevron-circle-right:before { + content: "\f138"; +} +.fa-chevron-circle-up:before { + content: "\f139"; +} +.fa-chevron-circle-down:before { + content: "\f13a"; +} +.fa-html5:before { + content: "\f13b"; +} +.fa-css3:before { + content: "\f13c"; +} +.fa-anchor:before { + content: "\f13d"; +} +.fa-unlock-alt:before { + content: "\f13e"; +} +.fa-bullseye:before { + content: "\f140"; +} +.fa-ellipsis-h:before { + content: "\f141"; +} +.fa-ellipsis-v:before { + content: "\f142"; +} +.fa-rss-square:before { + content: "\f143"; +} +.fa-play-circle:before { + content: "\f144"; +} +.fa-ticket:before { + content: "\f145"; +} +.fa-minus-square:before { + content: "\f146"; +} +.fa-minus-square-o:before { + content: "\f147"; +} +.fa-level-up:before { + content: "\f148"; +} +.fa-level-down:before { + content: "\f149"; +} +.fa-check-square:before { + content: "\f14a"; +} +.fa-pencil-square:before { + content: "\f14b"; +} +.fa-external-link-square:before { + content: "\f14c"; +} +.fa-share-square:before { + content: "\f14d"; +} +.fa-compass:before { + content: "\f14e"; +} +.fa-toggle-down:before, +.fa-caret-square-o-down:before { + content: "\f150"; +} +.fa-toggle-up:before, +.fa-caret-square-o-up:before { + content: "\f151"; +} +.fa-toggle-right:before, +.fa-caret-square-o-right:before { + content: "\f152"; +} +.fa-euro:before, +.fa-eur:before { + content: "\f153"; +} +.fa-gbp:before { + content: "\f154"; +} +.fa-dollar:before, +.fa-usd:before { + content: "\f155"; +} +.fa-rupee:before, +.fa-inr:before { + content: "\f156"; +} +.fa-cny:before, +.fa-rmb:before, +.fa-yen:before, +.fa-jpy:before { + content: "\f157"; +} +.fa-ruble:before, +.fa-rouble:before, +.fa-rub:before { + content: "\f158"; +} +.fa-won:before, +.fa-krw:before { + content: "\f159"; +} +.fa-bitcoin:before, +.fa-btc:before { + content: "\f15a"; +} +.fa-file:before { + content: "\f15b"; +} +.fa-file-text:before { + content: "\f15c"; +} +.fa-sort-alpha-asc:before { + content: "\f15d"; +} +.fa-sort-alpha-desc:before { + content: "\f15e"; +} +.fa-sort-amount-asc:before { + content: "\f160"; +} +.fa-sort-amount-desc:before { + content: "\f161"; +} +.fa-sort-numeric-asc:before { + content: "\f162"; +} +.fa-sort-numeric-desc:before { + content: "\f163"; +} +.fa-thumbs-up:before { + content: "\f164"; +} +.fa-thumbs-down:before { + content: "\f165"; +} +.fa-youtube-square:before { + content: "\f166"; +} +.fa-youtube:before { + content: "\f167"; +} +.fa-xing:before { + content: "\f168"; +} +.fa-xing-square:before { + content: "\f169"; +} +.fa-youtube-play:before { + content: "\f16a"; +} +.fa-dropbox:before { + content: "\f16b"; +} +.fa-stack-overflow:before { + content: "\f16c"; +} +.fa-instagram:before { + content: "\f16d"; +} +.fa-flickr:before { + content: "\f16e"; +} +.fa-adn:before { + content: "\f170"; +} +.fa-bitbucket:before { + content: "\f171"; +} +.fa-bitbucket-square:before { + content: "\f172"; +} +.fa-tumblr:before { + content: "\f173"; +} +.fa-tumblr-square:before { + content: "\f174"; +} +.fa-long-arrow-down:before { + content: "\f175"; +} +.fa-long-arrow-up:before { + content: "\f176"; +} +.fa-long-arrow-left:before { + content: "\f177"; +} +.fa-long-arrow-right:before { + content: "\f178"; +} +.fa-apple:before { + content: "\f179"; +} +.fa-windows:before { + content: "\f17a"; +} +.fa-android:before { + content: "\f17b"; +} +.fa-linux:before { + content: "\f17c"; +} +.fa-dribbble:before { + content: "\f17d"; +} +.fa-skype:before { + content: "\f17e"; +} +.fa-foursquare:before { + content: "\f180"; +} +.fa-trello:before { + content: "\f181"; +} +.fa-female:before { + content: "\f182"; +} +.fa-male:before { + content: "\f183"; +} +.fa-gittip:before { + content: "\f184"; +} +.fa-sun-o:before { + content: "\f185"; +} +.fa-moon-o:before { + content: "\f186"; +} +.fa-archive:before { + content: "\f187"; +} +.fa-bug:before { + content: "\f188"; +} +.fa-vk:before { + content: "\f189"; +} +.fa-weibo:before { + content: "\f18a"; +} +.fa-renren:before { + content: "\f18b"; +} +.fa-pagelines:before { + content: "\f18c"; +} +.fa-stack-exchange:before { + content: "\f18d"; +} +.fa-arrow-circle-o-right:before { + content: "\f18e"; +} +.fa-arrow-circle-o-left:before { + content: "\f190"; +} +.fa-toggle-left:before, +.fa-caret-square-o-left:before { + content: "\f191"; +} +.fa-dot-circle-o:before { + content: "\f192"; +} +.fa-wheelchair:before { + content: "\f193"; +} +.fa-vimeo-square:before { + content: "\f194"; +} +.fa-turkish-lira:before, +.fa-try:before { + content: "\f195"; +} +.fa-plus-square-o:before { + content: "\f196"; +} diff --git a/css/highlight.css b/css/highlight.css new file mode 100644 index 000000000..da7fdb9d5 --- /dev/null +++ b/css/highlight.css @@ -0,0 +1,125 @@ +/* +This is the GitHub theme for highlight.js + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; padding: 0.5em; + color: #333; +} + +.hljs-comment, +.hljs-template_comment, +.diff .hljs-header, +.hljs-javadoc { + color: #998; + font-style: italic +} + +.hljs-keyword, +.css .rule .hljs-keyword, +.hljs-winutils, +.javascript .hljs-title, +.nginx .hljs-title, +.hljs-subst, +.hljs-request, +.hljs-status { + color: #333; + font-weight: bold +} + +.hljs-number, +.hljs-hexcolor, +.ruby .hljs-constant { + color: #099; +} + +.hljs-string, +.hljs-tag .hljs-value, +.hljs-phpdoc, +.tex .hljs-formula { + color: #d14 +} + +.hljs-title, +.hljs-id, +.coffeescript .hljs-params, +.scss .hljs-preprocessor { + color: #900; + font-weight: bold +} + +.javascript .hljs-title, +.lisp .hljs-title, +.clojure .hljs-title, +.hljs-subst { + font-weight: normal +} + +.hljs-class .hljs-title, +.haskell .hljs-type, +.vhdl .hljs-literal, +.tex .hljs-command { + color: #458; + font-weight: bold +} + +.hljs-tag, +.hljs-tag .hljs-title, +.hljs-rules .hljs-property, +.django .hljs-tag .hljs-keyword { + color: #000080; + font-weight: normal +} + +.hljs-attribute, +.hljs-variable, +.lisp .hljs-body { + color: #008080 +} + +.hljs-regexp { + color: #009926 +} + +.hljs-symbol, +.ruby .hljs-symbol .hljs-string, +.lisp .hljs-keyword, +.tex .hljs-special, +.hljs-prompt { + color: #990073 +} + +.hljs-built_in, +.lisp .hljs-title, +.clojure .hljs-built_in { + color: #0086b3 +} + +.hljs-preprocessor, +.hljs-pragma, +.hljs-pi, +.hljs-doctype, +.hljs-shebang, +.hljs-cdata { + color: #999; + font-weight: bold +} + +.hljs-deletion { + background: #fdd +} + +.hljs-addition { + background: #dfd +} + +.diff .hljs-change { + background: #0086b3 +} + +.hljs-chunk { + color: #aaa +} diff --git a/css/prettify-1.0.css b/css/prettify-1.0.css new file mode 100644 index 000000000..e0df24552 --- /dev/null +++ b/css/prettify-1.0.css @@ -0,0 +1,28 @@ +.com { color: #93a1a1; } +.lit { color: #195f91; } +.pun, .opn, .clo { color: #93a1a1; } +.fun { color: #dc322f; } +.str, .atv { color: #D14; } +.kwd, .prettyprint .tag { color: #1e347b; } +.typ, .atn, .dec, .var { color: teal; } +.pln { color: #48484c; } + +.prettyprint { + padding: 8px; +} +.prettyprint.linenums { + -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; + -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; + box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; +} + +/* Specify class=linenums on a pre to get line numbering */ +ol.linenums { + margin: 0 0 0 33px; /* IE indents via margin-left */ +} +ol.linenums li { + padding-left: 12px; + color: #bebec5; + line-height: 20px; + text-shadow: 0 1px 0 #fff; +} diff --git a/fonts/fontawesome-webfont.eot b/fonts/fontawesome-webfont.eot new file mode 100644 index 000000000..7c79c6a6b Binary files /dev/null and b/fonts/fontawesome-webfont.eot differ diff --git a/fonts/fontawesome-webfont.svg b/fonts/fontawesome-webfont.svg new file mode 100644 index 000000000..45fdf3383 --- /dev/null +++ b/fonts/fontawesome-webfont.svg @@ -0,0 +1,414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fonts/fontawesome-webfont.ttf b/fonts/fontawesome-webfont.ttf new file mode 100644 index 000000000..e89738de5 Binary files /dev/null and b/fonts/fontawesome-webfont.ttf differ diff --git a/fonts/fontawesome-webfont.woff b/fonts/fontawesome-webfont.woff new file mode 100644 index 000000000..8c1748aab Binary files /dev/null and b/fonts/fontawesome-webfont.woff differ diff --git a/img/.DS_Store b/img/.DS_Store new file mode 100644 index 000000000..ad96cb498 Binary files /dev/null and b/img/.DS_Store differ diff --git a/img/sponsors/.DS_Store b/img/sponsors/.DS_Store new file mode 100644 index 000000000..24ff55088 Binary files /dev/null and b/img/sponsors/.DS_Store differ diff --git a/img/sponsors/1-simple-energy.jpg b/img/sponsors/1-simple-energy.jpg deleted file mode 100644 index dfd56dace..000000000 Binary files a/img/sponsors/1-simple-energy.jpg and /dev/null differ diff --git a/index.html b/index.html index 145997178..ecaa4d8cb 100644 --- a/index.html +++ b/index.html @@ -1,65 +1,74 @@ - - - Django REST framework - Web APIs for Django - - - - - - - - - - + + + + Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -149,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -187,29 +335,118 @@ a.fusion-poweredby { -->
    + +
  • + Django REST framework +
  • + + + + +
  • + Requirements +
  • + + + + + +
  • + Installation +
  • + + + + + +
  • + Example +
  • + + + + + +
  • + Quickstart +
  • + + + + + +
  • + Tutorial +
  • + + + + + +
  • + API Guide +
  • + + + + + +
  • + Topics +
  • + + + + + +
  • + Development +
  • + + + + + +
  • + Support +
  • + + + + + +
  • + Security +
  • + + + + + +
  • + License +
  • + + + + + + +
    +
    + +
    + + +
    + +

    @@ -232,25 +469,21 @@ a.fusion-poweredby { clip: rect(0,0,0,0); border: 0;">Django REST Framework -Django REST Framework +Django REST Framework

    - -

    Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.

    Some reasons you might want to use REST framework:


    -

    Screenshot

    +

    Screenshot

    Above: Screenshot from the browsable API

    Requirements

    REST framework requires the following:

    @@ -271,21 +504,21 @@ a.fusion-poweredby {

    Note: The oauth2 Python package is badly misnamed, and actually provides OAuth 1.0a support. Also note that packages required for both OAuth 1.0a, and OAuth 2.0 are not yet Python 3 compatible.

    Installation

    Install using pip, including any optional packages you want...

    -
    pip install djangorestframework
    +
    pip install djangorestframework
     pip install markdown       # Markdown support for the browsable API.
     pip install django-filter  # Filtering support
     

    ...or clone the project from github.

    -
    git clone git@github.com:tomchristie/django-rest-framework.git
    +
    git clone git@github.com:tomchristie/django-rest-framework.git
     

    Add 'rest_framework' to your INSTALLED_APPS setting.

    -
    INSTALLED_APPS = (
    +
    INSTALLED_APPS = (
         ...
         'rest_framework',
     )
     

    If 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 urls.py file.

    -
    urlpatterns = [
    +
    urlpatterns = [
         ...
         url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
     ]
    @@ -295,7 +528,7 @@ pip install django-filter  # Filtering support
     

    Let's take a look at a quick example of using REST framework to build a simple model-backed API.

    We'll create a read-write API for accessing information on the users of our project.

    Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK. Start off by adding the following to your settings.py module:

    -
    REST_FRAMEWORK = {
    +
    REST_FRAMEWORK = {
         # Use Django's standard `django.contrib.auth` permissions,
         # or allow read-only access for unauthenticated users.
         'DEFAULT_PERMISSION_CLASSES': [
    @@ -306,7 +539,7 @@ pip install django-filter  # Filtering support
     

    Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS.

    We're ready to create our API now. Here's our project's root urls.py module:

    -
    from django.conf.urls import url, include
    +
    from django.conf.urls import url, include
     from django.contrib.auth.models import User
     from rest_framework import routers, serializers, viewsets
     
    @@ -334,65 +567,66 @@ 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.

    +

    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

    @@ -424,42 +658,52 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/js/base.js b/js/base.js new file mode 100644 index 000000000..7f18720c9 --- /dev/null +++ b/js/base.js @@ -0,0 +1,53 @@ + +/* Highlight */ +$( document ).ready(function() { + hljs.initHighlightingOnLoad(); + $('table').addClass('table'); +}); + + +/* Scrollspy */ +var navHeight = $('.navbar').outerHeight(true) + 10 + +$('body').scrollspy({ + target: '.bs-sidebar', + offset: navHeight +}) + + +/* Prevent disabled links from causing a page reload */ +$("li.disabled a").click(function() { + event.preventDefault(); +}); + + +/* Adjust the scroll height of anchors to compensate for the fixed navbar */ +window.disableShift = false; +var shiftWindow = function() { + if (window.disableShift) { + window.disableShift = false; + } else { + /* If we're at the bottom of the page, don't erronously scroll up */ + var scrolledToBottomOfPage = ( + (window.innerHeight + window.scrollY) >= document.body.offsetHeight + ); + if (!scrolledToBottomOfPage) { + scrollBy(0, -60); + }; + }; +}; +if (location.hash) {shiftWindow();} +window.addEventListener("hashchange", shiftWindow); + + +/* Deal with clicks on nav links that do not change the current anchor link. */ +$("ul.nav a" ).click(function() { + var href = this.href; + var suffix = location.hash; + var matchesCurrentHash = (href.indexOf(suffix, href.length - suffix.length) !== -1); + if (location.hash && matchesCurrentHash) { + /* Force a single 'hashchange' event to occur after the click event */ + window.disableShift = true; + location.hash=''; + }; +}); diff --git a/js/bootstrap-2.1.1-min.js b/js/bootstrap-2.1.1-min.js old mode 100755 new mode 100644 diff --git a/js/bootstrap-3.0.3.min.js b/js/bootstrap-3.0.3.min.js new file mode 100644 index 000000000..1a6258efc --- /dev/null +++ b/js/bootstrap-3.0.3.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.0.3 (http://getbootstrap.com) + * Copyright 2013 Twitter, Inc. + * Licensed under http://www.apache.org/licenses/LICENSE-2.0 + */ + +if("undefined"==typeof jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]'),b=!0;if(a.length){var c=this.$element.find("input");"radio"===c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?b=!1:a.find(".active").removeClass("active")),b&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}b&&this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid.bs.carousel",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid.bs.carousel")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid.bs.carousel")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(''}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(jQuery); \ No newline at end of file diff --git a/js/highlight.pack.js b/js/highlight.pack.js new file mode 100644 index 000000000..75d830c61 --- /dev/null +++ b/js/highlight.pack.js @@ -0,0 +1 @@ +var hljs=new function(){function k(v){return v.replace(/&/gm,"&").replace(//gm,">")}function t(v){return v.nodeName.toLowerCase()}function i(w,x){var v=w&&w.exec(x);return v&&v.index==0}function d(v){return Array.prototype.map.call(v.childNodes,function(w){if(w.nodeType==3){return b.useBR?w.nodeValue.replace(/\n/g,""):w.nodeValue}if(t(w)=="br"){return"\n"}return d(w)}).join("")}function r(w){var v=(w.className+" "+(w.parentNode?w.parentNode.className:"")).split(/\s+/);v=v.map(function(x){return x.replace(/^language-/,"")});return v.filter(function(x){return j(x)||x=="no-highlight"})[0]}function o(x,y){var v={};for(var w in x){v[w]=x[w]}if(y){for(var w in y){v[w]=y[w]}}return v}function u(x){var v=[];(function w(y,z){for(var A=y.firstChild;A;A=A.nextSibling){if(A.nodeType==3){z+=A.nodeValue.length}else{if(t(A)=="br"){z+=1}else{if(A.nodeType==1){v.push({event:"start",offset:z,node:A});z=w(A,z);v.push({event:"stop",offset:z,node:A})}}}}return z})(x,0);return v}function q(w,y,C){var x=0;var F="";var z=[];function B(){if(!w.length||!y.length){return w.length?w:y}if(w[0].offset!=y[0].offset){return(w[0].offset"}function E(G){F+=""}function v(G){(G.event=="start"?A:E)(G.node)}while(w.length||y.length){var D=B();F+=k(C.substr(x,D[0].offset-x));x=D[0].offset;if(D==w){z.reverse().forEach(E);do{v(D.splice(0,1)[0]);D=B()}while(D==w&&D.length&&D[0].offset==x);z.reverse().forEach(A)}else{if(D[0].event=="start"){z.push(D[0].node)}else{z.pop()}v(D.splice(0,1)[0])}}return F+k(C.substr(x))}function m(y){function v(z){return(z&&z.source)||z}function w(A,z){return RegExp(v(A),"m"+(y.cI?"i":"")+(z?"g":""))}function x(D,C){if(D.compiled){return}D.compiled=true;D.k=D.k||D.bK;if(D.k){var z={};function E(G,F){if(y.cI){F=F.toLowerCase()}F.split(" ").forEach(function(H){var I=H.split("|");z[I[0]]=[G,I[1]?Number(I[1]):1]})}if(typeof D.k=="string"){E("keyword",D.k)}else{Object.keys(D.k).forEach(function(F){E(F,D.k[F])})}D.k=z}D.lR=w(D.l||/\b[A-Za-z0-9_]+\b/,true);if(C){if(D.bK){D.b=D.bK.split(" ").join("|")}if(!D.b){D.b=/\B|\b/}D.bR=w(D.b);if(!D.e&&!D.eW){D.e=/\B|\b/}if(D.e){D.eR=w(D.e)}D.tE=v(D.e)||"";if(D.eW&&C.tE){D.tE+=(D.e?"|":"")+C.tE}}if(D.i){D.iR=w(D.i)}if(D.r===undefined){D.r=1}if(!D.c){D.c=[]}var B=[];D.c.forEach(function(F){if(F.v){F.v.forEach(function(G){B.push(o(F,G))})}else{B.push(F=="self"?D:F)}});D.c=B;D.c.forEach(function(F){x(F,D)});if(D.starts){x(D.starts,C)}var A=D.c.map(function(F){return F.bK?"\\.?\\b("+F.b+")\\b\\.?":F.b}).concat([D.tE]).concat([D.i]).map(v).filter(Boolean);D.t=A.length?w(A.join("|"),true):{exec:function(F){return null}};D.continuation={}}x(y)}function c(S,L,J,R){function v(U,V){for(var T=0;T";U+=Z+'">';return U+X+Y}function N(){var U=k(C);if(!I.k){return U}var T="";var X=0;I.lR.lastIndex=0;var V=I.lR.exec(U);while(V){T+=U.substr(X,V.index-X);var W=E(I,V);if(W){H+=W[1];T+=w(W[0],V[0])}else{T+=V[0]}X=I.lR.lastIndex;V=I.lR.exec(U)}return T+U.substr(X)}function F(){if(I.sL&&!f[I.sL]){return k(C)}var T=I.sL?c(I.sL,C,true,I.continuation.top):g(C);if(I.r>0){H+=T.r}if(I.subLanguageMode=="continuous"){I.continuation.top=T.top}return w(T.language,T.value,false,true)}function Q(){return I.sL!==undefined?F():N()}function P(V,U){var T=V.cN?w(V.cN,"",true):"";if(V.rB){D+=T;C=""}else{if(V.eB){D+=k(U)+T;C=""}else{D+=T;C=U}}I=Object.create(V,{parent:{value:I}})}function G(T,X){C+=T;if(X===undefined){D+=Q();return 0}var V=v(X,I);if(V){D+=Q();P(V,X);return V.rB?0:X.length}var W=z(I,X);if(W){var U=I;if(!(U.rE||U.eE)){C+=X}D+=Q();do{if(I.cN){D+=""}H+=I.r;I=I.parent}while(I!=W.parent);if(U.eE){D+=k(X)}C="";if(W.starts){P(W.starts,"")}return U.rE?0:X.length}if(A(X,I)){throw new Error('Illegal lexeme "'+X+'" for mode "'+(I.cN||"")+'"')}C+=X;return X.length||1}var M=j(S);if(!M){throw new Error('Unknown language: "'+S+'"')}m(M);var I=R||M;var D="";for(var K=I;K!=M;K=K.parent){if(K.cN){D=w(K.cN,D,true)}}var C="";var H=0;try{var B,y,x=0;while(true){I.t.lastIndex=x;B=I.t.exec(L);if(!B){break}y=G(L.substr(x,B.index-x),B[0]);x=B.index+y}G(L.substr(x));for(var K=I;K.parent;K=K.parent){if(K.cN){D+=""}}return{r:H,value:D,language:S,top:I}}catch(O){if(O.message.indexOf("Illegal")!=-1){return{r:0,value:k(L)}}else{throw O}}}function g(y,x){x=x||b.languages||Object.keys(f);var v={r:0,value:k(y)};var w=v;x.forEach(function(z){if(!j(z)){return}var A=c(z,y,false);A.language=z;if(A.r>w.r){w=A}if(A.r>v.r){w=v;v=A}});if(w.language){v.second_best=w}return v}function h(v){if(b.tabReplace){v=v.replace(/^((<[^>]+>|\t)+)/gm,function(w,z,y,x){return z.replace(/\t/g,b.tabReplace)})}if(b.useBR){v=v.replace(/\n/g,"
    ")}return v}function p(z){var y=d(z);var A=r(z);if(A=="no-highlight"){return}var v=A?c(A,y,true):g(y);var w=u(z);if(w.length){var x=document.createElementNS("http://www.w3.org/1999/xhtml","pre");x.innerHTML=v.value;v.value=q(w,u(x),y)}v.value=h(v.value);z.innerHTML=v.value;z.className+=" hljs "+(!A&&v.language||"");z.result={language:v.language,re:v.r};if(v.second_best){z.second_best={language:v.second_best.language,re:v.second_best.r}}}var b={classPrefix:"hljs-",tabReplace:null,useBR:false,languages:undefined};function s(v){b=o(b,v)}function l(){if(l.called){return}l.called=true;var v=document.querySelectorAll("pre code");Array.prototype.forEach.call(v,p)}function a(){addEventListener("DOMContentLoaded",l,false);addEventListener("load",l,false)}var f={};var n={};function e(v,x){var w=f[v]=x(this);if(w.aliases){w.aliases.forEach(function(y){n[y]=v})}}function j(v){return f[v]||f[n[v]]}this.highlight=c;this.highlightAuto=g;this.fixMarkup=h;this.highlightBlock=p;this.configure=s;this.initHighlighting=l;this.initHighlightingOnLoad=a;this.registerLanguage=e;this.getLanguage=j;this.inherit=o;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE]};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE]};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.REGEXP_MODE={cN:"regexp",b:/\//,e:/\/[gim]*/,i:/\n/,c:[this.BE,{b:/\[/,e:/\]/,r:0,c:[this.BE]}]};this.TM={cN:"title",b:this.IR,r:0};this.UTM={cN:"title",b:this.UIR,r:0}}();hljs.registerLanguage("bash",function(b){var a={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)\}/}]};var d={cN:"string",b:/"/,e:/"/,c:[b.BE,a,{cN:"variable",b:/\$\(/,e:/\)/,c:[b.BE]}]};var c={cN:"string",b:/'/,e:/'/};return{l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for break continue while in do done exit return set declare case esac export exec",literal:"true false",built_in:"printf echo read cd pwd pushd popd dirs let eval unset typeset readonly getopts source shopt caller type hash bind help sudo",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:true,c:[b.inherit(b.TM,{b:/\w[\w\d_]*/})],r:0},b.HCM,b.NM,d,c,a]}});hljs.registerLanguage("cs",function(b){var a="abstract as base bool break byte case catch char checked const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual volatile void while async await ascending descending from get group into join let orderby partial select set value var where yield";return{k:a,c:[{cN:"comment",b:"///",e:"$",rB:true,c:[{cN:"xmlDocTag",b:"///|"},{cN:"xmlDocTag",b:""}]},b.CLCM,b.CBLCLM,{cN:"preprocessor",b:"#",e:"$",k:"if else elif endif define undef warning error line region endregion pragma checksum"},{cN:"string",b:'@"',e:'"',c:[{b:'""'}]},b.ASM,b.QSM,b.CNM,{bK:"protected public private internal",e:/[{;=]/,k:a,c:[{bK:"class namespace interface",starts:{c:[b.TM]}},{b:b.IR+"\\s*\\(",rB:true,c:[b.TM]}]}]}});hljs.registerLanguage("ruby",function(e){var h="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?";var g="and false then defined module in return redo if BEGIN retry end for true self when next until do begin unless END rescue nil else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor";var a={cN:"yardoctag",b:"@[A-Za-z]+"};var i={cN:"comment",v:[{b:"#",e:"$",c:[a]},{b:"^\\=begin",e:"^\\=end",c:[a],r:10},{b:"^__END__",e:"\\n$"}]};var c={cN:"subst",b:"#\\{",e:"}",k:g};var d={cN:"string",c:[e.BE,c],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:"%[qw]?\\(",e:"\\)"},{b:"%[qw]?\\[",e:"\\]"},{b:"%[qw]?{",e:"}"},{b:"%[qw]?<",e:">",r:10},{b:"%[qw]?/",e:"/",r:10},{b:"%[qw]?%",e:"%",r:10},{b:"%[qw]?-",e:"-",r:10},{b:"%[qw]?\\|",e:"\\|",r:10},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/}]};var b={cN:"params",b:"\\(",e:"\\)",k:g};var f=[d,i,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{cN:"inheritance",b:"<\\s*",c:[{cN:"parent",b:"("+e.IR+"::)?"+e.IR}]},i]},{cN:"function",bK:"def",e:" |$|;",r:0,c:[e.inherit(e.TM,{b:h}),b,i]},{cN:"constant",b:"(::)?(\\b[A-Z]\\w*(::)?)+",r:0},{cN:"symbol",b:":",c:[d,{b:h}],r:0},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{cN:"variable",b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{b:"("+e.RSR+")\\s*",c:[i,{cN:"regexp",c:[e.BE,c],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}],r:0}];c.c=f;b.c=f;return{k:g,c:f}});hljs.registerLanguage("diff",function(a){return{c:[{cN:"chunk",r:10,v:[{b:/^\@\@ +\-\d+,\d+ +\+\d+,\d+ +\@\@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"header",v:[{b:/Index: /,e:/$/},{b:/=====/,e:/=====$/},{b:/^\-\-\-/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+\+\+/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"change",b:"^\\!",e:"$"}]}});hljs.registerLanguage("javascript",function(a){return{aliases:["js"],k:{keyword:"in if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const class",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require"},c:[{cN:"pi",b:/^\s*('|")use strict('|")/,r:10},a.ASM,a.QSM,a.CLCM,a.CBLCLM,a.CNM,{b:"("+a.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[a.CLCM,a.CBLCLM,a.REGEXP_MODE,{b:/;/,r:0,sL:"xml"}],r:0},{cN:"function",bK:"function",e:/\{/,c:[a.inherit(a.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,c:[a.CLCM,a.CBLCLM],i:/["'\(]/}],i:/\[|%/},{b:/\$[(.]/},{b:"\\."+a.IR,r:0}]}});hljs.registerLanguage("xml",function(a){var c="[A-Za-z0-9\\._:-]+";var d={b:/<\?(php)?(?!\w)/,e:/\?>/,sL:"php",subLanguageMode:"continuous"};var b={eW:true,i:/]+/}]}]}]};return{aliases:["html"],cI:true,c:[{cN:"doctype",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},{cN:"comment",b:"",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{title:"style"},c:[b],starts:{e:"",rE:true,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},d,{cN:"pi",b:/<\?\w+/,e:/\?>/,r:10},{cN:"tag",b:"",c:[{cN:"title",b:"[^ /><]+",r:0},b]}]}});hljs.registerLanguage("markdown",function(a){return{c:[{cN:"header",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"blockquote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"`.+?`"},{b:"^( {4}|\t)",e:"$",r:0}]},{cN:"horizontal_rule",b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].+?[\\)\\]]",rB:true,c:[{cN:"link_label",b:"\\[",e:"\\]",eB:true,rE:true,r:0},{cN:"link_url",b:"\\]\\(",e:"\\)",eB:true,eE:true},{cN:"link_reference",b:"\\]\\[",e:"\\]",eB:true,eE:true,}],r:10},{b:"^\\[.+\\]:",e:"$",rB:true,c:[{cN:"link_reference",b:"\\[",e:"\\]",eB:true,eE:true},{cN:"link_url",b:"\\s",e:"$"}]}]}});hljs.registerLanguage("css",function(a){var b="[a-zA-Z-][a-zA-Z0-9_-]*";var c={cN:"function",b:b+"\\(",e:"\\)",c:["self",a.NM,a.ASM,a.QSM]};return{cI:true,i:"[=/|']",c:[a.CBLCLM,{cN:"id",b:"\\#[A-Za-z0-9_-]+"},{cN:"class",b:"\\.[A-Za-z0-9_-]+",r:0},{cN:"attr_selector",b:"\\[",e:"\\]",i:"$"},{cN:"pseudo",b:":(:)?[a-zA-Z0-9\\_\\-\\+\\(\\)\\\"\\']+"},{cN:"at_rule",b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{cN:"at_rule",b:"@",e:"[{;]",c:[{cN:"keyword",b:/\S+/},{b:/\s/,eW:true,eE:true,r:0,c:[c,a.ASM,a.QSM,a.NM]}]},{cN:"tag",b:b,r:0},{cN:"rules",b:"{",e:"}",i:"[^\\s]",r:0,c:[a.CBLCLM,{cN:"rule",b:"[^\\s]",rB:true,e:";",eW:true,c:[{cN:"attribute",b:"[A-Z\\_\\.\\-]+",e:":",eE:true,i:"[^\\s]",starts:{cN:"value",eW:true,eE:true,c:[c,a.NM,a.QSM,a.ASM,a.CBLCLM,{cN:"hexcolor",b:"#[0-9A-Fa-f]+"},{cN:"important",b:"!important"}]}}]}]}]}});hljs.registerLanguage("profile",function(a){return{c:[a.CNM,{cN:"built_in",b:"{",e:"}$",eB:true,eE:true,c:[a.ASM,a.QSM],r:0},{cN:"filename",b:"[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}",e:":",eE:true},{cN:"header",b:"(ncalls|tottime|cumtime)",e:"$",k:"ncalls tottime|10 cumtime|10 filename",r:10},{cN:"summary",b:"function calls",e:"$",c:[a.CNM],r:10},a.ASM,a.QSM,{cN:"function",b:"\\(",e:"\\)$",c:[a.UTM],r:0}]}});hljs.registerLanguage("http",function(a){return{i:"\\S",c:[{cN:"status",b:"^HTTP/[0-9\\.]+",e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{cN:"request",b:"^[A-Z]+ (.*?) HTTP/[0-9\\.]+$",rB:true,e:"$",c:[{cN:"string",b:" ",e:" ",eB:true,eE:true}]},{cN:"attribute",b:"^\\w",e:": ",eE:true,i:"\\n|\\s|=",starts:{cN:"string",e:"$"}},{b:"\\n\\n",starts:{sL:"",eW:true}}]}});hljs.registerLanguage("java",function(b){var a="false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws";return{k:a,i:/<\//,c:[{cN:"javadoc",b:"/\\*\\*",e:"\\*/",c:[{cN:"javadoctag",b:"(^|\\s)@[A-Za-z]+"}],r:10},b.CLCM,b.CBLCLM,b.ASM,b.QSM,{bK:"protected public private",e:/[{;=]/,k:a,c:[{cN:"class",bK:"class interface",eW:true,i:/[:"<>]/,c:[{bK:"extends implements",r:10},b.UTM]},{b:b.UIR+"\\s*\\(",rB:true,c:[b.UTM]}]},b.CNM,{cN:"annotation",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("php",function(b){var e={cN:"variable",b:"\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"};var a={cN:"preprocessor",b:/<\?(php)?|\?>/};var c={cN:"string",c:[b.BE,a],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},b.inherit(b.ASM,{i:null}),b.inherit(b.QSM,{i:null})]};var d={v:[b.BNM,b.CNM]};return{cI:true,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[b.CLCM,b.HCM,{cN:"comment",b:"/\\*",e:"\\*/",c:[{cN:"phpdoc",b:"\\s@[A-Za-z]+"},a]},{cN:"comment",b:"__halt_compiler.+?;",eW:true,k:"__halt_compiler",l:b.UIR},{cN:"string",b:"<<<['\"]?\\w+['\"]?$",e:"^\\w+;",c:[b.BE]},a,e,{cN:"function",bK:"function",e:/[;{]/,i:"\\$|\\[|%",c:[b.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",e,b.CBLCLM,c,d]}]},{cN:"class",bK:"class interface",e:"{",i:/[:\(\$"]/,c:[{bK:"extends implements",r:10},b.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[b.UTM]},{bK:"use",e:";",c:[b.UTM]},{b:"=>"},c,d]}});hljs.registerLanguage("python",function(a){var f={cN:"prompt",b:/^(>>>|\.\.\.) /};var b={cN:"string",c:[a.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[f],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[f],r:10},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/,},{b:/(b|br)"/,e:/"/,},a.ASM,a.QSM]};var d={cN:"number",r:0,v:[{b:a.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:a.CNR+"[lLjJ]?"}]};var e={cN:"params",b:/\(/,e:/\)/,c:["self",f,d,b]};var c={e:/:/,i:/[${=;\n]/,c:[a.UTM,e]};return{k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},i:/(<\/|->|\?)/,c:[f,d,b,a.HCM,a.inherit(c,{cN:"function",bK:"def",r:10}),a.inherit(c,{cN:"class",bK:"class"}),{cN:"decorator",b:/@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("sql",function(a){return{cI:true,i:/[<>]/,c:[{cN:"operator",b:"\\b(begin|end|start|commit|rollback|savepoint|lock|alter|create|drop|rename|call|delete|do|handler|insert|load|replace|select|truncate|update|set|show|pragma|grant|merge)\\b(?!:)",e:";",eW:true,k:{keyword:"all partial global month current_timestamp using go revoke smallint indicator end-exec disconnect zone with character assertion to add current_user usage input local alter match collate real then rollback get read timestamp session_user not integer bit unique day minute desc insert execute like ilike|2 level decimal drop continue isolation found where constraints domain right national some module transaction relative second connect escape close system_user for deferred section cast current sqlstate allocate intersect deallocate numeric public preserve full goto initially asc no key output collation group by union session both last language constraint column of space foreign deferrable prior connection unknown action commit view or first into float year primary cascaded except restrict set references names table outer open select size are rows from prepare distinct leading create only next inner authorization schema corresponding option declare precision immediate else timezone_minute external varying translation true case exception join hour default double scroll value cursor descriptor values dec fetch procedure delete and false int is describe char as at in varchar null trailing any absolute current_time end grant privileges when cross check write current_date pad begin temporary exec time update catalog user sql date on identity timezone_hour natural whenever interval work order cascade diagnostics nchar having left call do handler load replace truncate start lock show pragma exists number trigger if before after each row merge matched database",aggregate:"count sum min max avg"},c:[{cN:"string",b:"'",e:"'",c:[a.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[a.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[a.BE]},a.CNM]},a.CBLCLM,{cN:"comment",b:"--",e:"$"}]}});hljs.registerLanguage("ini",function(a){return{cI:true,i:/\S/,c:[{cN:"comment",b:";",e:"$"},{cN:"title",b:"^\\[",e:"\\]"},{cN:"setting",b:"^[a-z0-9\\[\\]_-]+[ \\t]*=[ \\t]*",e:"$",c:[{cN:"value",eW:true,k:"on off true false yes no",c:[a.QSM,a.NM],r:0}]}]}});hljs.registerLanguage("vbnet",function(a){return{cI:true,k:{keyword:"addhandler addressof alias and andalso aggregate ansi as assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into is isfalse isnot istrue join key let lib like loop me mid mod module mustinherit mustoverride mybase myclass namespace narrowing new next not notinheritable notoverridable of off on operator option optional or order orelse overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim rem removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly xor",built_in:"boolean byte cbool cbyte cchar cdate cdec cdbl char cint clng cobj csbyte cshort csng cstr ctype date decimal directcast double gettype getxmlnamespace iif integer long object sbyte short single string trycast typeof uinteger ulong ushort",literal:"true false nothing"},i:"//|{|}|endif|gosub|variant|wend",c:[a.inherit(a.QSM,{c:[{b:'""'}]}),{cN:"comment",b:"'",e:"$",rB:true,c:[{cN:"xmlDocTag",b:"'''|"},{cN:"xmlDocTag",b:""},]},a.CNM,{cN:"preprocessor",b:"#",e:"$",k:"if else elseif end region externalsource"},]}});hljs.registerLanguage("perl",function(c){var d="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when";var f={cN:"subst",b:"[$@]\\{",e:"\\}",k:d};var g={b:"->{",e:"}"};var a={cN:"variable",v:[{b:/\$\d/},{b:/[\$\%\@\*](\^\w\b|#\w+(\:\:\w+)*|{\w+}|\w+(\:\:\w*)*)/},{b:/[\$\%\@\*][^\s\w{]/,r:0}]};var e={cN:"comment",b:"^(__END__|__DATA__)",e:"\\n$",r:5};var h=[c.BE,f,a];var b=[a,c.HCM,e,{cN:"comment",b:"^\\=\\w",e:"\\=cut",eW:true},g,{cN:"string",c:h,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[c.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[c.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+c.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[c.HCM,e,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[c.BE],r:0}]},{cN:"sub",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",r:5},{cN:"operator",b:"-\\w\\b",r:0}];f.c=b;g.c=b;return{k:d,c:b}});hljs.registerLanguage("objectivec",function(a){var d={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign self synchronized id nonatomic super unichar IBOutlet IBAction strong weak @private @protected @public @try @property @end @throw @catch @finally @synthesize @dynamic @selector @optional @required",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"NSString NSDictionary CGRect CGPoint UIButton UILabel UITextView UIWebView MKMapView UISegmentedControl NSObject UITableViewDelegate UITableViewDataSource NSThread UIActivityIndicator UITabbar UIToolBar UIBarButtonItem UIImageView NSAutoreleasePool UITableView BOOL NSInteger CGFloat NSException NSLog NSMutableString NSMutableArray NSMutableDictionary NSURL NSIndexPath CGSize UITableViewCell UIView UIViewController UINavigationBar UINavigationController UITabBarController UIPopoverController UIPopoverControllerDelegate UIImage NSNumber UISearchBar NSFetchedResultsController NSFetchedResultsChangeType UIScrollView UIScrollViewDelegate UIEdgeInsets UIColor UIFont UIApplication NSNotFound NSNotificationCenter NSNotification UILocalNotification NSBundle NSFileManager NSTimeInterval NSDate NSCalendar NSUserDefaults UIWindow NSRange NSArray NSError NSURLRequest NSURLConnection UIInterfaceOrientation MPMoviePlayerController dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"};var c=/[a-zA-Z@][a-zA-Z0-9_]*/;var b="@interface @class @protocol @implementation";return{k:d,l:c,i:""}]},{cN:"preprocessor",b:"#",e:"$"},{cN:"class",b:"("+b.split(" ").join("|")+")\\b",e:"({|$)",k:b,l:c,c:[a.UTM]},{cN:"variable",b:"\\."+a.UIR,r:0}]}});hljs.registerLanguage("coffeescript",function(c){var b={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",reserved:"case default function var void with const let enum export import native __hasProp __extends __slice __bind __indexOf",built_in:"npm require console print module exports global window document"};var a="[A-Za-z$_][0-9A-Za-z$_]*";var f=c.inherit(c.TM,{b:a});var e={cN:"subst",b:/#\{/,e:/}/,k:b};var d=[c.BNM,c.inherit(c.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[c.BE]},{b:/'/,e:/'/,c:[c.BE]},{b:/"""/,e:/"""/,c:[c.BE,e]},{b:/"/,e:/"/,c:[c.BE,e]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[e,c.HCM]},{b:"//[gim]*",r:0},{b:"/\\S(\\\\.|[^\\n])*?/[gim]*(?=\\s|\\W|$)"}]},{cN:"property",b:"@"+a},{b:"`",e:"`",eB:true,eE:true,sL:"javascript"}];e.c=d;return{k:b,c:d.concat([{cN:"comment",b:"###",e:"###"},c.HCM,{cN:"function",b:"("+a+"\\s*=\\s*)?(\\(.*\\))?\\s*\\B[-=]>",e:"[-=]>",rB:true,c:[f,{cN:"params",b:"\\(",rB:true,c:[{b:/\(/,e:/\)/,k:b,c:["self"].concat(d)}]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:true,i:/[:="\[\]]/,c:[f]},f]},{cN:"attribute",b:a+":",e:":",rB:true,eE:true,r:0}])}});hljs.registerLanguage("nginx",function(c){var b={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+c.UIR}]};var a={eW:true,l:"[a-z/_]+",k:{built_in:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[c.HCM,{cN:"string",c:[c.BE,b],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{cN:"url",b:"([a-z]+):/",e:"\\s",eW:true,eE:true},{cN:"regexp",c:[c.BE,b],v:[{b:"\\s\\^",e:"\\s|{|;",rE:true},{b:"~\\*?\\s+",e:"\\s|{|;",rE:true},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},b]};return{c:[c.HCM,{b:c.UIR+"\\s",e:";|{",rB:true,c:[c.inherit(c.UTM,{starts:a})],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("json",function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}});hljs.registerLanguage("vbscript",function(a){return{cI:true,k:{keyword:"call class const dim do loop erase execute executeglobal exit for each next function if then else on error option explicit new private property let get public randomize redim rem select case set stop sub while wend with end to elseif is or xor and not class_initialize class_terminate default preserve in me byval byref step resume goto",built_in:"lcase month vartype instrrev ubound setlocale getobject rgb getref string weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency conversions csng timevalue second year space abs clng timeserial fixs len asc isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim strcomp int createobject loadpicture tan formatnumber mid scriptenginebuildversion scriptengine split scriptengineminorversion cint sin datepart ltrim sqr scriptenginemajorversion time derived eval date formatpercent exp inputbox left ascw chrw regexp server response request cstr err",literal:"true false null nothing empty"},i:"//",c:[a.inherit(a.QSM,{c:[{b:'""'}]}),{cN:"comment",b:/'/,e:/$/,r:0},a.CNM]}});hljs.registerLanguage("apache",function(a){var b={cN:"number",b:"[\\$%]\\d+"};return{cI:true,c:[a.HCM,{cN:"tag",b:""},{cN:"keyword",b:/\w+/,r:0,k:{common:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"sqbracket",b:"\\s\\[",e:"\\]$"},{cN:"cbracket",b:"[\\$%]\\{",e:"\\}",c:["self",b]},b,a.QSM]}}],i:/\S/}});hljs.registerLanguage("cpp",function(a){var b={keyword:"false int float while private char catch export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace unsigned long throw volatile static protected bool template mutable if public friend do return goto auto void enum else break new extern using true class asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype noexcept nullptr static_assert thread_local restrict _Bool complex _Complex _Imaginary",built_in:"std string cin cout cerr clog stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf"};return{aliases:["c"],k:b,i:"",i:"\\n"},a.CLCM]},{cN:"stl_container",b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:b,r:10,c:["self"]}]}});hljs.registerLanguage("makefile",function(a){var b={cN:"variable",b:/\$\(/,e:/\)/,c:[a.BE]};return{c:[a.HCM,{b:/^\w+\s*\W*=/,rB:true,r:0,starts:{cN:"constant",e:/\s*\W*=/,eE:true,starts:{e:/$/,r:0,c:[b],}}},{cN:"title",b:/^[\w]+:\s*$/},{cN:"phony",b:/^\.PHONY:/,e:/$/,k:".PHONY",l:/[\.\w]+/},{b:/^\t+/,e:/$/,c:[a.QSM,b]}]}}); \ No newline at end of file diff --git a/js/prettify-1.0.min.js b/js/prettify-1.0.min.js new file mode 100644 index 000000000..eef5ad7e6 --- /dev/null +++ b/js/prettify-1.0.min.js @@ -0,0 +1,28 @@ +var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; +(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= +[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), +l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, +q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, +q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, +"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), +a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} +for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], +"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], +H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], +J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ +I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), +["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", +/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), +["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", +hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= +!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p - - - - http://www.django-rest-framework.org/ - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/tutorial/quickstart - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/1-serialization - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/2-requests-and-responses - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/3-class-based-views - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/api-guide/requests - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/responses - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/views - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/generic-views - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/viewsets - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/routers - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/parsers - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/renderers - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/serializers - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/fields - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/relations - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/authentication - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/permissions - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/throttling - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/filtering - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/pagination - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/content-negotiation - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/format-suffixes - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/reverse - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/exceptions - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/status-codes - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/testing - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/api-guide/settings - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/documenting-your-api - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/ajax-csrf-cors - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/browser-enhancements - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/browsable-api - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/contributing - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/rest-framework-2-announcement - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/topics/2.2-announcement - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/topics/2.3-announcement - 2014-01-02T09:29:15+00:00 - monthly - - - http://www.django-rest-framework.org/topics/release-notes - 2014-01-02T09:29:15+00:00 - weekly - - - http://www.django-rest-framework.org/topics/credits - 2014-01-02T09:29:15+00:00 - weekly - - diff --git a/topics/2.2-announcement.html b/topics/2.2-announcement.html deleted file mode 100644 index ca5414bc0..000000000 --- a/topics/2.2-announcement.html +++ /dev/null @@ -1,350 +0,0 @@ - - - - - REST framework 2.2 announcement - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    REST framework 2.2 announcement

    -

    The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.

    -

    Python 3 support

    -

    Thanks to some fantastic work from Xavier Ordoquy, Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently considered experimental.

    -

    Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.

    -

    If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's Porting to Python 3 documentation.

    -

    Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with Django 1.5's Python compatibility.

    -

    Deprecation policy

    -

    We've now introduced an official deprecation policy, which is in line with Django's deprecation policy. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.

    -

    The timeline for deprecation works as follows:

    -
      -
    • -

      Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise PendingDeprecationWarning warnings if you use bits of API 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 2.3 will escalate these warnings to DeprecationWarning, which is loud by default.

      -
    • -
    • -

      Version 2.4 will 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.

    -

    Community

    -

    As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in the credits, is now at over one hundred individuals. Each name on that list represents at least one merged pull request, however large or small.

    -

    Our mailing list and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great django-rest-framework-docs package from Marc Gibbons.

    -
    -

    API changes

    -

    The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.

    - -

    The ManyRelatedField() style is being deprecated in favor of a new RelatedField(many=True) syntax.

    -

    For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:

    -
    class UserSerializer(serializers.HyperlinkedModelSerializer):
    -    questions = serializers.PrimaryKeyRelatedField(many=True)
    -
    -    class Meta:
    -        fields = ('username', 'questions')
    -
    -

    The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.

    -

    The change also applies to serializers. If you have a nested serializer, you should start using many=True for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:

    -
    class TrackSerializer(serializer.ModelSerializer):
    -    class Meta:
    -        model = Track
    -        fields = ('name', 'duration')
    -
    -class AlbumSerializer(serializer.ModelSerializer):
    -    tracks = TrackSerializer(many=True)
    -
    -    class Meta:
    -        model = Album
    -        fields = ('album_name', 'artist', 'tracks')
    -
    -

    Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the many=True flag.

    -
    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    -serializer.data
    -
    -

    This more explicit behavior on serializing and deserializing data makes integration with non-ORM backends such as MongoDB easier, as instances to be serialized can include the __iter__ method, without incorrectly triggering list-based serialization, or requiring workarounds.

    -

    The implicit to-many behavior on serializers, and the ManyRelatedField style classes will continue to function, but will raise a PendingDeprecationWarning, which can be made visible using the -Wd flag.

    -

    Note: If you need to forcibly turn off the implicit "many=True for __iter__ objects" behavior, you can now do so by specifying many=False. This will become the default (instead of the current default of None) once the deprecation of the implicit behavior is finalised in version 2.4.

    -

    Cleaner optional relationships

    -

    Serializer relationships for nullable Foreign Keys will change from using the current null=True flag, to instead using required=False.

    -

    For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a Serializer class:

    -
    current_company = serializers.HyperlinkedRelatedField(required=False)
    -
    -

    This is in line both with the rest of the serializer fields API, and with Django's Form and ModelForm API.

    -

    Using required throughout the serializers API means you won't need to consider if a particular field should take blank or null arguments instead of required, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.

    -

    The null=True argument will continue to function, and will imply required=False, but will raise a PendingDeprecationWarning.

    -

    Cleaner CharField syntax

    -

    The CharField API previously took an optional blank=True argument, which was intended to differentiate between null CharField input, and blank CharField input.

    -

    In keeping with Django's CharField API, REST framework's CharField will only ever return the empty string, for missing or None inputs. The blank flag will no longer be in use, and you should instead just use the required=<bool> flag. For example:

    -
    extra_details = CharField(required=False)
    -
    -

    The blank keyword argument will continue to function, but will raise a PendingDeprecationWarning.

    -

    Simpler object-level permissions

    -

    Custom permissions classes previously used the signature .has_permission(self, request, view, obj=None). This method would be called twice, firstly for the global permissions check, with the obj parameter set to None, and again for the object-level permissions check when appropriate, with the obj parameter set to the relevant model instance.

    -

    The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.

    -
      -
    • Global permission checks now use the .has_permission(self, request, view) signature.
    • -
    • Object-level permission checks use a new method .has_object_permission(self, request, view, obj).
    • -
    -

    For example, the following custom permission class:

    -
    class IsOwner(permissions.BasePermission):
    -    """
    -    Custom permission to only allow owners of an object to view or edit it.
    -    Model instances are expected to include an `owner` attribute.
    -    """
    -
    -    def has_permission(self, request, view, obj=None):
    -        if obj is None:
    -            # Ignore global permissions check
    -            return True
    -
    -        return obj.owner == request.user
    -
    -

    Now becomes:

    -
    class IsOwner(permissions.BasePermission):
    -    """
    -    Custom permission to only allow owners of an object to view or edit it.
    -    Model instances are expected to include an `owner` attribute.
    -    """
    -
    -    def has_object_permission(self, request, view, obj):
    -        return obj.owner == request.user
    -
    -

    If you're overriding the BasePermission class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a PendingDeprecationWarning.

    -

    Note also that the usage of the internal APIs for permission checking on the View class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.

    - -

    When using a serializer with a HyperlinkedRelatedField or HyperlinkedIdentityField, the hyperlinks would previously use absolute URLs if the serializer context included a 'request' key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.

    -

    From version 2.2 onwards, serializers with hyperlinked relationships always require a 'request' key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a PendingDeprecationWarning.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/2.2-announcement/index.html b/topics/2.2-announcement/index.html new file mode 100644 index 000000000..2c41b0cae --- /dev/null +++ b/topics/2.2-announcement/index.html @@ -0,0 +1,533 @@ + + + + + + + 2.2 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    REST framework 2.2 announcement

    +

    The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.

    +

    Python 3 support

    +

    Thanks to some fantastic work from Xavier Ordoquy, Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently considered experimental.

    +

    Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.

    +

    If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's Porting to Python 3 documentation.

    +

    Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with Django 1.5's Python compatibility.

    +

    Deprecation policy

    +

    We've now introduced an official deprecation policy, which is in line with Django's deprecation policy. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.

    +

    The timeline for deprecation works as follows:

    +
      +
    • +

      Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise PendingDeprecationWarning warnings if you use bits of API 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 2.3 will escalate these warnings to DeprecationWarning, which is loud by default.

      +
    • +
    • +

      Version 2.4 will 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.

    +

    Community

    +

    As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in the credits, is now at over one hundred individuals. Each name on that list represents at least one merged pull request, however large or small.

    +

    Our mailing list and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great django-rest-framework-docs package from Marc Gibbons.

    +
    +

    API changes

    +

    The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.

    + +

    The ManyRelatedField() style is being deprecated in favor of a new RelatedField(many=True) syntax.

    +

    For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:

    +
    class UserSerializer(serializers.HyperlinkedModelSerializer):
    +    questions = serializers.PrimaryKeyRelatedField(many=True)
    +
    +    class Meta:
    +        fields = ('username', 'questions')
    +
    +

    The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.

    +

    The change also applies to serializers. If you have a nested serializer, you should start using many=True for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:

    +
    class TrackSerializer(serializer.ModelSerializer):
    +    class Meta:
    +        model = Track
    +        fields = ('name', 'duration')
    +
    +class AlbumSerializer(serializer.ModelSerializer):
    +    tracks = TrackSerializer(many=True)
    +
    +    class Meta:
    +        model = Album
    +        fields = ('album_name', 'artist', 'tracks')
    +
    +

    Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the many=True flag.

    +
    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    +serializer.data
    +
    +

    This more explicit behavior on serializing and deserializing data makes integration with non-ORM backends such as MongoDB easier, as instances to be serialized can include the __iter__ method, without incorrectly triggering list-based serialization, or requiring workarounds.

    +

    The implicit to-many behavior on serializers, and the ManyRelatedField style classes will continue to function, but will raise a PendingDeprecationWarning, which can be made visible using the -Wd flag.

    +

    Note: If you need to forcibly turn off the implicit "many=True for __iter__ objects" behavior, you can now do so by specifying many=False. This will become the default (instead of the current default of None) once the deprecation of the implicit behavior is finalised in version 2.4.

    +

    Cleaner optional relationships

    +

    Serializer relationships for nullable Foreign Keys will change from using the current null=True flag, to instead using required=False.

    +

    For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a Serializer class:

    +
    current_company = serializers.HyperlinkedRelatedField(required=False)
    +
    +

    This is in line both with the rest of the serializer fields API, and with Django's Form and ModelForm API.

    +

    Using required throughout the serializers API means you won't need to consider if a particular field should take blank or null arguments instead of required, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.

    +

    The null=True argument will continue to function, and will imply required=False, but will raise a PendingDeprecationWarning.

    +

    Cleaner CharField syntax

    +

    The CharField API previously took an optional blank=True argument, which was intended to differentiate between null CharField input, and blank CharField input.

    +

    In keeping with Django's CharField API, REST framework's CharField will only ever return the empty string, for missing or None inputs. The blank flag will no longer be in use, and you should instead just use the required=<bool> flag. For example:

    +
    extra_details = CharField(required=False)
    +
    +

    The blank keyword argument will continue to function, but will raise a PendingDeprecationWarning.

    +

    Simpler object-level permissions

    +

    Custom permissions classes previously used the signature .has_permission(self, request, view, obj=None). This method would be called twice, firstly for the global permissions check, with the obj parameter set to None, and again for the object-level permissions check when appropriate, with the obj parameter set to the relevant model instance.

    +

    The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.

    +
      +
    • Global permission checks now use the .has_permission(self, request, view) signature.
    • +
    • Object-level permission checks use a new method .has_object_permission(self, request, view, obj).
    • +
    +

    For example, the following custom permission class:

    +
    class IsOwner(permissions.BasePermission):
    +    """
    +    Custom permission to only allow owners of an object to view or edit it.
    +    Model instances are expected to include an `owner` attribute.
    +    """
    +
    +    def has_permission(self, request, view, obj=None):
    +        if obj is None:
    +            # Ignore global permissions check
    +            return True
    +
    +        return obj.owner == request.user
    +
    +

    Now becomes:

    +
    class IsOwner(permissions.BasePermission):
    +    """
    +    Custom permission to only allow owners of an object to view or edit it.
    +    Model instances are expected to include an `owner` attribute.
    +    """
    +
    +    def has_object_permission(self, request, view, obj):
    +        return obj.owner == request.user
    +
    +

    If you're overriding the BasePermission class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a PendingDeprecationWarning.

    +

    Note also that the usage of the internal APIs for permission checking on the View class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.

    + +

    When using a serializer with a HyperlinkedRelatedField or HyperlinkedIdentityField, the hyperlinks would previously use absolute URLs if the serializer context included a 'request' key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.

    +

    From version 2.2 onwards, serializers with hyperlinked relationships always require a 'request' key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a PendingDeprecationWarning.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/2.3-announcement.html b/topics/2.3-announcement/index.html similarity index 50% rename from topics/2.3-announcement.html rename to topics/2.3-announcement/index.html index 27da50d8a..ccbf4b7f0 100644 --- a/topics/2.3-announcement.html +++ b/topics/2.3-announcement/index.html @@ -1,65 +1,74 @@ - - - REST framework 2.3 announcement - Django REST framework - - - - - - - - - - + + + + 2.3 Announcement - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    + +

    REST framework 2.3 announcement

    REST framework 2.3 makes it even quicker and easier to build your Web APIs.

    ViewSets and Routers

    -

    The 2.3 release introduces the ViewSet and Router classes.

    +

    The 2.3 release introduces the ViewSet and Router classes.

    A viewset is simply a type of class based view that allows you to group multiple views into a single common class.

    Routers allow you to automatically determine the URLconf for your viewset classes.

    As an example of just how simple REST framework APIs can now be, here's an API written in a single urls.py module:

    -
    """
    +
    """
     A REST framework API for viewing and editing users and groups.
     """
     from django.conf.urls.defaults import url, include
    @@ -249,7 +466,7 @@ urlpatterns = [
         url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
     ]
     
    -

    The best place to get started with ViewSets and Routers is to take a look at the newest section in the tutorial, which demonstrates their usage.

    +

    The best place to get started with ViewSets and Routers is to take a look at the newest section in the tutorial, which demonstrates their usage.

    Simpler views

    This release rationalises the API and implementation of the generic views, dropping the dependency on Django's SingleObjectMixin and MultipleObjectMixin classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.

    This improvement is reflected in improved documentation for the GenericAPIView base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.

    @@ -257,7 +474,7 @@ urlpatterns = [

    REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.

    The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the fields metadata of the serializer class.

    For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.

    -
    class BlogSerializer(serializers.ModelSerializer):
    +
    class BlogSerializer(serializers.ModelSerializer):
         comments = serializers.PrimaryKeyRelatedField(many=True)
     
         class Meta:
    @@ -265,7 +482,7 @@ urlpatterns = [
             fields = ('id', 'title', 'created', 'comments')
     

    As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.

    -
    class BlogSerializer(serializers.ModelSerializer):
    +
    class BlogSerializer(serializers.ModelSerializer):
         """
         Don't need to specify the 'comments' field explicitly anymore.
         """
    @@ -274,7 +491,7 @@ urlpatterns = [
             fields = ('id', 'title', 'created', 'comments')
     

    Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.

    -
    class BlogSerializer(serializers.HyperlinkedModelSerializer):
    +
    class BlogSerializer(serializers.HyperlinkedModelSerializer):
         """
         This is a hyperlinked serializer, which default to using
         a field named 'url' as the primary identifier.
    @@ -328,18 +545,18 @@ urlpatterns = [
     
     

    This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the lookup_field argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.

    For example, a view with 'username' based lookup might look like this:

    -
    class UserDetail(generics.RetrieveAPIView):
    +
    class UserDetail(generics.RetrieveAPIView):
         lookup_field = 'username'
         queryset = User.objects.all()
         serializer_class = UserSerializer
     

    And would have the following entry in the urlconf:

    -
     url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
    +
     url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
     

    Usage of the old-style attributes continues to be supported, but will raise a PendingDeprecationWarning.

    The allow_empty attribute is also deprecated. To use allow_empty=False style behavior you should explicitly override get_queryset and raise an Http404 on empty querysets.

    For example:

    -
    class DisallowEmptyQuerysetMixin(object):
    +
    class DisallowEmptyQuerysetMixin(object):
         def get_queryset(self):
             queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
             if not queryset.exists():
    @@ -350,7 +567,7 @@ urlpatterns = [
     

    Simpler URL lookups

    The HyperlinkedRelatedField class now takes a single optional lookup_field argument, that replaces the pk_url_kwarg, slug_url_kwarg, and slug_field arguments.

    For example, you might have a field that references it's relationship by a hyperlink based on a slug field:

    -
        account = HyperlinkedRelatedField(read_only=True,
    +
        account = HyperlinkedRelatedField(read_only=True,
                                           lookup_field='slug',
                                           view_name='account-detail')
     
    @@ -363,23 +580,23 @@ urlpatterns = [

    ModelSerializers and reverse relationships

    The support for adding reverse relationships to the fields option on a ModelSerializer class means that the get_related_field and get_nested_field method signatures have now changed.

    In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now (self, model_field, related_model, to_many). For reverse relationships model_field will be None.

    -

    The old-style signature will continue to function but will raise a PendingDeprecationWarning.

    +

    The old-style signature will continue to function but will raise a PendingDeprecationWarning.

    View names and descriptions

    The mechanics of how the names and descriptions used in the browseable API are generated has been modified and cleaned up somewhat.

    If you've been customizing this behavior, for example perhaps to use rst markup for the browseable API, then you'll need to take a look at the implementation to see what updates you need to make.

    -

    Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.

    +

    Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.


    Other notes

    More explicit style

    The usage of model attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit queryset and serializer_class attributes.

    For example, the following is now the recommended style for using generic views:

    -
    class AccountListView(generics.RetrieveAPIView):
    +
    class AccountListView(generics.RetrieveAPIView):
         queryset = MyModel.objects.all()
         serializer_class = MyModelSerializer
     

    Using an explicit queryset and serializer_class attributes makes the functioning of the view more clear than using the shortcut model attribute.

    It also makes the usage of the get_queryset() or get_serializer_class() methods more obvious.

    -
    class AccountListView(generics.RetrieveAPIView):
    +
    class AccountListView(generics.RetrieveAPIView):
         serializer_class = MyModelSerializer
     
         def get_queryset(self):
    @@ -402,42 +619,52 @@ urlpatterns = [
     
  • Extra filter backends for searching and ordering of results are planned to be added shortly.
  • The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/topics/2.4-accouncement.html b/topics/2.4-accouncement.html deleted file mode 100644 index 7526010fd..000000000 --- a/topics/2.4-accouncement.html +++ /dev/null @@ -1,354 +0,0 @@ - - - - - REST framework 2.4 announcement - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    REST framework 2.4 announcement

    -

    The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.

    -

    Version requirements

    -

    Support for Django 1.3 has been dropped. -The lowest supported version of Django is now 1.4.2.

    -

    The current plan is for REST framework to remain in lockstep with Django's long-term support policy.

    -

    Django 1.7 support

    -

    The optional authtoken application now includes support for both Django 1.7 schema migrations, and for old-style south migrations.

    -

    If you are using authtoken, and you want to continue using south, you must upgrade your south package to version 1.0.

    -

    Deprecation of .model view attribute

    -

    The .model attribute on view classes is an optional shortcut for either or both of .serializer_class and .queryset. It's usage results in more implicit, less obvious behavior.

    -

    The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the .model shortcut.

    -

    Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the .model shortcut. However we firmly believe that it is the right trade-off to make.

    -

    Removing the shortcut takes away an unneccessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.

    -

    The DEFAULT_MODEL_SERIALIZER_CLASS API setting is now also deprecated.

    -

    Updated test runner

    -

    We now have a new test runner for developing against the project,, that uses the excellent py.test library.

    -

    To use it make sure you have first installed the test requirements.

    -
    pip install -r requirements-test.txt
    -
    -

    Then run the runtests.py script.

    -
    ./runtests.py
    -
    -

    The new test runner also includes flake8 code linting, which should help keep our coding style consistent.

    -

    Test runner flags

    -

    Run using a more concise output style.

    -
    ./runtests -q
    -
    -

    Run the tests using a more concise output style, no coverage, no flake8.

    -
    ./runtests --fast
    -
    -

    Don't run the flake8 code linting.

    -
    ./runtests --nolint
    -
    -

    Only run the flake8 code linting, don't run the tests.

    -
    ./runtests --lintonly
    -
    -

    Run the tests for a given test case.

    -
    ./runtests MyTestCase
    -
    -

    Run the tests for a given test method.

    -
    ./runtests MyTestCase.test_this_method
    -
    -

    Shorter form to run the tests for a given test method.

    -
    ./runtests 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.

    -

    Improved viewset routing

    -

    The @action and @link decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.

    -

    The @action and @link decorators have now been moved to pending deprecation, and the @list_route and @detail_route decorators have been introduced.

    -

    Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a pk argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.

    -
    class UserViewSet(viewsets.ModelViewSet):
    -    """
    -    A viewset that provides the standard actions
    -    """
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -    @detail_route(methods=['post'])
    -    def set_password(self, request, pk=None):
    -        user = self.get_object()
    -        serializer = PasswordSerializer(data=request.DATA)
    -        if serializer.is_valid():
    -            user.set_password(serializer.data['password'])
    -            user.save()
    -            return Response({'status': 'password set'})
    -        else:
    -            return Response(serializer.errors,
    -                            status=status.HTTP_400_BAD_REQUEST)
    -
    -    @list_route()
    -    def recent_users(self, request):
    -        recent_users = User.objects.all().order('-last_login')
    -        page = self.paginate_queryset(recent_users)
    -        serializer = self.get_pagination_serializer(page)
    -        return Response(serializer.data)
    -
    -

    For more details, see the viewsets documentation.

    -

    Throttle behavior

    -

    There's one bugfix in 2.4 that's worth calling out, as it will invalidate existing throttle caches when you upgrade.

    -

    We've now fixed a typo on the cache_format attribute. Previously this was named "throtte_%(scope)s_%(ident)s", it is now "throttle_%(scope)s_%(ident)s".

    -

    If you're concerned about the invalidation you have two options.

    -
      -
    • Manually pre-populate your cache with the fixed version.
    • -
    • Set the cache_format attribute on your throttle class in order to retain the previous incorrect spelling.
    • -
    -

    Other features

    -

    There are also a number of other features and bugfixes as listed in the release notes. In particular these include:

    -

    Customizable view name and description functions for use with the browsable API, by using the VIEW_NAME_FUNCTION and VIEW_DESCRIPTION_FUNCTION settings.

    -

    Smarter client IP identification for throttling, with the addition of the NUM_PROXIES setting.

    -

    Added the standardized Retry-After header to throttled responses, as per RFC 6585. This should now be used in preference to the custom X-Trottle-Wait-Seconds header which will be fully deprecated in 3.0.

    -

    Deprecations

    -

    All API changes in 2.3 that previously raised PendingDeprecationWarning will now raise a DeprecationWarning, which is loud by default.

    -

    All API changes in 2.3 that previously raised DeprecationWarning have now been removed entirely.

    -

    Furter details on these deprecations is available in the 2.3 announcement.

    -

    Labels and milestones

    -

    Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.

    -

    The labels that we use in GitHub have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.

    -

    We've also started using milestones in order to track tickets against particular releases.

    -
    -

    Labels and milestones

    -

    Above: Overview of our current use of labels and milestones in GitHub.

    -
    -

    We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.

    -

    Next steps

    -

    The next planned release will be 3.0, featuring an improved and simplified serializer implementation.

    -

    Once again, many thanks to all the generous backers and sponsors who've helped make this possible!

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/2.4-announcement.html b/topics/2.4-announcement.html deleted file mode 100644 index 868f718cf..000000000 --- a/topics/2.4-announcement.html +++ /dev/null @@ -1,355 +0,0 @@ - - - - - REST framework 2.4 announcement - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    REST framework 2.4 announcement

    -

    The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.

    -

    Version requirements

    -

    Support for Django 1.3 has been dropped. -The lowest supported version of Django is now 1.4.2.

    -

    The current plan is for REST framework to remain in lockstep with Django's long-term support policy.

    -

    Django 1.7 support

    -

    The optional authtoken application now includes support for both Django 1.7 schema migrations, and for old-style south migrations.

    -

    If you are using authtoken, and you want to continue using south, you must upgrade your south package to version 1.0.

    -

    Deprecation of .model view attribute

    -

    The .model attribute on view classes is an optional shortcut for either or both of .serializer_class and .queryset. Its usage results in more implicit, less obvious behavior.

    -

    The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the .model shortcut.

    -

    Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the .model shortcut. However we firmly believe that it is the right trade-off to make.

    -

    Removing the shortcut takes away an unneccessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.

    -

    The DEFAULT_MODEL_SERIALIZER_CLASS API setting is now also deprecated.

    -

    Updated test runner

    -

    We now have a new test runner for developing against the project,, that uses the excellent py.test library.

    -

    To use it make sure you have first installed the test requirements.

    -
    pip install -r requirements-test.txt
    -
    -

    Then run the runtests.py script.

    -
    ./runtests.py
    -
    -

    The new test runner also includes flake8 code linting, which should help keep our coding style consistent.

    -

    Test runner flags

    -

    Run using a more concise output style.

    -
    ./runtests -q
    -
    -

    Run the tests using a more concise output style, no coverage, no flake8.

    -
    ./runtests --fast
    -
    -

    Don't run the flake8 code linting.

    -
    ./runtests --nolint
    -
    -

    Only run the flake8 code linting, don't run the tests.

    -
    ./runtests --lintonly
    -
    -

    Run the tests for a given test case.

    -
    ./runtests MyTestCase
    -
    -

    Run the tests for a given test method.

    -
    ./runtests MyTestCase.test_this_method
    -
    -

    Shorter form to run the tests for a given test method.

    -
    ./runtests 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.

    -

    Improved viewset routing

    -

    The @action and @link decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.

    -

    The @action and @link decorators have now been moved to pending deprecation, and the @list_route and @detail_route decorators have been introduced.

    -

    Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a pk argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.

    -
    class UserViewSet(viewsets.ModelViewSet):
    -    """
    -    A viewset that provides the standard actions
    -    """
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -    @detail_route(methods=['post'])
    -    def set_password(self, request, pk=None):
    -        user = self.get_object()
    -        serializer = PasswordSerializer(data=request.DATA)
    -        if serializer.is_valid():
    -            user.set_password(serializer.data['password'])
    -            user.save()
    -            return Response({'status': 'password set'})
    -        else:
    -            return Response(serializer.errors,
    -                            status=status.HTTP_400_BAD_REQUEST)
    -
    -    @list_route()
    -    def recent_users(self, request):
    -        recent_users = User.objects.all().order('-last_login')
    -        page = self.paginate_queryset(recent_users)
    -        serializer = self.get_pagination_serializer(page)
    -        return Response(serializer.data)
    -
    -

    For more details, see the viewsets documentation.

    -

    Throttle behavior

    -

    There's one bugfix in 2.4 that's worth calling out, as it will invalidate existing throttle caches when you upgrade.

    -

    We've now fixed a typo on the cache_format attribute. Previously this was named "throtte_%(scope)s_%(ident)s", it is now "throttle_%(scope)s_%(ident)s".

    -

    If you're concerned about the invalidation you have two options.

    -
      -
    • Manually pre-populate your cache with the fixed version.
    • -
    • Set the cache_format attribute on your throttle class in order to retain the previous incorrect spelling.
    • -
    -

    Other features

    -

    There are also a number of other features and bugfixes as listed in the release notes. In particular these include:

    -

    Customizable view name and description functions for use with the browsable API, by using the VIEW_NAME_FUNCTION and VIEW_DESCRIPTION_FUNCTION settings.

    -

    Smarter client IP identification for throttling, with the addition of the NUM_PROXIES setting.

    -

    Added the standardized Retry-After header to throttled responses, as per RFC 6585. This should now be used in preference to the custom X-Throttle-Wait-Seconds header which will be fully deprecated in 3.0.

    -

    Deprecations

    -

    All API changes in 2.3 that previously raised PendingDeprecationWarning will now raise a DeprecationWarning, which is loud by default.

    -

    All API changes in 2.3 that previously raised DeprecationWarning have now been removed entirely.

    -

    Furter details on these deprecations is available in the 2.3 announcement.

    -

    Labels and milestones

    -

    Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.

    -

    The labels that we use in GitHub have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.

    -

    We've also started using milestones in order to track tickets against particular releases.

    -
    -

    Labels and milestones

    -

    Above: Overview of our current use of labels and milestones in GitHub.

    -
    -

    We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.

    -

    Next steps

    -

    The next planned release will be 3.0, featuring an improved and simplified serializer implementation.

    -

    Once again, many thanks to all the generous backers and sponsors who've helped make this possible!

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/2.4-announcement/index.html b/topics/2.4-announcement/index.html new file mode 100644 index 000000000..2b44bebe5 --- /dev/null +++ b/topics/2.4-announcement/index.html @@ -0,0 +1,556 @@ + + + + + + + 2.4 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    REST framework 2.4 announcement

    +

    The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.

    +

    Version requirements

    +

    Support for Django 1.3 has been dropped. +The lowest supported version of Django is now 1.4.2.

    +

    The current plan is for REST framework to remain in lockstep with Django's long-term support policy.

    +

    Django 1.7 support

    +

    The optional authtoken application now includes support for both Django 1.7 schema migrations, and for old-style south migrations.

    +

    If you are using authtoken, and you want to continue using south, you must upgrade your south package to version 1.0.

    +

    Deprecation of .model view attribute

    +

    The .model attribute on view classes is an optional shortcut for either or both of .serializer_class and .queryset. Its usage results in more implicit, less obvious behavior.

    +

    The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the .model shortcut.

    +

    Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the .model shortcut. However we firmly believe that it is the right trade-off to make.

    +

    Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.

    +

    The DEFAULT_MODEL_SERIALIZER_CLASS API setting is now also deprecated.

    +

    Updated test runner

    +

    We now have a new test runner for developing against the project,, that uses the excellent py.test library.

    +

    To use it make sure you have first installed the test requirements.

    +
    pip install -r requirements-test.txt
    +
    +

    Then run the runtests.py script.

    +
    ./runtests.py
    +
    +

    The new test runner also includes flake8 code linting, which should help keep our coding style consistent.

    +

    Test runner flags

    +

    Run using a more concise output style.

    +
    ./runtests -q
    +
    +

    Run the tests using a more concise output style, no coverage, no flake8.

    +
    ./runtests --fast
    +
    +

    Don't run the flake8 code linting.

    +
    ./runtests --nolint
    +
    +

    Only run the flake8 code linting, don't run the tests.

    +
    ./runtests --lintonly
    +
    +

    Run the tests for a given test case.

    +
    ./runtests MyTestCase
    +
    +

    Run the tests for a given test method.

    +
    ./runtests MyTestCase.test_this_method
    +
    +

    Shorter form to run the tests for a given test method.

    +
    ./runtests 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.

    +

    Improved viewset routing

    +

    The @action and @link decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.

    +

    The @action and @link decorators have now been moved to pending deprecation, and the @list_route and @detail_route decorators have been introduced.

    +

    Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a pk argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.

    +
    class UserViewSet(viewsets.ModelViewSet):
    +    """
    +    A viewset that provides the standard actions
    +    """
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +
    +    @detail_route(methods=['post'])
    +    def set_password(self, request, pk=None):
    +        user = self.get_object()
    +        serializer = PasswordSerializer(data=request.DATA)
    +        if serializer.is_valid():
    +            user.set_password(serializer.data['password'])
    +            user.save()
    +            return Response({'status': 'password set'})
    +        else:
    +            return Response(serializer.errors,
    +                            status=status.HTTP_400_BAD_REQUEST)
    +
    +    @list_route()
    +    def recent_users(self, request):
    +        recent_users = User.objects.all().order('-last_login')
    +        page = self.paginate_queryset(recent_users)
    +        serializer = self.get_pagination_serializer(page)
    +        return Response(serializer.data)
    +
    +

    For more details, see the viewsets documentation.

    +

    Throttle behavior

    +

    There's one bugfix in 2.4 that's worth calling out, as it will invalidate existing throttle caches when you upgrade.

    +

    We've now fixed a typo on the cache_format attribute. Previously this was named "throtte_%(scope)s_%(ident)s", it is now "throttle_%(scope)s_%(ident)s".

    +

    If you're concerned about the invalidation you have two options.

    +
      +
    • Manually pre-populate your cache with the fixed version.
    • +
    • Set the cache_format attribute on your throttle class in order to retain the previous incorrect spelling.
    • +
    +

    Other features

    +

    There are also a number of other features and bugfixes as listed in the release notes. In particular these include:

    +

    Customizable view name and description functions for use with the browsable API, by using the VIEW_NAME_FUNCTION and VIEW_DESCRIPTION_FUNCTION settings.

    +

    Smarter client IP identification for throttling, with the addition of the NUM_PROXIES setting.

    +

    Added the standardized Retry-After header to throttled responses, as per RFC 6585. This should now be used in preference to the custom X-Throttle-Wait-Seconds header which will be fully deprecated in 3.0.

    +

    Deprecations

    +

    All API changes in 2.3 that previously raised PendingDeprecationWarning will now raise a DeprecationWarning, which is loud by default.

    +

    All API changes in 2.3 that previously raised DeprecationWarning have now been removed entirely.

    +

    Furter details on these deprecations is available in the 2.3 announcement.

    +

    Labels and milestones

    +

    Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.

    +

    The labels that we use in GitHub have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.

    +

    We've also started using milestones in order to track tickets against particular releases.

    +
    +

    Labels and milestones

    +

    Above: Overview of our current use of labels and milestones in GitHub.

    +
    +

    We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.

    +

    Next steps

    +

    The next planned release will be 3.0, featuring an improved and simplified serializer implementation.

    +

    Once again, many thanks to all the generous backers and sponsors who've helped make this possible!

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/3.0-announcement.html b/topics/3.0-announcement.html deleted file mode 100644 index 3ced0ce6c..000000000 --- a/topics/3.0-announcement.html +++ /dev/null @@ -1,886 +0,0 @@ - - - - - Pre-release notes: - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Pre-release notes:

    -

    The 3.0 release is now ready for some tentative testing and upgrades for super keen early adopters. You can install the development version directly from GitHub like so:

    -
    pip install https://github.com/tomchristie/django-rest-framework/archive/version-3.0.zip
    -
    -

    See the Version 3.0 GitHub issue for more details on remaining work.

    -

    The most notable outstanding issues still to be resolved on the version-3.0 branch are as follows:

    -
      -
    • Finish forms support for serializers and in the browsable API.
    • -
    • Optimisations for serializing primary keys.
    • -
    • Refine style of validation errors in some cases, such as validation errors in ListField.
    • -
    -

    Your feedback on the upgrade process and 3.0 changes is hugely important!

    -

    Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group.

    -
    -

    REST framework 3.0

    -

    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.

    -

    New features

    -

    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 plus new ListField and MultipleChoiceField classes.
    • -
    • 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.
    • -
    -

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

    -
    -

    Request objects

    -

    The .data and .query_params properties.

    -

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

    -

    Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.

    -

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

    -
    # Do this...
    -ExampleSerializer(data=request.data)
    -
    -

    Instead of passing the files argument separately:

    -
    # Don't do this...
    -ExampleSerializer(data=request.DATA, files=request.FILES)
    -
    -

    The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params.

    -

    Serializers

    -

    Single-step object creation.

    -

    Previously the serializers used a two-step object creation, as follows:

    -
      -
    1. Validating the data would create an object instance. This instance would be available as serializer.object.
    2. -
    3. Calling serializer.save() would then save the object instance to the database.
    4. -
    -

    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, eg 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:

    -
      -
    1. Validating the data makes the cleaned data available as serializer.validated_data.
    2. -
    3. Calling serializer.save() then saves and returns the new object instance.
    4. -
    -

    The resulting API changes are further detailed below.

    -

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

    -

    The .restore_object() method is now replaced with two separate methods, .create() and .update().

    -

    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.

    -

    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):
    -    if instance:
    -        # Update existing instance
    -        instance.title = attrs.get('title', instance.title)
    -        instance.code = attrs.get('code', instance.code)
    -        instance.linenos = attrs.get('linenos', instance.linenos)
    -        instance.language = attrs.get('language', instance.language)
    -        instance.style = attrs.get('style', instance.style)
    -        return instance
    -
    -    # Create new instance
    -    return Snippet(**attrs)
    -
    -

    This would now be split out into two separate methods.

    -
    def update(self, instance, validated_data):
    -    instance.title = validated_data.get('title', instance.title)
    -    instance.code = validated_data.get('code', instance.code)
    -    instance.linenos = validated_data.get('linenos', instance.linenos)
    -    instance.language = validated_data.get('language', instance.language)
    -    instance.style = validated_data.get('style', instance.style)
    -    instance.save()
    -    return instance
    -
    -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.

    -

    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():
    -    name = serializer.object.name  # Inspect validated field data.
    -    logging.info('Creating ticket "%s"' % name)
    -    serializer.object.user = request.user  # Include the user when saving.
    -    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():
    -    name = serializer.validated_data['name']  # Inspect validated field data.
    -    logging.info('Creating ticket "%s"' % name)
    -    serializer.save(user=request.user)  # Include the user when saving.
    -
    -

    Using serializers.ValidationError.

    -

    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 are always 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.

    -

    Change to validate_<field_name>.

    -

    The validate_<field_name> 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):
    -    if attrs[score] % 10 != 0:
    -        raise serializers.ValidationError('This field should be a multiple of ten.')
    -    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):
    -    if value % 10 != 0:
    -        raise serializers.ValidationError('This field should be a multiple of ten.')
    -    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_<field_name> 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):
    -    # serializer.errors == {'non_field_errors': ['A non field error']}
    -    raise serailizers.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):
    -    # serializer.errors == {'my_field': ['A field error']}
    -    raise serailizers.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.

    -

    Limitations of ModelSerializer validation.

    -

    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.

    -

    This change comes with the following limitations:

    -
      -
    • The model .clean() method will not be called as part of serializer validation. Use the serializer .validate() method to perform a final validation step on incoming data where required.
    • -
    • The .unique_for_date, .unique_for_month and .unique_for_year options on model fields are not automatically validated. Again, you'll need to handle these explicitly on the serializer if required.
    • -
    -

    Writable nested serialization.

    -

    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):
    ->>>     class Meta:
    ->>>         model = Profile
    ->>>         fields = ('address', 'phone')
    ->>>
    ->>> class UserSerializer(serializers.ModelSerializer):
    ->>>     profile = ProfileSerializer()
    ->>>     class Meta:
    ->>>         model = User
    ->>>         fields = ('username', 'email', 'profile')
    ->>>
    ->>> data = {
    ->>>     'username': 'lizzy',
    ->>>     'email': 'lizzy@example.com',
    ->>>     'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
    ->>> }
    ->>>
    ->>> serializer = UserSerializer(data=data)
    ->>> serializer.save()
    -AssertionError: The `.create()` method does not suport 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):
    -    profile = ProfileSerializer()
    -
    -    class Meta:
    -        model = User
    -        fields = ('username', 'email', 'profile')
    -
    -    def create(self, validated_data):
    -        profile_data = validated_data.pop['profile']
    -        user = User.objects.create(**validated_data)
    -        Profile.objects.create(user=user, **profile_data)
    -        return user
    -
    -

    The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.

    -

    Printable serializer representations.

    -

    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):
    -    location = models.CharField(max_length=100)
    -    rating = models.IntegerField()
    -    created_by = models.ForeignKey(User)
    -
    -

    Let's create a simple ModelSerializer class corresponding to the LocationRating model.

    -
    class LocationRatingSerializer(serializer.ModelSerializer):
    -    class Meta:
    -        model = LocationRating
    -
    -

    We can now inspect the serializer representation in the Django shell, using python manage.py shell...

    -
    >>> serializer = LocationRatingSerializer()
    ->>> print(serializer)  # Or use `print serializer` in Python 2.x
    -LocationRatingSerializer():
    -    id = IntegerField(label='ID', read_only=True)
    -    location = CharField(max_length=100)
    -    rating = IntegerField()
    -    created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
    -
    -

    The extra_kwargs option.

    -

    The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs.

    -
    class MySerializer(serializer.ModelSerializer):
    -    class Meta:
    -        model = MyModel
    -        fields = ('id', 'email', 'notes', 'is_admin')
    -        extra_kwargs = {
    -            'is_admin': {'write_only': True}
    -        }
    -
    -

    Alternatively, specify the field explicitly on the serializer class:

    -
    class MySerializer(serializer.ModelSerializer):
    -    is_admin = serializers.BooleanField(write_only=True)
    -
    -    class Meta:
    -        model = MyModel
    -        fields = ('id', 'email', 'notes', 'is_admin')
    -
    -

    The read_only_fields option remains as a convenient shortcut for the more common case.

    -

    Changes to HyperlinkedModelSerializer.

    -

    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):
    -    class Meta:
    -        model = MyModel
    -        fields = ('url', 'email', 'notes', 'is_admin')
    -        extra_kwargs = {
    -            'url': {'lookup_field': 'uuid'}
    -        }
    -
    -

    Alternatively, specify the field explicitly on the serializer class:

    -
    class MySerializer(serializer.HyperlinkedModelSerializer):
    -    url = serializers.HyperlinkedIdentityField(
    -        view_name='mymodel-detail',
    -        lookup_field='uuid'
    -    )
    -
    -    class Meta:
    -        model = MyModel
    -        fields = ('url', 'email', 'notes', 'is_admin')
    -
    -

    Fields for model methods and properties.

    -

    With ModelSerilizer 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):
    -    created = models.DateTimeField()
    -    to_email = models.EmailField()
    -    message = models.CharField(max_length=1000)
    -
    -    def expiry_date(self):
    -        return self.created + datetime.timedelta(days=30)
    -
    -

    You can include expiry_date as a field option on a ModelSerializer class.

    -
    class InvitationSerializer(serializers.ModelSerializer):
    -    class Meta:
    -        model = Invitation
    -        fields = ('to_email', 'message', 'expiry_date')
    -
    -

    These fields will be mapped to serializers.ReadOnlyField() instances.

    -
    >>> serializer = InvitationSerializer()
    ->>> print repr(serializer)
    -InvitationSerializer():
    -    to_email = EmailField(max_length=75)
    -    message = CharField(max_length=1000)
    -    expiry_date = ReadOnlyField()
    -
    -

    The ListSerializer class.

    -

    The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.

    -
    class MultipleUserSerializer(ListSerializer):
    -    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.

    -

    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.

    -

    The BaseSerializer class.

    -

    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 mathods that can be overriding, 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() - Overide either or both of these to support saving instances.
    • -
    -
    Read-only BaseSerializer classes.
    -

    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):
    -    created = models.DateTimeField(auto_now_add=True)
    -    player_name = models.CharField(max_length=10)
    -    score = models.IntegerField()
    -
    -

    It's simple to create a read-only serializer for converting HighScore instances into primitive data types.

    -
    class HighScoreSerializer(serializers.BaseSerializer):
    -    def to_representation(self, obj):
    -        return {
    -            'score': obj.score,
    -            'player_name': obj.player_name
    -        }
    -
    -

    We can now use this class to serialize single HighScore instances:

    -
    @api_view(['GET'])
    -def high_score(request, pk):
    -    instance = HighScore.objects.get(pk=pk)
    -    serializer = HighScoreSerializer(instance)
    -    return Response(serializer.data)
    -
    -

    Or use it to serialize multiple instances:

    -
    @api_view(['GET'])
    -def all_high_scores(request):
    -    queryset = HighScore.objects.order_by('-score')
    -    serializer = HighScoreSerializer(queryset, many=True)
    -    return Response(serializer.data)
    -
    -
    Read-write BaseSerializer classes.
    -

    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):
    -    def to_internal_value(self, data):
    -        score = data.get('score')
    -        player_name = data.get('player_name')
    -
    -        # Perform the data validation.
    -        if not score:
    -            raise ValidationError({
    -                'score': 'This field is required.'
    -            })
    -        if not player_name:
    -            raise ValidationError({
    -                'player_name': 'This field is required.'
    -            })
    -        if len(player_name) > 10:
    -            raise ValidationError({
    -                'player_name': 'May not be more than 10 characters.'
    -            })
    -
    -        # Return the validated values. This will be available as
    -        # the `.validated_data` property.
    -        return {
    -            'score': int(score),
    -            'player_name': player_name
    -        }
    -
    -    def to_representation(self, obj):
    -        return {
    -            'score': obj.score,
    -            'player_name': obj.player_name
    -        }
    -
    -    def create(self, validated_data):
    -        return HighScore.objects.create(**validated_data)
    -
    -

    Creating new generic serializers with BaseSerializer.

    -

    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 aribitrary objects into primitive representations.

    -
    class ObjectSerializer(serializers.BaseSerializer):
    -    """
    -    A read-only serializer that coerces arbitrary complex objects
    -    into primitive representations.
    -    """
    -    def to_representation(self, obj):
    -        for attribute_name in dir(obj):
    -            attribute = getattr(obj, attribute_name)
    -            if attribute_name('_'):
    -                # Ignore private attributes.
    -                pass
    -            elif hasattr(attribute, '__call__'):
    -                # Ignore methods and other callables.
    -                pass
    -            elif isinstance(attribute, (str, int, bool, float, type(None))):
    -                # Primitive types can be passed through unmodified.
    -                output[attribute_name] = attribute
    -            elif isinstance(attribute, list):
    -                # Recursivly deal with items in lists.
    -                output[attribute_name] = [
    -                    self.to_representation(item) for item in attribute
    -                ]
    -            elif isinstance(attribute, dict):
    -                # Recursivly deal with items in dictionarys.
    -                output[attribute_name] = {
    -                    str(key): self.to_representation(value)
    -                    for key, value in attribute.items()
    -                }
    -            else:
    -                # Force anything else to its string representation.
    -                output[attribute_name] = str(attribute)
    -
    -

    Serializer fields

    -

    The Field and ReadOnly field classes.

    -

    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.
    • -
    -

    The required, allow_none, allow_blank and default arguments.

    -

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

    -

    Previously the meaning of the required=False keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be None.

    -

    We now have a better separation, with separate required and allow_none 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=<value>: 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_none=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_none=True or allow_blank=True if required.

    -

    The default argument is there if you need it, but you'll more typically want defaults to be set on model fields, rather than serializer fields.

    -

    Coercing output types.

    -

    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.

    -

    The ListField class.

    -

    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):
    -    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.

    -

    The ChoiceField class may now accept a flat list.

    -

    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'])
    -
    -

    The MultipleChoiceField class.

    -

    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.

    -

    Changes to the custom field API.

    -

    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.

    -

    Explicit queryset required on relational fields.

    -

    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):
    -    organisations = serializers.SlugRelatedField(slug_field='name')
    -
    -    class Meta:
    -        model = Account
    -
    -

    However this code would not be valid in 2.4.3:

    -
    # Missing `queryset`
    -class AccountSerializer(serializers.Serializer):
    -    organisations = serializers.SlugRelatedField(slug_field='name')
    -
    -    def restore_object(self, attrs, instance=None):
    -        # ...
    -
    -

    The queryset argument is now always required for writable relational fields. -This removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes.

    -
    class AccountSerializer(serializers.ModelSerializer):
    -    organisations = serializers.SlugRelatedField(
    -        slug_field='name',
    -        queryset=Organisation.objects.all()
    -    )
    -
    -    class Meta:
    -        model = Account
    -
    -

    The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True.

    -

    Optional argument to SerializerMethodField.

    -

    The argument to SerializerMethodField is now optional, and defaults to get_<field_name>. For example the following is valid:

    -
    class AccountSerializer(serializers.Serializer):
    -    # `method_name='get_billing_details'` by default.
    -    billing_details = serializers.SerializerMethodField()
    -
    -    def get_billing_details(self, account):
    -        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')
    -
    -

    Enforcing consistent source usage.

    -

    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')
    -
    -

    The UniqueValidator and UniqueTogetherValidator classes.

    -

    REST framework now provides two 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
    -from rest_framework.validators import UniqueValidator
    -
    -class OrganizationSerializer(serializers.Serializer):
    -    url = serializers.HyperlinkedIdentityField(view_name='organisation_detail')
    -    created = serializers.DateTimeField(read_only=True)
    -    name = serializers.CharField(
    -        max_length=100,
    -        validators=UniqueValidator(queryset=Organisation.objects.all())
    -    )
    -
    -

    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):
    -    category = serializers.ChoiceField(['5k', '10k'])
    -    position = serializers.IntegerField()
    -    name = serializers.CharField(max_length=100)
    -
    -    default_validators = [UniqueTogetherValidator(
    -        queryset=RaceResult.objects.all(),
    -        fields=('category', 'position')
    -    )]
    -
    -

    Generic views

    -

    Simplification of view logic.

    -

    The view logic for the default method handlers has been significantly simplified, due to the new serializers API.

    -

    Changes to pre/post save hooks.

    -

    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):
    -    # Include the owner attribute directly, rather than from request data.
    -    instance = serializer.save(owner=self.request.user)
    -    # Perform a custom post-save action.
    -    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):
    -    # Perform a custom pre-delete action.
    -    send_deletion_alert(user=instance.created_by, deleted=instance)
    -    # Delete the object instance.
    -    instance.delete()
    -
    -

    Removal of view attributes.

    -

    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.

    -

    PUT as create.

    -

    Allowing PUT as create operations is problematic, as it necessarily exposes information about the existence or non-existance 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 can include the AllowPUTAsCreateMixin class in your view. This class can be imported from rest_framework.mixins.

    -

    Customizing error responses.

    -

    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.

    -

    The metadata API

    -

    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.

    -

    API style

    -

    There are some improvements in the default style we use in our API responses.

    -

    Unicode JSON by default.

    -

    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 = {
    -    'UNICODE_JSON': False
    -}
    -
    -

    Compact JSON by default.

    -

    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 = {
    -    'COMPACT_JSON': False
    -}
    -
    -

    File fields as URLs

    -

    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 = {
    -    'UPLOADED_FILES_USE_URL': False
    -}
    -
    -

    You can also modify serializer fields individually, using the use_url argument:

    -
    uploaded_file = serializers.FileField(user_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}
    -serializer = ExampleSerializer(instance, context=context)
    -return Response(serializer.data)
    -
    -

    If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt.

    -

    Throttle headers using Retry-After.

    -

    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.

    -

    Date and time objects as ISO-8859-1 strings in serializer data.

    -

    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-8859-1' will result in native objects being returned in serializer data.

    -
    REST_FRAMEWORK = {
    -    # Return native `Date` and `Time` objects in `serializer.data`
    -    'DATETIME_FORMAT': None
    -    'DATE_FORMAT': None
    -    'TIME_FORMAT': None
    -}
    -
    -

    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.
    -created = serializers.DateTimeField(format=None)
    -
    -

    Decimals as strings in serializer data.

    -

    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 = {
    -    'COERCE_DECIMAL_TO_STRING': False
    -}
    -
    -

    Or modify it on an individual serializer field, using the corece_to_string keyword argument.

    -
    # Return `Decimal` instances in `serializer.data`, not strings.
    -amount = serializers.DecimalField(
    -    max_digits=10,
    -    decimal_places=2,
    -    coerce_to_string=False
    -)
    -
    -

    The default JSON renderer will return float objects for uncoerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.

    -

    What's coming next.

    -

    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:

    -
      -
    • 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.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/ajax-csrf-cors.html b/topics/ajax-csrf-cors.html deleted file mode 100644 index 85fb3ba84..000000000 --- a/topics/ajax-csrf-cors.html +++ /dev/null @@ -1,263 +0,0 @@ - - - - - Working with AJAX, CSRF & CORS - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Working with AJAX, CSRF & CORS

    -
    -

    "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."

    -

    Jeff Atwood

    -
    -

    Javascript clients

    -

    If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.

    -

    AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.

    -

    AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.

    -

    CSRF protection

    -

    Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.

    -

    To guard against these type of attacks, you need to do two things:

    -
      -
    1. Ensure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS cannot be used to alter any server-side state.
    2. -
    3. Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token.
    4. -
    -

    If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.

    -

    In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

    -

    CORS

    -

    Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.

    -

    The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.

    -

    Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/ajax-csrf-cors/index.html b/topics/ajax-csrf-cors/index.html new file mode 100644 index 000000000..c7771456d --- /dev/null +++ b/topics/ajax-csrf-cors/index.html @@ -0,0 +1,443 @@ + + + + + + + AJAX, CSRF & CORS - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    Working with AJAX, CSRF & CORS

    +
    +

    "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."

    +

    Jeff Atwood

    +
    +

    Javascript clients

    +

    If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.

    +

    AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.

    +

    AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.

    +

    CSRF protection

    +

    Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.

    +

    To guard against these type of attacks, you need to do two things:

    +
      +
    1. Ensure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS cannot be used to alter any server-side state.
    2. +
    3. Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token.
    4. +
    +

    If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.

    +

    In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

    +

    CORS

    +

    Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.

    +

    The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.

    +

    Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/browsable-api.html b/topics/browsable-api.html deleted file mode 100644 index be0a07db1..000000000 --- a/topics/browsable-api.html +++ /dev/null @@ -1,358 +0,0 @@ - - - - - The Browsable API - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - -
    - -
    - - -
    -
    - -
    -

    The Browsable API

    -
    -

    It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.

    -

    Alfred North Whitehead, An Introduction to Mathematics (1911)

    -
    -

    API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.

    -

    URLs

    -

    If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.

    -

    Formats

    -

    By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using ?format= in the request, so you can look at the raw JSON response in a browser by adding ?format=json to the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.

    -

    Customizing

    -

    The browsable API is built with Twitter's Bootstrap (v 2.1.1), making it easy to customize the look-and-feel.

    -

    To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html. For example:

    -

    templates/rest_framework/api.html

    -
    {% extends "rest_framework/base.html" %}
    -
    -...  # Override blocks with required customizations
    -
    -

    Overriding the default theme

    -

    To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme.

    -
    {% block bootstrap_theme %}
    -    <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
    -{% endblock %}
    -
    -

    A suitable replacement theme can be generated using Bootstrap's Customize Tool. There are also pre-made themes available at Bootswatch. To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above.

    -

    You can also change the navbar variant, which by default is navbar-inverse, using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style.

    -

    Full example:

    -
    {% extends "rest_framework/base.html" %}
    -
    -{% block bootstrap_theme %}
    -    <link rel="stylesheet" href="http://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
    -{% endblock %}
    -
    -{% block bootstrap_navbar_variant %}{% endblock %}
    -
    -

    For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.

    -
    -

    Cerulean theme

    -

    Screenshot of the bootswatch 'Cerulean' theme

    -
    -

    Slate theme

    -

    Screenshot of the bootswatch 'Slate' theme

    -
    -

    Blocks

    -

    All of the blocks available in the browsable API base template that can be used in your api.html.

    -
      -
    • body - The entire html <body>.
    • -
    • bodyclass - Class attribute for the <body> tag, empty by default.
    • -
    • bootstrap_theme - CSS for the Bootstrap theme.
    • -
    • bootstrap_navbar_variant - CSS class for the navbar.
    • -
    • branding - Branding section of the navbar, see Bootstrap components.
    • -
    • breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
    • -
    • footer - Any copyright notices or similar footer materials can go here (by default right-aligned).
    • -
    • script - JavaScript files for the page.
    • -
    • style - CSS stylesheets for the page.
    • -
    • title - Title of the page.
    • -
    • userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
    • -
    -

    Components

    -

    All of the standard Bootstrap components are available.

    -

    Tooltips

    -

    The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events.

    -

    Login Template

    -

    To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html. The template should extend from rest_framework/login_base.html.

    -

    You can add your site name or branding by including the branding block:

    -
    {% block branding %}
    -    <h3 style="margin: 0 0 20px;">My Site Name</h3>
    -{% endblock %}
    -
    -

    You can also customize the style by adding the bootstrap_theme or style block similar to api.html.

    -

    Advanced Customization

    -

    Context

    -

    The context that's available to the template:

    -
      -
    • allowed_methods : A list of methods allowed by the resource
    • -
    • api_settings : The API settings
    • -
    • available_formats : A list of formats allowed by the resource
    • -
    • breadcrumblist : The list of links following the chain of nested resources
    • -
    • content : The content of the API response
    • -
    • description : The description of the resource, generated from its docstring
    • -
    • name : The name of the resource
    • -
    • post_form : A form instance for use by the POST form (if allowed)
    • -
    • put_form : A form instance for use by the PUT form (if allowed)
    • -
    • display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed
    • -
    • request : The request object
    • -
    • response : The response object
    • -
    • version : The version of Django REST Framework
    • -
    • view : The view handling the request
    • -
    • FORMAT_PARAM : The view can accept a format override
    • -
    • METHOD_PARAM : The view can accept a method override
    • -
    -

    You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template.

    -

    Not using base.html

    -

    For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html extend base.html. Then the page content and capabilities are entirely up to you.

    -

    Autocompletion

    -

    When a ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.

    -

    There are a variety of packages for autocomplete widgets, such as django-autocomplete-light. To setup django-autocomplete-light, follow the installation documentation, add the the following to the api.html template:

    -
    {% block script %}
    -{{ block.super }}
    -{% include 'autocomplete_light/static.html' %}
    -{% endblock %}
    -
    -

    You can now add the autocomplete_light.ChoiceWidget widget to the serializer field.

    -
    import autocomplete_light
    -
    -class BookSerializer(serializers.ModelSerializer):
    -    author = serializers.ChoiceField(
    -        widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
    -    )
    -
    -    class Meta:
    -        model = Book
    -
    -
    -

    Autocomplete

    -

    Screenshot of the autocomplete-light widget

    -
    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/browsable-api/index.html b/topics/browsable-api/index.html new file mode 100644 index 000000000..b56b64264 --- /dev/null +++ b/topics/browsable-api/index.html @@ -0,0 +1,538 @@ + + + + + + + The Browsable API - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    The Browsable API

    +
    +

    It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.

    +

    Alfred North Whitehead, An Introduction to Mathematics (1911)

    +
    +

    API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.

    +

    URLs

    +

    If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.

    +

    Formats

    +

    By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using ?format= in the request, so you can look at the raw JSON response in a browser by adding ?format=json to the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.

    +

    Customizing

    +

    The browsable API is built with Twitter's Bootstrap (v 2.1.1), making it easy to customize the look-and-feel.

    +

    To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html. For example:

    +

    templates/rest_framework/api.html

    +
    {% extends "rest_framework/base.html" %}
    +
    +...  # Override blocks with required customizations
    +
    +

    Overriding the default theme

    +

    To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme.

    +
    {% block bootstrap_theme %}
    +    <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
    +{% endblock %}
    +
    +

    A suitable replacement theme can be generated using Bootstrap's Customize Tool. There are also pre-made themes available at Bootswatch. To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above.

    +

    You can also change the navbar variant, which by default is navbar-inverse, using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style.

    +

    Full example:

    +
    {% extends "rest_framework/base.html" %}
    +
    +{% block bootstrap_theme %}
    +    <link rel="stylesheet" href="http://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
    +{% endblock %}
    +
    +{% block bootstrap_navbar_variant %}{% endblock %}
    +
    +

    For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.

    +
    +

    Cerulean theme

    +

    Screenshot of the bootswatch 'Cerulean' theme

    +
    +

    Slate theme

    +

    Screenshot of the bootswatch 'Slate' theme

    +
    +

    Blocks

    +

    All of the blocks available in the browsable API base template that can be used in your api.html.

    +
      +
    • body - The entire html <body>.
    • +
    • bodyclass - Class attribute for the <body> tag, empty by default.
    • +
    • bootstrap_theme - CSS for the Bootstrap theme.
    • +
    • bootstrap_navbar_variant - CSS class for the navbar.
    • +
    • branding - Branding section of the navbar, see Bootstrap components.
    • +
    • breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
    • +
    • footer - Any copyright notices or similar footer materials can go here (by default right-aligned).
    • +
    • script - JavaScript files for the page.
    • +
    • style - CSS stylesheets for the page.
    • +
    • title - Title of the page.
    • +
    • userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
    • +
    +

    Components

    +

    All of the standard Bootstrap components are available.

    +

    Tooltips

    +

    The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events.

    +

    Login Template

    +

    To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html. The template should extend from rest_framework/login_base.html.

    +

    You can add your site name or branding by including the branding block:

    +
    {% block branding %}
    +    <h3 style="margin: 0 0 20px;">My Site Name</h3>
    +{% endblock %}
    +
    +

    You can also customize the style by adding the bootstrap_theme or style block similar to api.html.

    +

    Advanced Customization

    +

    Context

    +

    The context that's available to the template:

    +
      +
    • allowed_methods : A list of methods allowed by the resource
    • +
    • api_settings : The API settings
    • +
    • available_formats : A list of formats allowed by the resource
    • +
    • breadcrumblist : The list of links following the chain of nested resources
    • +
    • content : The content of the API response
    • +
    • description : The description of the resource, generated from its docstring
    • +
    • name : The name of the resource
    • +
    • post_form : A form instance for use by the POST form (if allowed)
    • +
    • put_form : A form instance for use by the PUT form (if allowed)
    • +
    • display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed
    • +
    • request : The request object
    • +
    • response : The response object
    • +
    • version : The version of Django REST Framework
    • +
    • view : The view handling the request
    • +
    • FORMAT_PARAM : The view can accept a format override
    • +
    • METHOD_PARAM : The view can accept a method override
    • +
    +

    You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template.

    +

    Not using base.html

    +

    For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html extend base.html. Then the page content and capabilities are entirely up to you.

    +

    Autocompletion

    +

    When a ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.

    +

    There are a variety of packages for autocomplete widgets, such as django-autocomplete-light. To setup django-autocomplete-light, follow the installation documentation, add the the following to the api.html template:

    +
    {% block script %}
    +{{ block.super }}
    +{% include 'autocomplete_light/static.html' %}
    +{% endblock %}
    +
    +

    You can now add the autocomplete_light.ChoiceWidget widget to the serializer field.

    +
    import autocomplete_light
    +
    +class BookSerializer(serializers.ModelSerializer):
    +    author = serializers.ChoiceField(
    +        widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
    +    )
    +
    +    class Meta:
    +        model = Book
    +
    +
    +

    Autocomplete

    +

    Screenshot of the autocomplete-light widget

    +
    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/browser-enhancements.html b/topics/browser-enhancements.html deleted file mode 100644 index 6453c5e9b..000000000 --- a/topics/browser-enhancements.html +++ /dev/null @@ -1,297 +0,0 @@ - - - - - Browser enhancements - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Browser enhancements

    -
    -

    "There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"

    -

    RESTful Web Services, Leonard Richardson & Sam Ruby.

    -
    -

    Browser based PUT, DELETE, etc...

    -

    REST framework supports browser-based PUT, DELETE and other methods, by -overloading POST requests using a hidden form field.

    -

    Note that this is the same strategy as is used in Ruby on Rails.

    -

    For example, given the following form:

    -
    <form action="/news-items/5" method="POST">
    -    <input type="hidden" name="_method" value="DELETE">
    -</form>
    -
    -

    request.method would return "DELETE".

    -

    HTTP header based method overriding

    -

    REST framework also supports method overriding via the semi-standard X-HTTP-Method-Override header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as PATCH. For example Amazon Web Services ELB.

    -

    To use it, make a POST request, setting the X-HTTP-Method-Override header.

    -

    For example, making a PATCH request via POST in jQuery:

    -
    $.ajax({
    -    url: '/myresource/',
    -    method: 'POST',
    -    headers: {'X-HTTP-Method-Override': 'PATCH'},
    -    ...
    -});
    -
    -

    Browser based submission of non-form content

    -

    Browser-based submission of content types other than form are supported by -using form fields named _content and _content_type:

    -

    For example, given the following form:

    -
    <form action="/news-items/5" method="PUT">
    -    <input type="hidden" name="_content_type" value="application/json">
    -    <input name="_content" value="{'count': 1}">
    -</form>
    -
    -

    request.content_type would return "application/json", and -request.stream would return "{'count': 1}"

    -

    URL based accept headers

    -

    REST framework can take ?accept=application/json style URL parameters, -which allow the Accept header to be overridden.

    -

    This can be useful for testing the API from a web browser, where you don't -have any control over what is sent in the Accept header.

    -

    URL based format suffixes

    -

    REST framework can take ?format=json style URL parameters, which can be a -useful shortcut for determining which content type should be returned from -the view.

    -

    This is a more concise than using the accept override, but it also gives -you less control. (For example you can't specify any media type parameters)

    -

    Doesn't HTML5 support PUT and DELETE forms?

    -

    Nope. It was at one point intended to support PUT and DELETE forms, but -was later dropped from the spec. There remains -ongoing discussion about adding support for PUT and DELETE, -as well as how to support content types other than form-encoded data.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/browser-enhancements/index.html b/topics/browser-enhancements/index.html new file mode 100644 index 000000000..399c1d279 --- /dev/null +++ b/topics/browser-enhancements/index.html @@ -0,0 +1,486 @@ + + + + + + + Browser enhancements - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Browser enhancements

    +
    +

    "There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"

    +

    RESTful Web Services, Leonard Richardson & Sam Ruby.

    +
    +

    Browser based PUT, DELETE, etc...

    +

    REST framework supports browser-based PUT, DELETE and other methods, by +overloading POST requests using a hidden form field.

    +

    Note that this is the same strategy as is used in Ruby on Rails.

    +

    For example, given the following form:

    +
    <form action="/news-items/5" method="POST">
    +    <input type="hidden" name="_method" value="DELETE">
    +</form>
    +
    +

    request.method would return "DELETE".

    +

    HTTP header based method overriding

    +

    REST framework also supports method overriding via the semi-standard X-HTTP-Method-Override header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as PATCH. For example Amazon Web Services ELB.

    +

    To use it, make a POST request, setting the X-HTTP-Method-Override header.

    +

    For example, making a PATCH request via POST in jQuery:

    +
    $.ajax({
    +    url: '/myresource/',
    +    method: 'POST',
    +    headers: {'X-HTTP-Method-Override': 'PATCH'},
    +    ...
    +});
    +
    +

    Browser based submission of non-form content

    +

    Browser-based submission of content types other than form are supported by +using form fields named _content and _content_type:

    +

    For example, given the following form:

    +
    <form action="/news-items/5" method="PUT">
    +    <input type="hidden" name="_content_type" value="application/json">
    +    <input name="_content" value="{'count': 1}">
    +</form>
    +
    +

    request.content_type would return "application/json", and +request.stream would return "{'count': 1}"

    +

    URL based accept headers

    +

    REST framework can take ?accept=application/json style URL parameters, +which allow the Accept header to be overridden.

    +

    This can be useful for testing the API from a web browser, where you don't +have any control over what is sent in the Accept header.

    +

    URL based format suffixes

    +

    REST framework can take ?format=json style URL parameters, which can be a +useful shortcut for determining which content type should be returned from +the view.

    +

    This is a more concise than using the accept override, but it also gives +you less control. (For example you can't specify any media type parameters)

    +

    Doesn't HTML5 support PUT and DELETE forms?

    +

    Nope. It was at one point intended to support PUT and DELETE forms, but +was later dropped from the spec. There remains +ongoing discussion about adding support for PUT and DELETE, +as well as how to support content types other than form-encoded data.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/contributing.html b/topics/contributing.html deleted file mode 100644 index 85d9736d7..000000000 --- a/topics/contributing.html +++ /dev/null @@ -1,399 +0,0 @@ - - - - - Contributing to REST framework - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Contributing to REST framework

    -
    -

    The world can only really be changed one piece at a time. The art is picking that piece.

    -

    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.

    -

    Community

    -

    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 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.

    -

    Code of conduct

    -

    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.

    -

    Issues

    -

    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 maintainence 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.
    • -
    -

    Triaging issues

    -

    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.
    • -
    -

    Development

    -

    To start developing on Django REST framework, clone the repo:

    -
    git clone git@github.com:tomchristie/django-rest-framework.git
    -
    -

    Changes should broadly follow the PEP 8 style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.

    -

    Testing

    -

    To run the tests, clone the repository, and then:

    -
    # Setup the virtual environment
    -virtualenv env
    -source env/bin/activate
    -pip install -r requirements.txt
    -pip install -r requirements-test.txt
    -
    -# Run the tests
    -./runtests.py
    -
    -

    Test options

    -

    Run using a more concise output style.

    -
    ./runtests -q
    -
    -

    Run the tests using a more concise output style, no coverage, no flake8.

    -
    ./runtests --fast
    -
    -

    Don't run the flake8 code linting.

    -
    ./runtests --nolint
    -
    -

    Only run the flake8 code linting, don't run the tests.

    -
    ./runtests --lintonly
    -
    -

    Run the tests for a given test case.

    -
    ./runtests MyTestCase
    -
    -

    Run the tests for a given test method.

    -
    ./runtests MyTestCase.test_this_method
    -
    -

    Shorter form to run the tests for a given test method.

    -
    ./runtests 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.

    -

    Running against multiple environments

    -

    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
    -
    -

    Pull requests

    -

    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 seperate 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 runnning as you'd expect.

    -

    Travis status

    -

    Above: Travis build notifications

    -

    Managing compatibility issues

    -

    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.

    -

    Documentation

    -

    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.

    -

    Building the documentation

    -

    To build the documentation, simply run the mkdocs.py script.

    -
    ./mkdocs.py
    -
    -

    This will build the html output into the html directory.

    -

    You can build the documentation and open a preview in a browser window by using the -p flag.

    -
    ./mkdocs.py -p
    -
    -

    Language style

    -

    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.
    • -
    • Use double spacing after the end of sentences.
    • -
    • Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
    • -
    -

    Markdown style

    -

    There are a couple of conventions you should follow when working on the documentation.

    -
    1. Headers
    -

    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
    -====================
    -
    - -

    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].
    -
    -More text...
    -
    -[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.

    -
    3. Notes
    -

    If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:

    -
    ---
    -
    -**Note:** A useful documentation note.
    -
    ----
    -
    -

    Third party packages

    -

    New features to REST framework are generally recommended to be implemented as third party libraries that are developed outside of the core framework. Ideally third party libraries should be properly documented and packaged, and made available on PyPI.

    -

    Getting started

    -

    If you have some functionality that you would like to implement as a third party package it's worth contacting the discussion group as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.

    -

    We recommend the django-reusable-app template as a good resource for getting up and running with implementing a third party Django package.

    -

    Linking to your package

    -

    Once your package is decently documented and available on PyPI open a pull request or issue, 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 Resources section.

    -

    We also suggest adding it to the REST Framework grid on Django Packages.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/contributing/index.html b/topics/contributing/index.html new file mode 100644 index 000000000..0445597a4 --- /dev/null +++ b/topics/contributing/index.html @@ -0,0 +1,631 @@ + + + + + + + Contributing to REST framework - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    Contributing to REST framework

    +
    +

    The world can only really be changed one piece at a time. The art is picking that piece.

    +

    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.

    +

    Community

    +

    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.

    +

    Code of conduct

    +

    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.

    +

    Issues

    +

    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.
    • +
    +

    Triaging issues

    +

    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.
    • +
    +

    Development

    +

    To start developing on Django REST framework, clone the repo:

    +
    git clone git@github.com:tomchristie/django-rest-framework.git
    +
    +

    Changes should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.

    +

    Testing

    +

    To run the tests, clone the repository, and then:

    +
    # Setup the virtual environment
    +virtualenv env
    +source env/bin/activate
    +pip install -r requirements.txt
    +pip install -r requirements-test.txt
    +
    +# Run the tests
    +./runtests.py
    +
    +

    Test options

    +

    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.

    +

    Running against multiple environments

    +

    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
    +
    +

    Pull requests

    +

    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.

    +

    Travis status

    +

    Above: Travis build notifications

    +

    Managing compatibility issues

    +

    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.

    +

    Documentation

    +

    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.

    +

    Building the documentation

    +

    To build the documentation, install MkDocs with pip install mkdocs and then run the following command.

    +
    mkdocs build
    +
    +

    This will build the html output into the html directory.

    +

    You can build the documentation and open a preview in a browser window by using the serve command.

    +
    mkdocs serve
    +
    +

    Language style

    +

    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.
    • +
    • Use double spacing after the end of sentences.
    • +
    • Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
    • +
    +

    Markdown style

    +

    There are a couple of conventions you should follow when working on the documentation.

    +
    1. Headers
    +

    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
    +====================
    +
    + +

    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].
    +
    +More text...
    +
    +[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.

    +
    3. Notes
    +

    If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:

    +
    ---
    +
    +**Note:** A useful documentation note.
    +
    +---
    +
    +

    Third party packages

    +

    New features to REST framework are generally recommended to be implemented as third party libraries that are developed outside of the core framework. Ideally third party libraries should be properly documented and packaged, and made available on PyPI.

    +

    Getting started

    +

    If you have some functionality that you would like to implement as a third party package it's worth contacting the discussion group as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.

    +

    We recommend the django-reusable-app template as a good resource for getting up and running with implementing a third party Django package.

    +

    Linking to your package

    +

    Once your package is decently documented and available on PyPI open a pull request or issue, 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 Resources section.

    +

    We also suggest adding it to the REST Framework grid on Django Packages.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/credits.html b/topics/credits/index.html similarity index 59% rename from topics/credits.html rename to topics/credits/index.html index cd27da06c..6be66631c 100644 --- a/topics/credits.html +++ b/topics/credits/index.html @@ -1,65 +1,74 @@ - - - Credits - Django REST framework - - - - - - - - - - + + + + Credits - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,19 +335,37 @@ a.fusion-poweredby { -->
    + + + + +
  • + Credits +
  • + + +
  • + Additional thanks +
  • + +
  • + Contact +
  • + + + + + + +
    + +

    Credits

    The following people have helped make REST framework great.

    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/topics/documenting-your-api.html b/topics/documenting-your-api.html deleted file mode 100644 index b0e814864..000000000 --- a/topics/documenting-your-api.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - - Documenting your API - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Documenting your API

    -
    -

    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.

    -

    — Roy Fielding, REST APIs must be hypertext driven

    -
    -

    There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.

    -

    Endpoint documentation

    -

    The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.

    -
    -

    Django REST Swagger

    -

    Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.

    -

    The package is fully documented, well supported, and comes highly recommended.

    -

    Django REST Swagger supports REST framework versions 2.3 and above.

    -

    Screenshot - Django REST Swagger

    -
    -

    REST Framework Docs

    -

    The REST Framework Docs package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.

    -

    Screenshot - REST Framework Docs

    -
    -

    Apiary

    -

    There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.

    -

    Screenshot - Apiary

    -
    -

    Self describing APIs

    -

    The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.

    -

    Screenshot - Self describing API

    -
    -

    Setting the title

    -

    The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.

    -

    For example, the view UserListView, will be named User List when presented in the browsable API.

    -

    When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance.

    -

    Setting the description

    -

    The description in the browsable API is generated from the docstring of the view or viewset.

    -

    If the python markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:

    -
    class AccountListView(views.APIView):
    -    """
    -    Returns a list of all **active** accounts in the system.
    -
    -    For more details on how accounts are activated please [see here][ref].
    -
    -    [ref]: http://example.com/activating-accounts
    -    """
    -
    -

    Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.

    -

    The OPTIONS method

    -

    REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with.

    -

    When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer.

    -

    You can modify the response behavior to OPTIONS requests by overriding the metadata view method. For example:

    -
    def metadata(self, request):
    -    """
    -    Don't include the view description in OPTIONS responses.
    -    """ 
    -    data = super(ExampleView, self).metadata(request)
    -    data.pop('description')
    -    return data
    -
    -
    -

    The hypermedia approach

    -

    To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.

    -

    In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.

    -

    To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/documenting-your-api/index.html b/topics/documenting-your-api/index.html new file mode 100644 index 000000000..cca66649d --- /dev/null +++ b/topics/documenting-your-api/index.html @@ -0,0 +1,482 @@ + + + + + + + Documenting your API - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    Documenting your API

    +
    +

    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.

    +

    — Roy Fielding, REST APIs must be hypertext driven

    +
    +

    There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.

    +

    Endpoint documentation

    +

    The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.

    +
    +

    Django REST Swagger

    +

    Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.

    +

    The package is fully documented, well supported, and comes highly recommended.

    +

    Django REST Swagger supports REST framework versions 2.3 and above.

    +

    Screenshot - Django REST Swagger

    +
    +

    REST Framework Docs

    +

    The REST Framework Docs package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.

    +

    Screenshot - REST Framework Docs

    +
    +

    Apiary

    +

    There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.

    +

    Screenshot - Apiary

    +
    +

    Self describing APIs

    +

    The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.

    +

    Screenshot - Self describing API

    +
    +

    Setting the title

    +

    The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.

    +

    For example, the view UserListView, will be named User List when presented in the browsable API.

    +

    When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance.

    +

    Setting the description

    +

    The description in the browsable API is generated from the docstring of the view or viewset.

    +

    If the python markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:

    +
    class AccountListView(views.APIView):
    +    """
    +    Returns a list of all **active** accounts in the system.
    +
    +    For more details on how accounts are activated please [see here][ref].
    +
    +    [ref]: http://example.com/activating-accounts
    +    """
    +
    +

    Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.

    +

    The OPTIONS method

    +

    REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with.

    +

    When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer.

    +

    You can modify the response behavior to OPTIONS requests by overriding the metadata view method. For example:

    +
    def metadata(self, request):
    +    """
    +    Don't include the view description in OPTIONS responses.
    +    """
    +    data = super(ExampleView, self).metadata(request)
    +    data.pop('description')
    +    return data
    +
    +
    +

    The hypermedia approach

    +

    To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.

    +

    In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.

    +

    To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/kickstarter-announcement.html b/topics/kickstarter-announcement/index.html similarity index 57% rename from topics/kickstarter-announcement.html rename to topics/kickstarter-announcement/index.html index 5022f1e0c..90857a244 100644 --- a/topics/kickstarter-announcement.html +++ b/topics/kickstarter-announcement/index.html @@ -1,65 +1,74 @@ - - - Kickstarting Django REST framework 3 - Django REST framework - - - - - - - - - - + + + + Kickstarter Announcement - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,19 +335,37 @@ a.fusion-poweredby { -->
    + +

    Kickstarting Django REST framework 3


    @@ -332,42 +499,52 @@ a.fusion-poweredby {

    Supporters

    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!

    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/topics/release-notes.html b/topics/release-notes/index.html similarity index 75% rename from topics/release-notes.html rename to topics/release-notes/index.html index d3c6a059b..e3b8b5969 100644 --- a/topics/release-notes.html +++ b/topics/release-notes/index.html @@ -1,65 +1,74 @@ - - - Release Notes - Django REST framework - - - - - - - - - - + + + + Release Notes - Django REST framework + + + + + - - + + + + + - - - - - + + +
    - @@ -148,32 +295,34 @@ a.fusion-poweredby {
    - - + +
    @@ -186,29 +335,77 @@ a.fusion-poweredby { -->
    + +

    Release Notes

    Release Early, Release Often

    @@ -235,10 +432,10 @@ a.fusion-poweredby {

    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.

    Upgrading

    To upgrade Django REST framework to the latest version, use pip:

    -
    pip install -U djangorestframework
    +
    pip install -U djangorestframework
     

    You can determine your currently installed version using pip freeze:

    -
    pip freeze | grep djangorestframework
    +
    pip freeze | grep djangorestframework
     

    2.4.x series

    @@ -263,7 +460,7 @@ a.fusion-poweredby {
  • Bugfix: Fix migration in authtoken application.
  • Bugfix: Allow selection of integer keys in nested choices.
  • Bugfix: Return None instead of 'None' in CharField with allow_none=True.
  • -
  • Bugfix: Ensure custom model fields map to equivelent serializer fields more reliably.
  • +
  • Bugfix: Ensure custom model fields map to equivelent serializer fields more reliably.
  • Bugfix: DjangoFilterBackend no longer quietly changes queryset ordering.
  • 2.4.2

    @@ -348,7 +545,7 @@ a.fusion-poweredby {
  • Added write_only_fields option to ModelSerializer classes.
  • JSON renderer now deals with objects that implement a dict-like interface.
  • Fix compatiblity with newer versions of django-oauth-plus.
  • -
  • Bugfix: Refine behavior that calls model manager all() across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations.
  • +
  • Bugfix: Refine behavior that calls model manager all() across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unnecessary queryset re-evaluations.
  • Bugfix: Allow defaults on BooleanFields to be properly honored when values are not supplied.
  • Bugfix: Prevent double-escaping of non-latin1 URL query params when appending format=json params.
  • @@ -395,7 +592,7 @@ a.fusion-poweredby {

    [*] Note that the change in page_size=0 behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.

    -
    class DisablePaginationMixin(object):
    +
    class DisablePaginationMixin(object):
         def get_paginate_by(self, queryset=None):
             if self.request.QUERY_PARAMS[self.paginate_by_param] == '0':
                 return None
    @@ -486,7 +683,7 @@ a.fusion-poweredby {
     
  • Made Login template easier to restyle.
  • Bugfix: Fix issue with depth>1 on ModelSerializer.
  • -

    Note: See the 2.3 announcement for full details.

    +

    Note: See the 2.3 announcement for full details.


    2.2.x series

    2.2.7

    @@ -571,7 +768,7 @@ a.fusion-poweredby {
  • Bugfix: Fix issue with deserializing empty to-many relations.
  • Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom .restore_object() method.
  • -

    Note: See the 2.2 announcement for full details.

    +

    Note: See the 2.2 announcement for full details.


    2.1.x series

    2.1.17

    @@ -741,7 +938,7 @@ a.fusion-poweredby {

    Date: 30th Oct 2012


    0.4.x series

    @@ -861,42 +1058,52 @@ a.fusion-poweredby {
    • Initial release.
    -
    -
    -
    -
    -
    - + + + + + + + + +
    + + - - - - - + + + + + - + - // Dynamically force sidenav to no higher than browser window - $('.side-nav').css('max-height', window.innerHeight - 130); - - $(function(){ - $(window).resize(function(){ - $('.side-nav').css('max-height', window.innerHeight - 130); - }); - }); - - + \ No newline at end of file diff --git a/topics/rest-framework-2-announcement.html b/topics/rest-framework-2-announcement.html deleted file mode 100644 index 6ebab79b9..000000000 --- a/topics/rest-framework-2-announcement.html +++ /dev/null @@ -1,298 +0,0 @@ - - - - - Django REST framework 2 - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Django REST framework 2

    -

    What it is, and why you should care.

    -
    -

    Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.

    -

    Roy Fielding

    -
    -
    -

    Announcement: REST framework 2 released - Tue 30th Oct 2012

    -
    -

    REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.

    -

    Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.

    -

    This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.

    -

    User feedback

    -

    Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…

    -

    "Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - Kit La Touche

    -

    "Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - Ian Strachan

    -

    "I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's much more to my tastes" - Bruno Desthuilliers

    -

    Sounds good, right? Let's get into some details...

    -

    Serialization

    -

    REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:

    -
      -
    • A declarative serialization API, that mirrors Django's Forms/ModelForms API.
    • -
    • Structural concerns are decoupled from encoding concerns.
    • -
    • Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
    • -
    • Validation that can be mapped to obvious and comprehensive error responses.
    • -
    • Serializers that support both nested, flat, and partially-nested representations.
    • -
    • Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
    • -
    -

    Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.

    -

    Generic views

    -

    When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming View class, but it didn't take full advantage of the generic view implementations.

    -

    With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.

    -

    Requests, Responses & Views

    -

    REST framework 2 includes Request and Response classes, than are used in place of Django's existing HttpRequest and HttpResponse classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.

    -

    The Request/Response approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.

    -

    REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single @api_view decorator, and you're good to go.

    -

    API Design

    -

    Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.

    -

    The Browsable API

    -

    Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.

    -

    Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.

    -

    With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.

    -

    There are also some functionality improvements - actions such as as POST and DELETE will only display if the user has the appropriate permissions.

    -

    Browsable API

    -

    Image above: An example of the browsable API in REST framework 2

    -

    Documentation

    -

    As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.

    -

    We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.

    -

    Summary

    -

    In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.

    -

    If you're interested please take a browse around the documentation. The tutorial is a great place to get started.

    -

    There's also a live sandbox version of the tutorial API available for testing.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/rest-framework-2-announcement/index.html b/topics/rest-framework-2-announcement/index.html new file mode 100644 index 000000000..011715d31 --- /dev/null +++ b/topics/rest-framework-2-announcement/index.html @@ -0,0 +1,493 @@ + + + + + + + 2.0 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    Django REST framework 2

    +

    What it is, and why you should care.

    +
    +

    Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.

    +

    Roy Fielding

    +
    +
    +

    Announcement: REST framework 2 released - Tue 30th Oct 2012

    +
    +

    REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.

    +

    Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.

    +

    This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.

    +

    User feedback

    +

    Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…

    +

    "Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - Kit La Touche

    +

    "Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - Ian Strachan

    +

    "I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's much more to my tastes" - Bruno Desthuilliers

    +

    Sounds good, right? Let's get into some details...

    +

    Serialization

    +

    REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:

    +
      +
    • A declarative serialization API, that mirrors Django's Forms/ModelForms API.
    • +
    • Structural concerns are decoupled from encoding concerns.
    • +
    • Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
    • +
    • Validation that can be mapped to obvious and comprehensive error responses.
    • +
    • Serializers that support both nested, flat, and partially-nested representations.
    • +
    • Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
    • +
    +

    Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.

    +

    Generic views

    +

    When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming View class, but it didn't take full advantage of the generic view implementations.

    +

    With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.

    +

    Requests, Responses & Views

    +

    REST framework 2 includes Request and Response classes, than are used in place of Django's existing HttpRequest and HttpResponse classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.

    +

    The Request/Response approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.

    +

    REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single @api_view decorator, and you're good to go.

    +

    API Design

    +

    Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.

    +

    The Browsable API

    +

    Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.

    +

    Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.

    +

    With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.

    +

    There are also some functionality improvements - actions such as as POST and DELETE will only display if the user has the appropriate permissions.

    +

    Browsable API

    +

    Image above: An example of the browsable API in REST framework 2

    +

    Documentation

    +

    As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.

    +

    We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.

    +

    Summary

    +

    In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.

    +

    If you're interested please take a browse around the documentation. The tutorial is a great place to get started.

    +

    There's also a live sandbox version of the tutorial API available for testing.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/rest-hypermedia-hateoas.html b/topics/rest-hypermedia-hateoas.html deleted file mode 100644 index ffe4d760d..000000000 --- a/topics/rest-hypermedia-hateoas.html +++ /dev/null @@ -1,266 +0,0 @@ - - - - - REST, Hypermedia & HATEOAS - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    REST, Hypermedia & HATEOAS

    -
    -

    You keep using that word "REST". I do not think it means what you think it means.

    -

    — Mike Amundsen, REST fest 2012 keynote.

    -
    -

    First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".

    -

    If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices.

    -

    The following fall into the "required reading" category.

    - -

    For a more thorough background, check out Klabnik's Hypermedia API reading list.

    -

    Building Hypermedia APIs with REST framework

    -

    REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.

    -

    What REST framework provides.

    -

    It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.

    -

    REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.

    -

    What REST framework doesn't provide.

    -

    What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/rest-hypermedia-hateoas/index.html b/topics/rest-hypermedia-hateoas/index.html new file mode 100644 index 000000000..afe915528 --- /dev/null +++ b/topics/rest-hypermedia-hateoas/index.html @@ -0,0 +1,446 @@ + + + + + + + REST, Hypermedia & HATEOAS - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    REST, Hypermedia & HATEOAS

    +
    +

    You keep using that word "REST". I do not think it means what you think it means.

    +

    — Mike Amundsen, REST fest 2012 keynote.

    +
    +

    First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".

    +

    If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices.

    +

    The following fall into the "required reading" category.

    + +

    For a more thorough background, check out Klabnik's Hypermedia API reading list.

    +

    Building Hypermedia APIs with REST framework

    +

    REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.

    +

    What REST framework provides.

    +

    It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.

    +

    REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.

    +

    What REST framework doesn't provide.

    +

    What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/third-party-resources.html b/topics/third-party-resources.html deleted file mode 100644 index a7f11af75..000000000 --- a/topics/third-party-resources.html +++ /dev/null @@ -1,330 +0,0 @@ - - - - - Third Party Resources - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Third Party Resources

    -

    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.

    -

    Libraries and Extensions

    -

    Authentication

    - -

    Permissions

    - -

    Serializers

    - -

    Serializer fields

    - -

    Views

    -
      -
    • djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
    • -
    -

    Routers

    -
      -
    • 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.
    • -
    -

    Parsers

    - -

    Renderers

    - -

    Filtering

    - -

    Misc

    - -

    Tutorials

    - -

    Videos

    - -

    Articles

    - -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html new file mode 100644 index 000000000..3c6ed5c2d --- /dev/null +++ b/topics/third-party-resources/index.html @@ -0,0 +1,622 @@ + + + + + + + Third Party Resources - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Third Party Resources

    +

    About Third Party Packages

    +

    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 favour the creation of Third Party Packages to encapsulate new behaviour rather than adding additional functionality directly to Django REST Framework.

    +

    We aim to make creating Third Party Packages as easy as possible, whilst keeping the simplicity of the core API and ensuring that maintenance of the main project remains under control. If a Third Party Package proves popular it is relatively easy to move it into the main project; removing features is much more problematic.

    +

    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 dicuss ideas on the Mailing List.

    +

    How to create a Third Party Package

    +

    Creating your package

    +

    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.

    +

    Running the initial cookiecutter command

    +

    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
    +email (default is "you@example.com")? jappleseed@example.com
    +github_username (default is "yourname")? jappleseed
    +pypi_project_name (default is "dj-package")? djangorestframework-custom-auth
    +repo_name (default is "dj-package")? django-rest-framework-custom-auth
    +app_name (default is "djpackage")? custom_auth
    +project_short_description (default is "Your project description goes here")?
    +year (default is "2014")?
    +version (default is "0.1.0")?
    +
    +

    Getting it onto GitHub

    +

    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.

    +

    Adding to Travis CI

    +

    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.

    +

    Uploading to PyPI

    +

    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
    +$ 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
    +You probably want to also tag the version now:
    +    git tag -a {0} -m 'version 0.1.0'
    +    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.

    +

    Development

    +

    Version requirements

    +

    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.

    +

    Tests

    +

    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-test.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
    +
    +

    Version compatibility

    +

    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.

    +

    Once your package is available

    +

    Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.

    +

    Adding to the Django REST framework grid

    +

    We suggest adding your package to the REST Framework grid on Django Packages.

    +

    Adding to the Django REST framework docs

    +

    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 Resources][third-party-resources] section.

    +

    Announce on the discussion group.

    +

    You can also let others know about your package through the discussion group.

    +

    Existing Third Party Packages

    +

    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.

    +

    Authentication

    + +

    Permissions

    + +

    Serializers

    + +

    Serializer fields

    + +

    Views

    +
      +
    • djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
    • +
    +

    Routers

    +
      +
    • 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.
    • +
    +

    Parsers

    + +

    Renderers

    + +

    Filtering

    + +

    Misc

    + +

    Other Resources

    +

    Tutorials

    + +

    Videos

    + +

    Articles

    + + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/topics/writable-nested-serializers.html b/topics/writable-nested-serializers.html deleted file mode 100644 index eb349413c..000000000 --- a/topics/writable-nested-serializers.html +++ /dev/null @@ -1,274 +0,0 @@ - - - - - Writable nested serializers - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -
    -

    To save HTTP requests, it may be convenient to send related documents along with the request.

    -

    JSON API specification for Ember Data.

    -
    -

    Writable nested serializers

    -

    Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.

    -

    Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action.

    -

    One-to-many data structures

    -

    Example of a read-only nested serializer. Nothing complex to worry about here.

    -
    class ToDoItemSerializer(serializers.ModelSerializer):
    -    class Meta:
    -        model = ToDoItem
    -        fields = ('text', 'is_completed')
    -
    -class ToDoListSerializer(serializers.ModelSerializer):
    -    items = ToDoItemSerializer(many=True, read_only=True)
    -
    -    class Meta:
    -        model = ToDoList
    -        fields = ('title', 'items')
    -
    -

    Some example output from our serializer.

    -
    {
    -    'title': 'Leaving party preperations',
    -    'items': {
    -        {'text': 'Compile playlist', 'is_completed': True},
    -        {'text': 'Send invites', 'is_completed': False},
    -        {'text': 'Clean house', 'is_completed': False}            
    -    }
    -}
    -
    -

    Let's take a look at updating our nested one-to-many data structure.

    -

    Validation errors

    -

    Adding and removing items

    -

    Making PATCH requests

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/1-serialization.html b/tutorial/1-serialization.html deleted file mode 100644 index a94ef276a..000000000 --- a/tutorial/1-serialization.html +++ /dev/null @@ -1,539 +0,0 @@ - - - - - Tutorial 1: Serialization - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 1: Serialization

    -

    Introduction

    -

    This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.

    -

    The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the quickstart documentation instead.

    -
    -

    Note: The code for this tutorial is available in the tomchristie/rest-framework-tutorial repository on GitHub. The completed implementation is also online as a sandbox version for testing, available here.

    -
    -

    Setting up a new environment

    -

    Before we do anything else we'll create a new virtual environment, using virtualenv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.

    -
    -virtualenv env
    -source env/bin/activate
    -
    -

    Now that we're inside a virtualenv environment, we can install our package requirements.

    -
    pip install django
    -pip install djangorestframework
    -pip install pygments  # We'll be using this for the code highlighting
    -
    -

    Note: To exit the virtualenv environment at any time, just type deactivate. For more information see the virtualenv documentation.

    -

    Getting started

    -

    Okay, we're ready to get coding. -To get started, let's create a new project to work with.

    -
    cd ~
    -django-admin.py startproject tutorial
    -cd tutorial
    -
    -

    Once that's done we can create an app that we'll use to create a simple Web API.

    -
    python manage.py startapp snippets
    -
    -

    The simplest way to get up and running will probably be to use an sqlite3 database for the tutorial. Edit the tutorial/settings.py file, and set the default database "ENGINE" to "sqlite3", and "NAME" to "tmp.db".

    -
    DATABASES = {
    -    'default': {
    -        'ENGINE': 'django.db.backends.sqlite3',
    -        'NAME': 'tmp.db',
    -        'USER': '',
    -        'PASSWORD': '',
    -        'HOST': '',
    -        'PORT': '',
    -    }
    -}
    -
    -

    We'll also need to add our new snippets app and the rest_framework app to INSTALLED_APPS.

    -
    INSTALLED_APPS = (
    -    ...
    -    'rest_framework',
    -    'snippets',
    -)
    -
    -

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

    -
    urlpatterns = [
    -    url(r'^', include('snippets.urls')),
    -]
    -
    -

    Okay, we're ready to roll.

    -

    Creating a model to work with

    -

    For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets app's models.py 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.

    -
    from django.db import models
    -from pygments.lexers import get_all_lexers
    -from pygments.styles import get_all_styles
    -
    -LEXERS = [item for item in get_all_lexers() if item[1]]
    -LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
    -STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
    -
    -
    -class Snippet(models.Model):
    -    created = models.DateTimeField(auto_now_add=True)
    -    title = models.CharField(max_length=100, blank=True, default='')
    -    code = models.TextField()
    -    linenos = models.BooleanField(default=False)
    -    language = models.CharField(choices=LANGUAGE_CHOICES,
    -                                default='python',
    -                                max_length=100)
    -    style = models.CharField(choices=STYLE_CHOICES,
    -                             default='friendly',
    -                             max_length=100)
    -
    -    class Meta:
    -        ordering = ('created',)
    -
    -

    Don't forget to sync the database for the first time.

    -
    python manage.py makemigrations snippets
    -python manage.py migrate
    -

    Creating a Serializer class

    -

    The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets directory named serializers.py and add the following.

    -
    from django.forms import widgets
    -from rest_framework import serializers
    -from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
    -
    -
    -class SnippetSerializer(serializers.Serializer):
    -    pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
    -    title = serializers.CharField(required=False,
    -                                  max_length=100)
    -    code = serializers.CharField(widget=widgets.Textarea,
    -                                 max_length=100000)
    -    linenos = serializers.BooleanField(required=False)
    -    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
    -                                       default='python')
    -    style = serializers.ChoiceField(choices=STYLE_CHOICES,
    -                                    default='friendly')
    -
    -    def restore_object(self, attrs, instance=None):
    -        """
    -        Create or update a new snippet instance, given a dictionary
    -        of deserialized field values.
    -
    -        Note that if we don't define this method, then deserializing
    -        data will simply return a dictionary of items.
    -        """
    -        if instance:
    -            # Update existing instance
    -            instance.title = attrs.get('title', instance.title)
    -            instance.code = attrs.get('code', instance.code)
    -            instance.linenos = attrs.get('linenos', instance.linenos)
    -            instance.language = attrs.get('language', instance.language)
    -            instance.style = attrs.get('style', instance.style)
    -            return instance
    -
    -        # Create new instance
    -        return Snippet(**attrs)
    -
    -

    The first part of the serializer class defines the fields that get serialized/deserialized. The restore_object method defines how fully fledged instances get created when deserializing data.

    -

    Notice that we can also use various attributes that would typically be used on form fields, such as widget=widgets.Textarea. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.

    -

    We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but for now we'll keep our serializer definition explicit.

    -

    Working with Serializers

    -

    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
    -from snippets.serializers import SnippetSerializer
    -from rest_framework.renderers import JSONRenderer
    -from rest_framework.parsers import JSONParser
    -
    -snippet = Snippet(code='foo = "bar"\n')
    -snippet.save()
    -
    -snippet = Snippet(code='print "hello, world"\n')
    -snippet.save()
    -
    -

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

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

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

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

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

    -
    # This import will use either `StringIO.StringIO` or `io.BytesIO`
    -# as appropriate, depending on if we're running Python 2 or Python 3.
    -from rest_framework.compat import BytesIO
    -
    -stream = BytesIO(content)
    -data = JSONParser().parse(stream)
    -
    -

    ...then we restore those native datatypes into to a fully populated object instance.

    -
    serializer = SnippetSerializer(data=data)
    -serializer.is_valid()
    -# True
    -serializer.object
    -# <Snippet: Snippet object>
    -
    -

    Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.

    -

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

    -
    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    -serializer.data
    -# [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
    -
    -

    Using ModelSerializers

    -

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

    -

    In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.

    -

    Let's look at refactoring our serializer using the ModelSerializer class. -Open the file snippets/serializers.py again, and edit the SnippetSerializer class.

    -
    class SnippetSerializer(serializers.ModelSerializer):
    -    class Meta:
    -        model = Snippet
    -        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
    -
    -

    Writing regular Django views using our Serializer

    -

    Let's see how we can write some API views using our new Serializer class. -For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.

    -

    We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into json.

    -

    Edit the snippets/views.py file, and add the following.

    -
    from django.http import HttpResponse
    -from django.views.decorators.csrf import csrf_exempt
    -from rest_framework.renderers import JSONRenderer
    -from rest_framework.parsers import JSONParser
    -from snippets.models import Snippet
    -from snippets.serializers import SnippetSerializer
    -
    -class JSONResponse(HttpResponse):
    -    """
    -    An HttpResponse that renders its content into JSON.
    -    """
    -    def __init__(self, data, **kwargs):
    -        content = JSONRenderer().render(data)
    -        kwargs['content_type'] = 'application/json'
    -        super(JSONResponse, self).__init__(content, **kwargs)
    -
    -

    The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.

    -
    @csrf_exempt
    -def snippet_list(request):
    -    """
    -    List all code snippets, or create a new snippet.
    -    """
    -    if request.method == 'GET':
    -        snippets = Snippet.objects.all()
    -        serializer = SnippetSerializer(snippets, many=True)
    -        return JSONResponse(serializer.data)
    -
    -    elif request.method == 'POST':
    -        data = JSONParser().parse(request)
    -        serializer = SnippetSerializer(data=data)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return JSONResponse(serializer.data, status=201)
    -        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
    -def snippet_detail(request, pk):
    -    """
    -    Retrieve, update or delete a code snippet.
    -    """
    -    try:
    -        snippet = Snippet.objects.get(pk=pk)
    -    except Snippet.DoesNotExist:
    -        return HttpResponse(status=404)
    -
    -    if request.method == 'GET':
    -        serializer = SnippetSerializer(snippet)
    -        return JSONResponse(serializer.data)
    -
    -    elif request.method == 'PUT':
    -        data = JSONParser().parse(request)
    -        serializer = SnippetSerializer(snippet, data=data)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return JSONResponse(serializer.data)
    -        return JSONResponse(serializer.errors, status=400)
    -
    -    elif request.method == 'DELETE':
    -        snippet.delete()
    -        return HttpResponse(status=204)
    -
    -

    Finally we need to wire these views up. Create the snippets/urls.py file:

    -
    from django.conf.urls import patterns, url
    -from snippets import views
    -
    -urlpatterns = [
    -    url(r'^snippets/$', views.snippet_list),
    -    url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
    -]
    -
    -

    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.

    -

    Testing our first attempt at a Web API

    -

    Now we can start up a sample server that serves our snippets.

    -

    Quit out of the shell...

    -
    quit()
    -
    -

    ...and start up Django's development server.

    -
    python manage.py runserver
    -
    -Validating models...
    -
    -0 errors found
    -Django version 1.4.3, using settings 'tutorial.settings'
    -Development server is running at http://127.0.0.1:8000/
    -Quit the server with CONTROL-C.
    -
    -

    In another terminal window, we can test the server.

    -

    We can get a list of all of the snippets.

    -
    curl http://127.0.0.1:8000/snippets/
    -
    -[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
    -
    -

    Or we can get a particular snippet by referencing its id.

    -
    curl http://127.0.0.1:8000/snippets/2/
    -
    -{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
    -
    -

    Similarly, you can have the same json displayed by visiting these URLs in a web browser.

    -

    Where are we now

    -

    We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.

    -

    Our API views don't do anything particularly special at the moment, beyond serving json responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.

    -

    We'll see how we can start to improve things in part 2 of the tutorial.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/1-serialization/index.html b/tutorial/1-serialization/index.html new file mode 100644 index 000000000..e861ac0a6 --- /dev/null +++ b/tutorial/1-serialization/index.html @@ -0,0 +1,744 @@ + + + + + + + 1 - Serialization - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 1: Serialization

    +

    Introduction

    +

    This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.

    +

    The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the quickstart documentation instead.

    +
    +

    Note: The code for this tutorial is available in the tomchristie/rest-framework-tutorial repository on GitHub. The completed implementation is also online as a sandbox version for testing, available here.

    +
    +

    Setting up a new environment

    +

    Before we do anything else we'll create a new virtual environment, using virtualenv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.

    +
    :::bash
    +virtualenv env
    +source env/bin/activate
    +
    +

    Now that we're inside a virtualenv environment, we can install our package requirements.

    +
    pip install django
    +pip install djangorestframework
    +pip install pygments  # We'll be using this for the code highlighting
    +
    +

    Note: To exit the virtualenv environment at any time, just type deactivate. For more information see the virtualenv documentation.

    +

    Getting started

    +

    Okay, we're ready to get coding. +To get started, let's create a new project to work with.

    +
    cd ~
    +django-admin.py startproject tutorial
    +cd tutorial
    +
    +

    Once that's done we can create an app that we'll use to create a simple Web API.

    +
    python manage.py startapp snippets
    +
    +

    We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS. Let's edit the tutorial/settings.py file:

    +
    INSTALLED_APPS = (
    +    ...
    +    'rest_framework',
    +    'snippets',
    +)
    +
    +

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

    +
    urlpatterns = [
    +    url(r'^', include('snippets.urls')),
    +]
    +
    +

    Okay, we're ready to roll.

    +

    Creating a model to work with

    +

    For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets/models.py 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.

    +
    from django.db import models
    +from pygments.lexers import get_all_lexers
    +from pygments.styles import get_all_styles
    +
    +LEXERS = [item for item in get_all_lexers() if item[1]]
    +LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
    +STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
    +
    +
    +class Snippet(models.Model):
    +    created = models.DateTimeField(auto_now_add=True)
    +    title = models.CharField(max_length=100, blank=True, default='')
    +    code = models.TextField()
    +    linenos = models.BooleanField(default=False)
    +    language = models.CharField(choices=LANGUAGE_CHOICES,
    +                                default='python',
    +                                max_length=100)
    +    style = models.CharField(choices=STYLE_CHOICES,
    +                             default='friendly',
    +                             max_length=100)
    +
    +    class Meta:
    +        ordering = ('created',)
    +
    +

    We'll also need to create an initial migration for our snippet model, and sync the database for the first time.

    +
    python manage.py makemigrations snippets
    +python manage.py migrate
    +
    +

    Creating a Serializer class

    +

    The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets directory named serializers.py and add the following.

    +
    from django.forms import widgets
    +from rest_framework import serializers
    +from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
    +
    +
    +class SnippetSerializer(serializers.Serializer):
    +    pk = serializers.IntegerField(read_only=True)
    +    title = serializers.CharField(required=False,
    +                                  max_length=100)
    +    code = serializers.CharField(style={'type': 'textarea'})
    +    linenos = serializers.BooleanField(required=False)
    +    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
    +                                       default='python')
    +    style = serializers.ChoiceField(choices=STYLE_CHOICES,
    +                                    default='friendly')
    +
    +    def create(self, validated_attrs):
    +        """
    +        Create and return a new `Snippet` instance, given the validated data.
    +        """
    +        return Snippet.objects.create(**validated_attrs)
    +
    +    def update(self, instance, validated_attrs):
    +        """
    +        Update and return an existing `Snippet` instance, given the validated data.
    +        """
    +        instance.title = validated_attrs.get('title', instance.title)
    +        instance.code = validated_attrs.get('code', instance.code)
    +        instance.linenos = validated_attrs.get('linenos', instance.linenos)
    +        instance.language = validated_attrs.get('language', instance.language)
    +        instance.style = validated_attrs.get('style', instance.style)
    +        instance.save()
    +        return instance
    +
    +

    The first part of the serializer class defines the fields that get serialized/deserialized. The create() and update() methods define how fully fledged instances are created or modified when calling serializer.save()

    +

    A serializer class is very similar to a Django Form class, and includes similar validation flags on the various fields, such as required, max_length and default.

    +

    The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The style={'type': 'textarea'} flag above is equivelent to using widget=widgets.Textarea on a Django Form class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.

    +

    We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but for now we'll keep our serializer definition explicit.

    +

    Working with Serializers

    +

    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
    +from snippets.serializers import SnippetSerializer
    +from rest_framework.renderers import JSONRenderer
    +from rest_framework.parsers import JSONParser
    +
    +snippet = Snippet(code='foo = "bar"\n')
    +snippet.save()
    +
    +snippet = Snippet(code='print "hello, world"\n')
    +snippet.save()
    +
    +

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

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

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

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

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

    +
    # This import will use either `StringIO.StringIO` or `io.BytesIO`
    +# as appropriate, depending on if we're running Python 2 or Python 3.
    +from rest_framework.compat import BytesIO
    +
    +stream = BytesIO(content)
    +data = JSONParser().parse(stream)
    +
    +

    ...then we restore those native datatypes into to a fully populated object instance.

    +
    serializer = SnippetSerializer(data=data)
    +serializer.is_valid()
    +# True
    +serializer.object
    +# <Snippet: Snippet object>
    +
    +

    Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.

    +

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

    +
    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    +serializer.data
    +# [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
    +
    +

    Using ModelSerializers

    +

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

    +

    In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.

    +

    Let's look at refactoring our serializer using the ModelSerializer class. +Open the file snippets/serializers.py again, and edit the SnippetSerializer class.

    +
    class SnippetSerializer(serializers.ModelSerializer):
    +    class Meta:
    +        model = Snippet
    +        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
    +
    +

    Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with python manange.py shell, then try the following:

    +
    >>> from snippets.serializers import SnippetSerializer
    +>>> serializer = SnippetSerializer()
    +>>> print repr(serializer)  # In python 3 use `print(repr(serializer))`
    +SnippetSerializer():
    +    id = IntegerField(label='ID', read_only=True)
    +    title = CharField(allow_blank=True, max_length=100, required=False)
    +    code = CharField(style={'type': 'textarea'})
    +    linenos = BooleanField(required=False)
    +    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
    +    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
    +
    +

    It's important to remember that ModelSerializer classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with:

    +
      +
    • An automatically determined set of fields.
    • +
    • Simple default implementations for the create() and update() methods.
    • +
    +

    Writing regular Django views using our Serializer

    +

    Let's see how we can write some API views using our new Serializer class. +For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.

    +

    We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into json.

    +

    Edit the snippets/views.py file, and add the following.

    +
    from django.http import HttpResponse
    +from django.views.decorators.csrf import csrf_exempt
    +from rest_framework.renderers import JSONRenderer
    +from rest_framework.parsers import JSONParser
    +from snippets.models import Snippet
    +from snippets.serializers import SnippetSerializer
    +
    +class JSONResponse(HttpResponse):
    +    """
    +    An HttpResponse that renders its content into JSON.
    +    """
    +    def __init__(self, data, **kwargs):
    +        content = JSONRenderer().render(data)
    +        kwargs['content_type'] = 'application/json'
    +        super(JSONResponse, self).__init__(content, **kwargs)
    +
    +

    The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.

    +
    @csrf_exempt
    +def snippet_list(request):
    +    """
    +    List all code snippets, or create a new snippet.
    +    """
    +    if request.method == 'GET':
    +        snippets = Snippet.objects.all()
    +        serializer = SnippetSerializer(snippets, many=True)
    +        return JSONResponse(serializer.data)
    +
    +    elif request.method == 'POST':
    +        data = JSONParser().parse(request)
    +        serializer = SnippetSerializer(data=data)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return JSONResponse(serializer.data, status=201)
    +        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
    +def snippet_detail(request, pk):
    +    """
    +    Retrieve, update or delete a code snippet.
    +    """
    +    try:
    +        snippet = Snippet.objects.get(pk=pk)
    +    except Snippet.DoesNotExist:
    +        return HttpResponse(status=404)
    +
    +    if request.method == 'GET':
    +        serializer = SnippetSerializer(snippet)
    +        return JSONResponse(serializer.data)
    +
    +    elif request.method == 'PUT':
    +        data = JSONParser().parse(request)
    +        serializer = SnippetSerializer(snippet, data=data)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return JSONResponse(serializer.data)
    +        return JSONResponse(serializer.errors, status=400)
    +
    +    elif request.method == 'DELETE':
    +        snippet.delete()
    +        return HttpResponse(status=204)
    +
    +

    Finally we need to wire these views up. Create the snippets/urls.py file:

    +
    from django.conf.urls import patterns, url
    +from snippets import views
    +
    +urlpatterns = [
    +    url(r'^snippets/$', views.snippet_list),
    +    url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
    +]
    +
    +

    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.

    +

    Testing our first attempt at a Web API

    +

    Now we can start up a sample server that serves our snippets.

    +

    Quit out of the shell...

    +
    quit()
    +
    +

    ...and start up Django's development server.

    +
    python manage.py runserver
    +
    +Validating models...
    +
    +0 errors found
    +Django version 1.4.3, using settings 'tutorial.settings'
    +Development server is running at http://127.0.0.1:8000/
    +Quit the server with CONTROL-C.
    +
    +

    In another terminal window, we can test the server.

    +

    We can get a list of all of the snippets.

    +
    curl http://127.0.0.1:8000/snippets/
    +
    +[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
    +
    +

    Or we can get a particular snippet by referencing its id.

    +
    curl http://127.0.0.1:8000/snippets/2/
    +
    +{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
    +
    +

    Similarly, you can have the same json displayed by visiting these URLs in a web browser.

    +

    Where are we now

    +

    We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.

    +

    Our API views don't do anything particularly special at the moment, beyond serving json responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.

    +

    We'll see how we can start to improve things in part 2 of the tutorial.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/2-requests-and-responses.html b/tutorial/2-requests-and-responses.html deleted file mode 100644 index 8add5464e..000000000 --- a/tutorial/2-requests-and-responses.html +++ /dev/null @@ -1,378 +0,0 @@ - - - - - Tutorial 2: Requests and Responses - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 2: Requests and Responses

    -

    From this point we're going to really start covering the core of REST framework. -Let's introduce a couple of essential building blocks.

    -

    Request objects

    -

    REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.DATA attribute, which is similar to request.POST, but more useful for working with Web APIs.

    -
    request.POST  # Only handles form data.  Only works for 'POST' method.
    -request.DATA  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.
    -
    -

    Response objects

    -

    REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.

    -
    return Response(data)  # Renders to content type as requested by the client.
    -
    -

    Status codes

    -

    Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as HTTP_400_BAD_REQUEST in the status module. It's a good idea to use these throughout rather than using numeric identifiers.

    -

    Wrapping API views

    -

    REST framework provides two wrappers you can use to write API views.

    -
      -
    1. The @api_view decorator for working with function based views.
    2. -
    3. The APIView class for working with class based views.
    4. -
    -

    These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.

    -

    The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.DATA with malformed input.

    -

    Pulling it all together

    -

    Okay, let's go ahead and start using these new components to write a few views.

    -

    We don't need our JSONResponse class in views.py anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.

    -
    from rest_framework import status
    -from rest_framework.decorators import api_view
    -from rest_framework.response import Response
    -from snippets.models import Snippet
    -from snippets.serializers import SnippetSerializer
    -
    -
    -@api_view(['GET', 'POST'])
    -def snippet_list(request):
    -    """
    -    List all snippets, or create a new snippet.
    -    """
    -    if request.method == 'GET':
    -        snippets = Snippet.objects.all()
    -        serializer = SnippetSerializer(snippets, many=True)
    -        return Response(serializer.data)
    -
    -    elif request.method == 'POST':
    -        serializer = SnippetSerializer(data=request.DATA)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return Response(serializer.data, status=status.HTTP_201_CREATED)
    -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    -
    -

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

    -

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

    -
    @api_view(['GET', 'PUT', 'DELETE'])
    -def snippet_detail(request, pk):
    -    """
    -    Retrieve, update or delete a snippet instance.
    -    """
    -    try:
    -        snippet = Snippet.objects.get(pk=pk)
    -    except Snippet.DoesNotExist:
    -        return Response(status=status.HTTP_404_NOT_FOUND)
    -
    -    if request.method == 'GET':
    -        serializer = SnippetSerializer(snippet)
    -        return Response(serializer.data)
    -
    -    elif request.method == 'PUT':
    -        serializer = SnippetSerializer(snippet, data=request.DATA)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return Response(serializer.data)
    -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    -
    -    elif request.method == 'DELETE':
    -        snippet.delete()
    -        return Response(status=status.HTTP_204_NO_CONTENT)
    -
    -

    This should all feel very familiar - it is not a lot different from working with regular Django views.

    -

    Notice that we're no longer explicitly tying our requests or responses to a given content type. request.DATA can handle incoming json requests, but it can also handle yaml and 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.

    -

    Adding optional format suffixes to our URLs

    -

    To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.

    -

    Start by adding a format keyword argument to both of the views, like so.

    -
    def snippet_list(request, format=None):
    -
    -

    and

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

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

    -
    from django.conf.urls import patterns, url
    -from rest_framework.urlpatterns import format_suffix_patterns
    -from snippets import views
    -
    -urlpatterns = [
    -    url(r'^snippets/$', views.snippet_list),
    -    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
    -]
    -
    -urlpatterns = 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.

    -

    How's it looking?

    -

    Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

    -

    We can get a list of all of the snippets, as before.

    -
    curl http://127.0.0.1:8000/snippets/
    -
    -[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
    -
    -

    We can control the format of the response that we get back, either by using the Accept header:

    -
    curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json'  # Request JSON
    -curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html'         # Request HTML
    -
    -

    Or by appending a format suffix:

    -
    curl http://127.0.0.1:8000/snippets/.json  # JSON suffix
    -curl http://127.0.0.1:8000/snippets/.api   # Browsable API suffix
    -
    -

    Similarly, we can control the format of the request that we send, using the Content-Type header.

    -
    # POST using form data
    -curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
    -
    -{"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"}
    -
    -# POST using JSON
    -curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
    -
    -{"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
    -
    -

    Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.

    -

    Browsability

    -

    Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.

    -

    Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.

    -

    See the browsable api topic for more information about the browsable API feature and how to customize it.

    -

    What's next?

    -

    In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/2-requests-and-responses/index.html b/tutorial/2-requests-and-responses/index.html new file mode 100644 index 000000000..aab357695 --- /dev/null +++ b/tutorial/2-requests-and-responses/index.html @@ -0,0 +1,573 @@ + + + + + + + 2 - Requests and responses - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 2: Requests and Responses

    +

    From this point we're going to really start covering the core of REST framework. +Let's introduce a couple of essential building blocks.

    +

    Request objects

    +

    REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.DATA attribute, which is similar to request.POST, but more useful for working with Web APIs.

    +
    request.POST  # Only handles form data.  Only works for 'POST' method.
    +request.DATA  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.
    +
    +

    Response objects

    +

    REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.

    +
    return Response(data)  # Renders to content type as requested by the client.
    +
    +

    Status codes

    +

    Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as HTTP_400_BAD_REQUEST in the status module. It's a good idea to use these throughout rather than using numeric identifiers.

    +

    Wrapping API views

    +

    REST framework provides two wrappers you can use to write API views.

    +
      +
    1. The @api_view decorator for working with function based views.
    2. +
    3. The APIView class for working with class based views.
    4. +
    +

    These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.

    +

    The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.DATA with malformed input.

    +

    Pulling it all together

    +

    Okay, let's go ahead and start using these new components to write a few views.

    +

    We don't need our JSONResponse class in views.py anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.

    +
    from rest_framework import status
    +from rest_framework.decorators import api_view
    +from rest_framework.response import Response
    +from snippets.models import Snippet
    +from snippets.serializers import SnippetSerializer
    +
    +
    +@api_view(['GET', 'POST'])
    +def snippet_list(request):
    +    """
    +    List all snippets, or create a new snippet.
    +    """
    +    if request.method == 'GET':
    +        snippets = Snippet.objects.all()
    +        serializer = SnippetSerializer(snippets, many=True)
    +        return Response(serializer.data)
    +
    +    elif request.method == 'POST':
    +        serializer = SnippetSerializer(data=request.DATA)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return Response(serializer.data, status=status.HTTP_201_CREATED)
    +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    +
    +

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

    +

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

    +
    @api_view(['GET', 'PUT', 'DELETE'])
    +def snippet_detail(request, pk):
    +    """
    +    Retrieve, update or delete a snippet instance.
    +    """
    +    try:
    +        snippet = Snippet.objects.get(pk=pk)
    +    except Snippet.DoesNotExist:
    +        return Response(status=status.HTTP_404_NOT_FOUND)
    +
    +    if request.method == 'GET':
    +        serializer = SnippetSerializer(snippet)
    +        return Response(serializer.data)
    +
    +    elif request.method == 'PUT':
    +        serializer = SnippetSerializer(snippet, data=request.DATA)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return Response(serializer.data)
    +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    +
    +    elif request.method == 'DELETE':
    +        snippet.delete()
    +        return Response(status=status.HTTP_204_NO_CONTENT)
    +
    +

    This should all feel very familiar - it is not a lot different from working with regular Django views.

    +

    Notice that we're no longer explicitly tying our requests or responses to a given content type. request.DATA can handle incoming json requests, but it can also handle yaml and 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.

    +

    Adding optional format suffixes to our URLs

    +

    To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.

    +

    Start by adding a format keyword argument to both of the views, like so.

    +
    def snippet_list(request, format=None):
    +
    +

    and

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

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

    +
    from django.conf.urls import patterns, url
    +from rest_framework.urlpatterns import format_suffix_patterns
    +from snippets import views
    +
    +urlpatterns = [
    +    url(r'^snippets/$', views.snippet_list),
    +    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
    +]
    +
    +urlpatterns = 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.

    +

    How's it looking?

    +

    Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

    +

    We can get a list of all of the snippets, as before.

    +
    curl http://127.0.0.1:8000/snippets/
    +
    +[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
    +
    +

    We can control the format of the response that we get back, either by using the Accept header:

    +
    curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json'  # Request JSON
    +curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html'         # Request HTML
    +
    +

    Or by appending a format suffix:

    +
    curl http://127.0.0.1:8000/snippets/.json  # JSON suffix
    +curl http://127.0.0.1:8000/snippets/.api   # Browsable API suffix
    +
    +

    Similarly, we can control the format of the request that we send, using the Content-Type header.

    +
    # POST using form data
    +curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
    +
    +{"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"}
    +
    +# POST using JSON
    +curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
    +
    +{"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
    +
    +

    Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.

    +

    Browsability

    +

    Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.

    +

    Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.

    +

    See the browsable api topic for more information about the browsable API feature and how to customize it.

    +

    What's next?

    +

    In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/3-class-based-views.html b/tutorial/3-class-based-views.html deleted file mode 100644 index c8a1d7284..000000000 --- a/tutorial/3-class-based-views.html +++ /dev/null @@ -1,370 +0,0 @@ - - - - - Tutorial 3: Class Based Views - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 3: Class Based Views

    -

    We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.

    -

    Rewriting our API using class based views

    -

    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
    -from snippets.serializers import SnippetSerializer
    -from django.http import Http404
    -from rest_framework.views import APIView
    -from rest_framework.response import Response
    -from rest_framework import status
    -
    -
    -class SnippetList(APIView):
    -    """
    -    List all snippets, or create a new snippet.
    -    """
    -    def get(self, request, format=None):
    -        snippets = Snippet.objects.all()
    -        serializer = SnippetSerializer(snippets, many=True)
    -        return Response(serializer.data)
    -
    -    def post(self, request, format=None):
    -        serializer = SnippetSerializer(data=request.DATA)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return Response(serializer.data, status=status.HTTP_201_CREATED)
    -        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):
    -    """
    -    Retrieve, update or delete a snippet instance.
    -    """
    -    def get_object(self, pk):
    -        try:
    -            return Snippet.objects.get(pk=pk)
    -        except Snippet.DoesNotExist:
    -            raise Http404
    -
    -    def get(self, request, pk, format=None):
    -        snippet = self.get_object(pk)
    -        serializer = SnippetSerializer(snippet)
    -        return Response(serializer.data)
    -
    -    def put(self, request, pk, format=None):
    -        snippet = self.get_object(pk)
    -        serializer = SnippetSerializer(snippet, data=request.DATA)
    -        if serializer.is_valid():
    -            serializer.save()
    -            return Response(serializer.data)
    -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    -
    -    def delete(self, request, pk, format=None):
    -        snippet = self.get_object(pk)
    -        snippet.delete()
    -        return Response(status=status.HTTP_204_NO_CONTENT)
    -
    -

    That's looking good. Again, it's still pretty similar to the function based view right now.

    -

    We'll also need to refactor our urls.py slightly now we're using class based views.

    -
    from django.conf.urls import patterns, url
    -from rest_framework.urlpatterns import format_suffix_patterns
    -from snippets import views
    -
    -urlpatterns = [
    -    url(r'^snippets/$', views.SnippetList.as_view()),
    -    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
    -]
    -
    -urlpatterns = format_suffix_patterns(urlpatterns)
    -
    -

    Okay, we're done. If you run the development server everything should be working just as before.

    -

    Using mixins

    -

    One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.

    -

    The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.

    -

    Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module again.

    -
    from snippets.models import Snippet
    -from snippets.serializers import SnippetSerializer
    -from rest_framework import mixins
    -from rest_framework import generics
    -
    -class SnippetList(mixins.ListModelMixin,
    -                  mixins.CreateModelMixin,
    -                  generics.GenericAPIView):
    -    queryset = Snippet.objects.all()
    -    serializer_class = SnippetSerializer
    -
    -    def get(self, request, *args, **kwargs):
    -        return self.list(request, *args, **kwargs)
    -
    -    def post(self, request, *args, **kwargs):
    -        return self.create(request, *args, **kwargs)
    -
    -

    We'll take a moment to examine exactly what's happening here. We're building our view using GenericAPIView, and adding in ListModelMixin and CreateModelMixin.

    -

    The base class provides the core functionality, and the mixin classes provide the .list() and .create() actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough stuff so far.

    -
    class SnippetDetail(mixins.RetrieveModelMixin,
    -                    mixins.UpdateModelMixin,
    -                    mixins.DestroyModelMixin,
    -                    generics.GenericAPIView):
    -    queryset = Snippet.objects.all()
    -    serializer_class = SnippetSerializer
    -
    -    def get(self, request, *args, **kwargs):
    -        return self.retrieve(request, *args, **kwargs)
    -
    -    def put(self, request, *args, **kwargs):
    -        return self.update(request, *args, **kwargs)
    -
    -    def delete(self, request, *args, **kwargs):
    -        return self.destroy(request, *args, **kwargs)
    -
    -

    Pretty similar. Again we're using the GenericAPIView class to provide the core functionality, and adding in mixins to provide the .retrieve(), .update() and .destroy() actions.

    -

    Using generic class based views

    -

    Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.

    -
    from snippets.models import Snippet
    -from snippets.serializers import SnippetSerializer
    -from rest_framework import generics
    -
    -
    -class SnippetList(generics.ListCreateAPIView):
    -    queryset = Snippet.objects.all()
    -    serializer_class = SnippetSerializer
    -
    -
    -class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    -    queryset = Snippet.objects.all()
    -    serializer_class = SnippetSerializer
    -
    -

    Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

    -

    Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/3-class-based-views/index.html b/tutorial/3-class-based-views/index.html new file mode 100644 index 000000000..433584782 --- /dev/null +++ b/tutorial/3-class-based-views/index.html @@ -0,0 +1,550 @@ + + + + + + + 3 - Class based views - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 3: Class Based Views

    +

    We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.

    +

    Rewriting our API using class based views

    +

    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
    +from snippets.serializers import SnippetSerializer
    +from django.http import Http404
    +from rest_framework.views import APIView
    +from rest_framework.response import Response
    +from rest_framework import status
    +
    +
    +class SnippetList(APIView):
    +    """
    +    List all snippets, or create a new snippet.
    +    """
    +    def get(self, request, format=None):
    +        snippets = Snippet.objects.all()
    +        serializer = SnippetSerializer(snippets, many=True)
    +        return Response(serializer.data)
    +
    +    def post(self, request, format=None):
    +        serializer = SnippetSerializer(data=request.DATA)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return Response(serializer.data, status=status.HTTP_201_CREATED)
    +        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):
    +    """
    +    Retrieve, update or delete a snippet instance.
    +    """
    +    def get_object(self, pk):
    +        try:
    +            return Snippet.objects.get(pk=pk)
    +        except Snippet.DoesNotExist:
    +            raise Http404
    +
    +    def get(self, request, pk, format=None):
    +        snippet = self.get_object(pk)
    +        serializer = SnippetSerializer(snippet)
    +        return Response(serializer.data)
    +
    +    def put(self, request, pk, format=None):
    +        snippet = self.get_object(pk)
    +        serializer = SnippetSerializer(snippet, data=request.DATA)
    +        if serializer.is_valid():
    +            serializer.save()
    +            return Response(serializer.data)
    +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    +
    +    def delete(self, request, pk, format=None):
    +        snippet = self.get_object(pk)
    +        snippet.delete()
    +        return Response(status=status.HTTP_204_NO_CONTENT)
    +
    +

    That's looking good. Again, it's still pretty similar to the function based view right now.

    +

    We'll also need to refactor our urls.py slightly now we're using class based views.

    +
    from django.conf.urls import patterns, url
    +from rest_framework.urlpatterns import format_suffix_patterns
    +from snippets import views
    +
    +urlpatterns = [
    +    url(r'^snippets/$', views.SnippetList.as_view()),
    +    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
    +]
    +
    +urlpatterns = format_suffix_patterns(urlpatterns)
    +
    +

    Okay, we're done. If you run the development server everything should be working just as before.

    +

    Using mixins

    +

    One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.

    +

    The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.

    +

    Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module again.

    +
    from snippets.models import Snippet
    +from snippets.serializers import SnippetSerializer
    +from rest_framework import mixins
    +from rest_framework import generics
    +
    +class SnippetList(mixins.ListModelMixin,
    +                  mixins.CreateModelMixin,
    +                  generics.GenericAPIView):
    +    queryset = Snippet.objects.all()
    +    serializer_class = SnippetSerializer
    +
    +    def get(self, request, *args, **kwargs):
    +        return self.list(request, *args, **kwargs)
    +
    +    def post(self, request, *args, **kwargs):
    +        return self.create(request, *args, **kwargs)
    +
    +

    We'll take a moment to examine exactly what's happening here. We're building our view using GenericAPIView, and adding in ListModelMixin and CreateModelMixin.

    +

    The base class provides the core functionality, and the mixin classes provide the .list() and .create() actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough stuff so far.

    +
    class SnippetDetail(mixins.RetrieveModelMixin,
    +                    mixins.UpdateModelMixin,
    +                    mixins.DestroyModelMixin,
    +                    generics.GenericAPIView):
    +    queryset = Snippet.objects.all()
    +    serializer_class = SnippetSerializer
    +
    +    def get(self, request, *args, **kwargs):
    +        return self.retrieve(request, *args, **kwargs)
    +
    +    def put(self, request, *args, **kwargs):
    +        return self.update(request, *args, **kwargs)
    +
    +    def delete(self, request, *args, **kwargs):
    +        return self.destroy(request, *args, **kwargs)
    +
    +

    Pretty similar. Again we're using the GenericAPIView class to provide the core functionality, and adding in mixins to provide the .retrieve(), .update() and .destroy() actions.

    +

    Using generic class based views

    +

    Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.

    +
    from snippets.models import Snippet
    +from snippets.serializers import SnippetSerializer
    +from rest_framework import generics
    +
    +
    +class SnippetList(generics.ListCreateAPIView):
    +    queryset = Snippet.objects.all()
    +    serializer_class = SnippetSerializer
    +
    +
    +class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    +    queryset = Snippet.objects.all()
    +    serializer_class = SnippetSerializer
    +
    +

    Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

    +

    Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/4-authentication-and-permissions.html b/tutorial/4-authentication-and-permissions.html deleted file mode 100644 index f72c89307..000000000 --- a/tutorial/4-authentication-and-permissions.html +++ /dev/null @@ -1,406 +0,0 @@ - - - - - Tutorial 4: Authentication & Permissions - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 4: Authentication & Permissions

    -

    Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:

    -
      -
    • Code snippets are always associated with a creator.
    • -
    • Only authenticated users may create snippets.
    • -
    • Only the creator of a snippet may update or delete it.
    • -
    • Unauthenticated requests should have full read-only access.
    • -
    -

    Adding information to our model

    -

    We're going to make a couple of changes to our Snippet model class. -First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.

    -

    Add the following two fields to the Snippet model in models.py.

    -
    owner = models.ForeignKey('auth.User', related_name='snippets')
    -highlighted = models.TextField()
    -
    -

    We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.

    -

    We'll need some extra imports:

    -
    from pygments.lexers import get_lexer_by_name
    -from pygments.formatters.html import HtmlFormatter
    -from pygments import highlight
    -
    -

    And now we can add a .save() method to our model class:

    -
    def save(self, *args, **kwargs):
    -    """
    -    Use the `pygments` library to create a highlighted HTML
    -    representation of the code snippet.
    -    """
    -    lexer = get_lexer_by_name(self.language)
    -    linenos = self.linenos and 'table' or False
    -    options = self.title and {'title': self.title} or {}
    -    formatter = HtmlFormatter(style=self.style, linenos=linenos,
    -                              full=True, **options)
    -    self.highlighted = highlight(self.code, lexer, formatter)
    -    super(Snippet, self).save(*args, **kwargs)
    -
    -

    When that's all done we'll need to update our database tables. -Normally 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.

    -
    rm tmp.db
    -python manage.py syncdb
    -
    -

    You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.

    -
    python manage.py createsuperuser
    -
    -

    Adding endpoints for our User models

    -

    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
    -
    -class UserSerializer(serializers.ModelSerializer):
    -    snippets = serializers.PrimaryKeyRelatedField(many=True)
    -
    -    class Meta:
    -        model = User
    -        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
    -
    -
    -class UserList(generics.ListAPIView):
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -
    -class UserDetail(generics.RetrieveAPIView):
    -    queryset = User.objects.all()
    -    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()),
    -url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
    -
    -

    Associating Snippets with Users

    -

    Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.

    -

    The way we deal with that is by overriding a .pre_save() method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.

    -

    On both the SnippetList and SnippetDetail view classes, add the following method:

    -
    def pre_save(self, obj):
    -    obj.owner = self.request.user
    -
    -

    Updating our serializer

    -

    Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:

    -
    owner = serializers.Field(source='owner.username')
    -
    -

    Note: Make sure you also add 'owner', to the list of fields in the inner Meta class.

    -

    This field is doing something quite interesting. The source 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.

    -

    The field we've added is the untyped Field class, in contrast to the other typed fields, such as CharField, BooleanField etc... The untyped Field is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.

    -

    Adding required permissions to views

    -

    Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.

    -

    REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.

    -

    First add the following import in the views module

    -
    from rest_framework import permissions
    -
    -

    Then, add the following property to both the SnippetList and SnippetDetail view classes.

    -
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    -
    -

    Adding login to the Browsable API

    -

    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 += [
    -    url(r'^api-auth/', include('rest_framework.urls',
    -                               namespace='rest_framework')),
    -]
    -
    -

    The r'^api-auth/' part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework' namespace.

    -

    Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.

    -

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

    -

    Object level permissions

    -

    Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.

    -

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

    -

    In the snippets app, create a new file, permissions.py

    -
    from rest_framework import permissions
    -
    -
    -class IsOwnerOrReadOnly(permissions.BasePermission):
    -    """
    -    Custom permission to only allow owners of an object to edit it.
    -    """
    -
    -    def has_object_permission(self, request, view, obj):
    -        # Read permissions are allowed to any request,
    -        # so we'll always allow GET, HEAD or OPTIONS requests.
    -        if request.method in permissions.SAFE_METHODS:
    -            return True
    -
    -        # Write permissions are only allowed to the owner of the snippet.
    -        return obj.owner == request.user
    -
    -

    Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail class:

    -
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
    -                      IsOwnerOrReadOnly,)
    -
    -

    Make sure to also import the IsOwnerOrReadOnly class.

    -
    from snippets.permissions import IsOwnerOrReadOnly
    -
    -

    Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.

    -

    Authenticating with the API

    -

    Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.

    -

    When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.

    -

    If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.

    -

    If we try to create a snippet without authenticating, we'll get an error:

    -
    curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
    -
    -{"detail": "Authentication credentials were not provided."}
    -
    -

    We can make a successful request by including the username and password of one of the users we created earlier.

    -
    curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password
    -
    -{"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"}
    -
    -

    Summary

    -

    We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.

    -

    In part 5 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.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html new file mode 100644 index 000000000..90e2d9211 --- /dev/null +++ b/tutorial/4-authentication-and-permissions/index.html @@ -0,0 +1,607 @@ + + + + + + + 4 - Authentication and permissions - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 4: Authentication & Permissions

    +

    Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:

    +
      +
    • Code snippets are always associated with a creator.
    • +
    • Only authenticated users may create snippets.
    • +
    • Only the creator of a snippet may update or delete it.
    • +
    • Unauthenticated requests should have full read-only access.
    • +
    +

    Adding information to our model

    +

    We're going to make a couple of changes to our Snippet model class. +First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.

    +

    Add the following two fields to the Snippet model in models.py.

    +
    owner = models.ForeignKey('auth.User', related_name='snippets')
    +highlighted = models.TextField()
    +
    +

    We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.

    +

    We'll need some extra imports:

    +
    from pygments.lexers import get_lexer_by_name
    +from pygments.formatters.html import HtmlFormatter
    +from pygments import highlight
    +
    +

    And now we can add a .save() method to our model class:

    +
    def save(self, *args, **kwargs):
    +    """
    +    Use the `pygments` library to create a highlighted HTML
    +    representation of the code snippet.
    +    """
    +    lexer = get_lexer_by_name(self.language)
    +    linenos = self.linenos and 'table' or False
    +    options = self.title and {'title': self.title} or {}
    +    formatter = HtmlFormatter(style=self.style, linenos=linenos,
    +                              full=True, **options)
    +    self.highlighted = highlight(self.code, lexer, formatter)
    +    super(Snippet, self).save(*args, **kwargs)
    +
    +

    When that's all done we'll need to update our database tables. +Normally 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.

    +
    rm tmp.db
    +rm -r snippets/migrations
    +python manage.py makemigrations snippets
    +python manage.py migrate
    +
    +

    You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.

    +
    python manage.py createsuperuser
    +
    +

    Adding endpoints for our User models

    +

    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
    +
    +class UserSerializer(serializers.ModelSerializer):
    +    snippets = serializers.PrimaryKeyRelatedField(many=True)
    +
    +    class Meta:
    +        model = User
    +        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
    +
    +
    +class UserList(generics.ListAPIView):
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +
    +
    +class UserDetail(generics.RetrieveAPIView):
    +    queryset = User.objects.all()
    +    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()),
    +url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
    +
    +

    Associating Snippets with Users

    +

    Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.

    +

    The way we deal with that is by overriding a .perform_create() 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.

    +

    On the SnippetList view class, add the following method:

    +
    def perform_create(self, serializer):
    +    serializer.save(owner=self.request.user)
    +
    +

    The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request.

    +

    Updating our serializer

    +

    Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:

    +
    owner = serializers.ReadOnlyField(source='owner.username')
    +
    +

    Note: Make sure you also add 'owner', to the list of fields in the inner Meta class.

    +

    This field is doing something quite interesting. The source 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.

    +

    The field we've added is the untyped ReadOnlyField class, in contrast to the other typed fields, such as CharField, BooleanField etc... The untyped ReadOnlyField 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 CharField(read_only=True) here.

    +

    Adding required permissions to views

    +

    Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.

    +

    REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.

    +

    First add the following import in the views module

    +
    from rest_framework import permissions
    +
    +

    Then, add the following property to both the SnippetList and SnippetDetail view classes.

    +
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    +
    +

    Adding login to the Browsable API

    +

    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 += [
    +    url(r'^api-auth/', include('rest_framework.urls',
    +                               namespace='rest_framework')),
    +]
    +
    +

    The r'^api-auth/' part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework' namespace.

    +

    Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.

    +

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

    +

    Object level permissions

    +

    Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.

    +

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

    +

    In the snippets app, create a new file, permissions.py

    +
    from rest_framework import permissions
    +
    +
    +class IsOwnerOrReadOnly(permissions.BasePermission):
    +    """
    +    Custom permission to only allow owners of an object to edit it.
    +    """
    +
    +    def has_object_permission(self, request, view, obj):
    +        # Read permissions are allowed to any request,
    +        # so we'll always allow GET, HEAD or OPTIONS requests.
    +        if request.method in permissions.SAFE_METHODS:
    +            return True
    +
    +        # Write permissions are only allowed to the owner of the snippet.
    +        return obj.owner == request.user
    +
    +

    Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail class:

    +
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
    +                      IsOwnerOrReadOnly,)
    +
    +

    Make sure to also import the IsOwnerOrReadOnly class.

    +
    from snippets.permissions import IsOwnerOrReadOnly
    +
    +

    Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.

    +

    Authenticating with the API

    +

    Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.

    +

    When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.

    +

    If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.

    +

    If we try to create a snippet without authenticating, we'll get an error:

    +
    curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
    +
    +{"detail": "Authentication credentials were not provided."}
    +
    +

    We can make a successful request by including the username and password of one of the users we created earlier.

    +
    curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password
    +
    +{"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"}
    +
    +

    Summary

    +

    We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.

    +

    In part 5 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.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/5-relationships-and-hyperlinked-apis.html b/tutorial/5-relationships-and-hyperlinked-apis.html deleted file mode 100644 index 250a3d521..000000000 --- a/tutorial/5-relationships-and-hyperlinked-apis.html +++ /dev/null @@ -1,372 +0,0 @@ - - - - - Tutorial 5: Relationships & Hyperlinked APIs - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 5: Relationships & Hyperlinked APIs

    -

    At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.

    -

    Creating an endpoint for the root of our API

    -

    Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view decorator we introduced earlier. In your snippets/views.py add:

    -
    from rest_framework import renderers
    -from rest_framework.decorators import api_view
    -from rest_framework.response import Response
    -from rest_framework.reverse import reverse
    -
    -
    -@api_view(('GET',))
    -def api_root(request, format=None):
    -    return Response({
    -        'users': reverse('user-list', request=request, format=format),
    -        'snippets': reverse('snippet-list', request=request, format=format)
    -    })
    -
    -

    Notice that we're using REST framework's reverse function in order to return fully-qualified URLs.

    -

    Creating an endpoint for the highlighted snippets

    -

    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
    -from rest_framework.response import Response
    -
    -class SnippetHighlight(generics.GenericAPIView):
    -    queryset = Snippet.objects.all()
    -    renderer_classes = (renderers.StaticHTMLRenderer,)
    -
    -    def get(self, request, *args, **kwargs):
    -        snippet = self.get_object()
    -        return Response(snippet.highlighted)
    -
    -

    As usual we need to add the new views that we've created in to our URLconf. -We'll add a url pattern for our new API root in snippets/urls.py:

    -
    url(r'^$', 'api_root'),
    -
    -

    And then add a url pattern for the snippet highlights:

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

    Hyperlinking our API

    -

    Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:

    -
      -
    • Using primary keys.
    • -
    • Using hyperlinking between entities.
    • -
    • Using a unique identifying slug field on the related entity.
    • -
    • Using the default string representation of the related entity.
    • -
    • Nesting the related entity inside the parent representation.
    • -
    • Some other custom representation.
    • -
    -

    REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.

    -

    In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer instead of the existing ModelSerializer.

    -

    The HyperlinkedModelSerializer has the following differences from ModelSerializer:

    -
      -
    • It does not include the pk field by default.
    • -
    • It includes a url field, using HyperlinkedIdentityField.
    • -
    • Relationships use HyperlinkedRelatedField, - instead of PrimaryKeyRelatedField.
    • -
    -

    We can easily re-write our existing serializers to use hyperlinking. In your snippets/serializers.py add:

    -
    class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    -    owner = serializers.Field(source='owner.username')
    -    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
    -
    -    class Meta:
    -        model = Snippet
    -        fields = ('url', 'highlight', 'owner',
    -                  'title', 'code', 'linenos', 'language', 'style')
    -
    -
    -class UserSerializer(serializers.HyperlinkedModelSerializer):
    -    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
    -
    -    class Meta:
    -        model = User
    -        fields = ('url', 'username', 'snippets')
    -
    -

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

    -

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

    -

    Making sure our URL patterns are named

    -

    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 something like this:

    -
    # API endpoints
    -urlpatterns = format_suffix_patterns([
    -    url(r'^$', views.api_root),
    -    url(r'^snippets/$',
    -        views.SnippetList.as_view(),
    -        name='snippet-list'),
    -    url(r'^snippets/(?P<pk>[0-9]+)/$',
    -        views.SnippetDetail.as_view(),
    -        name='snippet-detail'),
    -    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
    -        views.SnippetHighlight.as_view(),
    -        name='snippet-highlight'),
    -    url(r'^users/$',
    -        views.UserList.as_view(),
    -        name='user-list'),
    -    url(r'^users/(?P<pk>[0-9]+)/$',
    -        views.UserDetail.as_view(),
    -        name='user-detail')
    -])
    -
    -# Login and logout views for the browsable API
    -urlpatterns += [
    -    url(r'^api-auth/', include('rest_framework.urls',
    -                               namespace='rest_framework')),
    -]
    -
    -

    Adding pagination

    -

    The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.

    -

    We can change the default list style to use pagination, by modifying our settings.py file slightly. Add the following setting:

    -
    REST_FRAMEWORK = {
    -    'PAGINATE_BY': 10
    -}
    -
    -

    Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.

    -

    We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.

    -

    Browsing the API

    -

    If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.

    -

    You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.

    -

    In part 6 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.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html new file mode 100644 index 000000000..dd39c4313 --- /dev/null +++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html @@ -0,0 +1,560 @@ + + + + + + + 5 - Relationships and hyperlinked APIs - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 5: Relationships & Hyperlinked APIs

    +

    At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.

    +

    Creating an endpoint for the root of our API

    +

    Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view decorator we introduced earlier. In your snippets/views.py add:

    +
    from rest_framework.decorators import api_view
    +from rest_framework.response import Response
    +from rest_framework.reverse import reverse
    +
    +
    +@api_view(('GET',))
    +def api_root(request, format=None):
    +    return Response({
    +        'users': reverse('user-list', request=request, format=format),
    +        'snippets': reverse('snippet-list', request=request, format=format)
    +    })
    +
    +

    Notice that we're using REST framework's reverse function in order to return fully-qualified URLs.

    +

    Creating an endpoint for the highlighted snippets

    +

    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
    +from rest_framework.response import Response
    +
    +class SnippetHighlight(generics.GenericAPIView):
    +    queryset = Snippet.objects.all()
    +    renderer_classes = (renderers.StaticHTMLRenderer,)
    +
    +    def get(self, request, *args, **kwargs):
    +        snippet = self.get_object()
    +        return Response(snippet.highlighted)
    +
    +

    As usual we need to add the new views that we've created in to our URLconf. +We'll add a url pattern for our new API root in snippets/urls.py:

    +
    url(r'^$', 'api_root'),
    +
    +

    And then add a url pattern for the snippet highlights:

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

    Hyperlinking our API

    +

    Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:

    +
      +
    • Using primary keys.
    • +
    • Using hyperlinking between entities.
    • +
    • Using a unique identifying slug field on the related entity.
    • +
    • Using the default string representation of the related entity.
    • +
    • Nesting the related entity inside the parent representation.
    • +
    • Some other custom representation.
    • +
    +

    REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.

    +

    In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer instead of the existing ModelSerializer.

    +

    The HyperlinkedModelSerializer has the following differences from ModelSerializer:

    +
      +
    • It does not include the pk field by default.
    • +
    • It includes a url field, using HyperlinkedIdentityField.
    • +
    • Relationships use HyperlinkedRelatedField, + instead of PrimaryKeyRelatedField.
    • +
    +

    We can easily re-write our existing serializers to use hyperlinking. In your snippets/serializers.py add:

    +
    class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    +    owner = serializers.Field(source='owner.username')
    +    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
    +
    +    class Meta:
    +        model = Snippet
    +        fields = ('url', 'highlight', 'owner',
    +                  'title', 'code', 'linenos', 'language', 'style')
    +
    +
    +class UserSerializer(serializers.HyperlinkedModelSerializer):
    +    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
    +
    +    class Meta:
    +        model = User
    +        fields = ('url', 'username', 'snippets')
    +
    +

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

    +

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

    +

    Making sure our URL patterns are named

    +

    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 something like this:

    +
    # API endpoints
    +urlpatterns = format_suffix_patterns([
    +    url(r'^$', views.api_root),
    +    url(r'^snippets/$',
    +        views.SnippetList.as_view(),
    +        name='snippet-list'),
    +    url(r'^snippets/(?P<pk>[0-9]+)/$',
    +        views.SnippetDetail.as_view(),
    +        name='snippet-detail'),
    +    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
    +        views.SnippetHighlight.as_view(),
    +        name='snippet-highlight'),
    +    url(r'^users/$',
    +        views.UserList.as_view(),
    +        name='user-list'),
    +    url(r'^users/(?P<pk>[0-9]+)/$',
    +        views.UserDetail.as_view(),
    +        name='user-detail')
    +])
    +
    +# Login and logout views for the browsable API
    +urlpatterns += [
    +    url(r'^api-auth/', include('rest_framework.urls',
    +                               namespace='rest_framework')),
    +]
    +
    +

    Adding pagination

    +

    The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.

    +

    We can change the default list style to use pagination, by modifying our settings.py file slightly. Add the following setting:

    +
    REST_FRAMEWORK = {
    +    'PAGINATE_BY': 10
    +}
    +
    +

    Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.

    +

    We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.

    +

    Browsing the API

    +

    If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.

    +

    You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.

    +

    In part 6 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.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/6-viewsets-and-routers.html b/tutorial/6-viewsets-and-routers.html deleted file mode 100644 index da4c63834..000000000 --- a/tutorial/6-viewsets-and-routers.html +++ /dev/null @@ -1,361 +0,0 @@ - - - - - Tutorial 6: ViewSets & Routers - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Tutorial 6: ViewSets & Routers

    -

    REST framework includes an abstraction for dealing with ViewSets, 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.

    -

    ViewSet classes are almost the same thing as View classes, except that they provide operations such as read, or update, and not method handlers such as get or put.

    -

    A ViewSet 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 Router class which handles the complexities of defining the URL conf for you.

    -

    Refactoring to use ViewSets

    -

    Let's take our current set of views, and refactor them into view sets.

    -

    First of all let's refactor our UserList and UserDetail views into a single UserViewSet. We can remove the two views, and replace them with a single class:

    -
    from rest_framework import viewsets
    -
    -class UserViewSet(viewsets.ReadOnlyModelViewSet):
    -    """
    -    This viewset automatically provides `list` and `detail` actions.
    -    """
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -

    Here we've used the ReadOnlyModelViewSet class to automatically provide the default 'read-only' operations. We're still setting the queryset and serializer_class 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.

    -

    Next we're going to replace the SnippetList, SnippetDetail and SnippetHighlight view classes. We can remove the three views, and again replace them with a single class.

    -
    from rest_framework.decorators import detail_route
    -
    -class SnippetViewSet(viewsets.ModelViewSet):
    -    """
    -    This viewset automatically provides `list`, `create`, `retrieve`,
    -    `update` and `destroy` actions.
    -
    -    Additionally we also provide an extra `highlight` action.
    -    """
    -    queryset = Snippet.objects.all()
    -    serializer_class = SnippetSerializer
    -    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
    -                          IsOwnerOrReadOnly,)
    -
    -    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    -    def highlight(self, request, *args, **kwargs):
    -        snippet = self.get_object()
    -        return Response(snippet.highlighted)
    -
    -    def pre_save(self, obj):
    -        obj.owner = self.request.user
    -
    -

    This time we've used the ModelViewSet class in order to get the complete set of default read and write operations.

    -

    Notice that we've also used the @detail_route decorator to create a custom action, named highlight. This decorator can be used to add any custom endpoints that don't fit into the standard create/update/delete style.

    -

    Custom actions which use the @detail_route decorator will respond to GET requests. We can use the methods argument if we wanted an action that responded to POST requests.

    -

    Binding ViewSets to URLs explicitly

    -

    The handler methods only get bound to the actions when we define the URLConf. -To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.

    -

    In the urls.py file we bind our ViewSet classes into a set of concrete views.

    -
    from snippets.views import SnippetViewSet, UserViewSet
    -from rest_framework import renderers
    -
    -snippet_list = SnippetViewSet.as_view({
    -    'get': 'list',
    -    'post': 'create'
    -})
    -snippet_detail = SnippetViewSet.as_view({
    -    'get': 'retrieve',
    -    'put': 'update',
    -    'patch': 'partial_update',
    -    'delete': 'destroy'
    -})
    -snippet_highlight = SnippetViewSet.as_view({
    -    'get': 'highlight'
    -}, renderer_classes=[renderers.StaticHTMLRenderer])
    -user_list = UserViewSet.as_view({
    -    'get': 'list'
    -})
    -user_detail = UserViewSet.as_view({
    -    'get': 'retrieve'
    -})
    -
    -

    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([
    -    url(r'^$', api_root),
    -    url(r'^snippets/$', snippet_list, name='snippet-list'),
    -    url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
    -    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
    -    url(r'^users/$', user_list, name='user-list'),
    -    url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
    -])
    -
    -

    Using Routers

    -

    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 urls.py file.

    -
    from django.conf.urls import url, include
    -from snippets import views
    -from rest_framework.routers import DefaultRouter
    -
    -# Create a router and register our viewsets with it.
    -router = DefaultRouter()
    -router.register(r'snippets', views.SnippetViewSet)
    -router.register(r'users', views.UserViewSet)
    -
    -# The API URLs are now determined automatically by the router.
    -# Additionally, we include the login URLs for the browseable API.
    -urlpatterns = [
    -    url(r'^', include(router.urls)),
    -    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    -]
    -
    -

    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.

    -

    Trade-offs between views vs viewsets

    -

    Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.

    -

    That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.

    -

    Reviewing our work

    -

    With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.

    -

    We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.

    -

    You can review the final tutorial code on GitHub, or try out a live example in the sandbox.

    -

    Onwards and upwards

    -

    We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:

    - -

    Now go build awesome things.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html new file mode 100644 index 000000000..d299743f9 --- /dev/null +++ b/tutorial/6-viewsets-and-routers/index.html @@ -0,0 +1,550 @@ + + + + + + + 6- Viewsets and routers - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + + + +
    + + +

    Tutorial 6: ViewSets & Routers

    +

    REST framework includes an abstraction for dealing with ViewSets, 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.

    +

    ViewSet classes are almost the same thing as View classes, except that they provide operations such as read, or update, and not method handlers such as get or put.

    +

    A ViewSet 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 Router class which handles the complexities of defining the URL conf for you.

    +

    Refactoring to use ViewSets

    +

    Let's take our current set of views, and refactor them into view sets.

    +

    First of all let's refactor our UserList and UserDetail views into a single UserViewSet. We can remove the two views, and replace them with a single class:

    +
    from rest_framework import viewsets
    +
    +class UserViewSet(viewsets.ReadOnlyModelViewSet):
    +    """
    +    This viewset automatically provides `list` and `detail` actions.
    +    """
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +
    +

    Here we've used the ReadOnlyModelViewSet class to automatically provide the default 'read-only' operations. We're still setting the queryset and serializer_class 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.

    +

    Next we're going to replace the SnippetList, SnippetDetail and SnippetHighlight view classes. We can remove the three views, and again replace them with a single class.

    +
    from rest_framework.decorators import detail_route
    +
    +class SnippetViewSet(viewsets.ModelViewSet):
    +    """
    +    This viewset automatically provides `list`, `create`, `retrieve`,
    +    `update` and `destroy` actions.
    +
    +    Additionally we also provide an extra `highlight` action.
    +    """
    +    queryset = Snippet.objects.all()
    +    serializer_class = SnippetSerializer
    +    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
    +                          IsOwnerOrReadOnly,)
    +
    +    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    +    def highlight(self, request, *args, **kwargs):
    +        snippet = self.get_object()
    +        return Response(snippet.highlighted)
    +
    +    def pre_save(self, obj):
    +        obj.owner = self.request.user
    +
    +

    This time we've used the ModelViewSet class in order to get the complete set of default read and write operations.

    +

    Notice that we've also used the @detail_route decorator to create a custom action, named highlight. This decorator can be used to add any custom endpoints that don't fit into the standard create/update/delete style.

    +

    Custom actions which use the @detail_route decorator will respond to GET requests. We can use the methods argument if we wanted an action that responded to POST requests.

    +

    Binding ViewSets to URLs explicitly

    +

    The handler methods only get bound to the actions when we define the URLConf. +To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.

    +

    In the urls.py file we bind our ViewSet classes into a set of concrete views.

    +
    from snippets.views import SnippetViewSet, UserViewSet, api_root
    +from rest_framework import renderers
    +
    +snippet_list = SnippetViewSet.as_view({
    +    'get': 'list',
    +    'post': 'create'
    +})
    +snippet_detail = SnippetViewSet.as_view({
    +    'get': 'retrieve',
    +    'put': 'update',
    +    'patch': 'partial_update',
    +    'delete': 'destroy'
    +})
    +snippet_highlight = SnippetViewSet.as_view({
    +    'get': 'highlight'
    +}, renderer_classes=[renderers.StaticHTMLRenderer])
    +user_list = UserViewSet.as_view({
    +    'get': 'list'
    +})
    +user_detail = UserViewSet.as_view({
    +    'get': 'retrieve'
    +})
    +
    +

    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([
    +    url(r'^$', api_root),
    +    url(r'^snippets/$', snippet_list, name='snippet-list'),
    +    url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
    +    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
    +    url(r'^users/$', user_list, name='user-list'),
    +    url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
    +])
    +
    +

    Using Routers

    +

    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 urls.py file.

    +
    from django.conf.urls import url, include
    +from snippets import views
    +from rest_framework.routers import DefaultRouter
    +
    +# Create a router and register our viewsets with it.
    +router = DefaultRouter()
    +router.register(r'snippets', views.SnippetViewSet)
    +router.register(r'users', views.UserViewSet)
    +
    +# The API URLs are now determined automatically by the router.
    +# Additionally, we include the login URLs for the browseable API.
    +urlpatterns = [
    +    url(r'^', include(router.urls)),
    +    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    +]
    +
    +

    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.

    +

    Trade-offs between views vs viewsets

    +

    Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.

    +

    That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.

    +

    Reviewing our work

    +

    With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.

    +

    We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.

    +

    You can review the final tutorial code on GitHub, or try out a live example in the sandbox.

    +

    Onwards and upwards

    +

    We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:

    + +

    Now go build awesome things.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tutorial/quickstart.html b/tutorial/quickstart.html deleted file mode 100644 index 07d38da84..000000000 --- a/tutorial/quickstart.html +++ /dev/null @@ -1,380 +0,0 @@ - - - - - Quickstart - Django REST framework - - - - - - - - - - - - - - - - - - - - -
    - - - -
    -
    - - - - -
    - - - -
    -

    Quickstart

    -

    We're going to create a simple API to allow admin users to view and edit the users and groups in the system.

    -

    Project setup

    -

    Create a new Django project named tutorial, then start a new app called quickstart.

    -
    # Create the project directory
    -mkdir tutorial
    -cd tutorial
    -
    -# Create a virtualenv to isolate our package dependencies locally
    -virtualenv env
    -source env/bin/activate  # On Windows use `env\Scripts\activate`
    -
    -# Install Django and Django REST framework into the virtualenv
    -pip install django
    -pip install djangorestframework
    -
    -# Set up a new project with a single application
    -django-admin.py startproject tutorial .
    -cd tutorial
    -django-admin.py startapp quickstart
    -cd ..
    -
    -

    Now sync your database for the first time:

    -
    python manage.py syncdb
    -
    -

    Make sure to create an initial user named admin with a password of password. We'll authenticate as that user later in our example.

    -

    Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...

    -

    Serializers

    -

    First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py that we'll use for our data representations.

    -
    from django.contrib.auth.models import User, Group
    -from rest_framework import serializers
    -
    -
    -class UserSerializer(serializers.HyperlinkedModelSerializer):
    -    class Meta:
    -        model = User
    -        fields = ('url', 'username', 'email', 'groups')
    -
    -
    -class GroupSerializer(serializers.HyperlinkedModelSerializer):
    -    class Meta:
    -        model = Group
    -        fields = ('url', 'name')
    -
    -

    Notice that we're using hyperlinked relations in this case, with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.

    -

    Views

    -

    Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.

    -
    from django.contrib.auth.models import User, Group
    -from rest_framework import viewsets
    -from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
    -
    -
    -class UserViewSet(viewsets.ModelViewSet):
    -    """
    -    API endpoint that allows users to be viewed or edited.
    -    """
    -    queryset = User.objects.all()
    -    serializer_class = UserSerializer
    -
    -
    -class GroupViewSet(viewsets.ModelViewSet):
    -    """
    -    API endpoint that allows groups to be viewed or edited.
    -    """
    -    queryset = Group.objects.all()
    -    serializer_class = GroupSerializer
    -
    -

    Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.

    -

    We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.

    -

    Notice that our viewset classes here are a little different from those in the frontpage example, as they include queryset and serializer_class attributes, instead of a model attribute.

    -

    For trivial cases you can simply set a model attribute on the ViewSet class and the serializer and queryset will be automatically generated for you. Setting the queryset and/or serializer_class attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications.

    -

    URLs

    -

    Okay, now let's wire up the API URLs. On to tutorial/urls.py...

    -
    from django.conf.urls import url, include
    -from rest_framework import routers
    -from tutorial.quickstart import views
    -
    -router = routers.DefaultRouter()
    -router.register(r'users', views.UserViewSet)
    -router.register(r'groups', views.GroupViewSet)
    -
    -# Wire up our API using automatic URL routing.
    -# Additionally, we include login URLs for the browseable API.
    -urlpatterns = [
    -    url(r'^', include(router.urls)),
    -    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    -]
    -
    -

    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.

    -

    Settings

    -

    We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in tutorial/settings.py

    -
    INSTALLED_APPS = (
    -    ...
    -    'rest_framework',
    -)
    -
    -REST_FRAMEWORK = {
    -    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    -    'PAGINATE_BY': 10
    -}
    -
    -

    Okay, we're done.

    -
    -

    Testing our API

    -

    We're now ready to test the API we've built. Let's fire up the server from the command line.

    -
    python ./manage.py runserver
    -
    -

    We can now access our API, both from the command-line, using tools like curl...

    -
    bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
    -{
    -    "count": 2,
    -    "next": null,
    -    "previous": null,
    -    "results": [
    -        {
    -            "email": "admin@example.com",
    -            "groups": [],
    -            "url": "http://127.0.0.1:8000/users/1/",
    -            "username": "admin"
    -        },
    -        {
    -            "email": "tom@example.com",
    -            "groups": [                ],
    -            "url": "http://127.0.0.1:8000/users/2/",
    -            "username": "tom"
    -        }
    -    ]
    -}
    -
    -

    Or directly through the browser...

    -

    Quick start image

    -

    If you're working through the browser, make sure to login using the control in the top right corner.

    -

    Great, that was easy!

    -

    If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

    -
    -
    -
    -
    - -
    -
    - - - - - - - - - - - diff --git a/tutorial/quickstart/index.html b/tutorial/quickstart/index.html new file mode 100644 index 000000000..0aad281b0 --- /dev/null +++ b/tutorial/quickstart/index.html @@ -0,0 +1,571 @@ + + + + + + + Quickstart - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +
    + + + + +
    + +
    + +
    + + +
    +
    + +
    + + +

    Quickstart

    +

    We're going to create a simple API to allow admin users to view and edit the users and groups in the system.

    +

    Project setup

    +

    Create a new Django project named tutorial, then start a new app called quickstart.

    +
    # Create the project directory
    +mkdir tutorial
    +cd tutorial
    +
    +# Create a virtualenv to isolate our package dependencies locally
    +virtualenv env
    +source env/bin/activate  # On Windows use `env\Scripts\activate`
    +
    +# Install Django and Django REST framework into the virtualenv
    +pip install django
    +pip install djangorestframework
    +
    +# Set up a new project with a single application
    +django-admin.py startproject tutorial
    +cd tutorial
    +django-admin.py startapp quickstart
    +cd ..
    +
    +

    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 password. We'll authenticate as that user later in our example.

    +
    python manage.py createsuperuser
    +
    +

    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...

    +

    Serializers

    +

    First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py that we'll use for our data representations.

    +
    from django.contrib.auth.models import User, Group
    +from rest_framework import serializers
    +
    +
    +class UserSerializer(serializers.HyperlinkedModelSerializer):
    +    class Meta:
    +        model = User
    +        fields = ('url', 'username', 'email', 'groups')
    +
    +
    +class GroupSerializer(serializers.HyperlinkedModelSerializer):
    +    class Meta:
    +        model = Group
    +        fields = ('url', 'name')
    +
    +

    Notice that we're using hyperlinked relations in this case, with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.

    +

    Views

    +

    Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.

    +
    from django.contrib.auth.models import User, Group
    +from rest_framework import viewsets
    +from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
    +
    +
    +class UserViewSet(viewsets.ModelViewSet):
    +    """
    +    API endpoint that allows users to be viewed or edited.
    +    """
    +    queryset = User.objects.all()
    +    serializer_class = UserSerializer
    +
    +
    +class GroupViewSet(viewsets.ModelViewSet):
    +    """
    +    API endpoint that allows groups to be viewed or edited.
    +    """
    +    queryset = Group.objects.all()
    +    serializer_class = GroupSerializer
    +
    +

    Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.

    +

    We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.

    +

    Notice that our viewset classes here are a little different from those in the frontpage example, as they include queryset and serializer_class attributes, instead of a model attribute.

    +

    For trivial cases you can simply set a model attribute on the ViewSet class and the serializer and queryset will be automatically generated for you. Setting the queryset and/or serializer_class attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications.

    +

    URLs

    +

    Okay, now let's wire up the API URLs. On to tutorial/urls.py...

    +
    from django.conf.urls import url, include
    +from rest_framework import routers
    +from tutorial.quickstart import views
    +
    +router = routers.DefaultRouter()
    +router.register(r'users', views.UserViewSet)
    +router.register(r'groups', views.GroupViewSet)
    +
    +# Wire up our API using automatic URL routing.
    +# Additionally, we include login URLs for the browseable API.
    +urlpatterns = [
    +    url(r'^', include(router.urls)),
    +    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    +]
    +
    +

    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.

    +

    Settings

    +

    We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in tutorial/settings.py

    +
    INSTALLED_APPS = (
    +    ...
    +    'rest_framework',
    +)
    +
    +REST_FRAMEWORK = {
    +    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    +    'PAGINATE_BY': 10
    +}
    +
    +

    Okay, we're done.

    +
    +

    Testing our API

    +

    We're now ready to test the API we've built. Let's fire up the server from the command line.

    +
    python ./manage.py runserver
    +
    +

    We can now access our API, both from the command-line, using tools like curl...

    +
    bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
    +{
    +    "count": 2,
    +    "next": null,
    +    "previous": null,
    +    "results": [
    +        {
    +            "email": "admin@example.com",
    +            "groups": [],
    +            "url": "http://127.0.0.1:8000/users/1/",
    +            "username": "admin"
    +        },
    +        {
    +            "email": "tom@example.com",
    +            "groups": [                ],
    +            "url": "http://127.0.0.1:8000/users/2/",
    +            "username": "tom"
    +        }
    +    ]
    +}
    +
    +

    Or directly through the browser...

    +

    Quick start image

    +

    If you're working through the browser, make sure to login using the control in the top right corner.

    +

    Great, that was easy!

    +

    If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

    + +
    + +
    + +
    + +
    + +
    +
    + + + + + + + + + + + + + + \ No newline at end of file