diff --git a/404.html b/404.html index c2d6c8238..1402fb9f4 100644 --- a/404.html +++ b/404.html @@ -1,167 +1,475 @@ - + - - - - George Floyd - + + + + Django REST framework + + + + + - + + - @media (min-width: 768px) { - .bd-placeholder-img-lg { - font-size: 3.5rem; - } - } - - - - - -
-
- + + +
+ + + + - --> - -
-

George Floyd

-

Natosha McDade, Yassin Mohamed, Finan H. Berhe, Sean Reed, Steven Demarco Taylor, Breonna Taylor, Ariane McCree, Terrance Franklin, Miles Hall, Darius Tarver, William Green, Samuel David Mallard, Kwame Jones, De’von Bailey, Christopher Whitfield, Anthony Hill, De’Von Bailey, Eric Logan, Jamarion Robinson, Gregory Hill Jr, JaQuavion Slaton, Ryan Twyman, Brandon Webber, Jimmy Atchison, Willie McCoy, Emantic Fitzgerald Bradford J, D’ettrick Griffin, Jemel Roberson, DeAndre Ballard, Botham Shem Jean, Robert Lawrence White, Anthony Lamar Smith, Ramarley Graham, Manuel Loggins Jr, Trayvon Martin, Wendell Allen, Kendrec McDade, Larry Jackson Jr, Jonathan Ferrell, Jordan Baker, Victor White III, Dontre Hamilton, Eric Garner, John Crawford III, Michael Brown, Ezell Ford, Dante Parker, Kajieme Powell, Laquan McDonald, Akai Gurley, Tamir Rice, Rumain Brisbon, Jerame Reid, Charly Keunang, Tony Robinson, Walter Scott, Freddie Gray, Brendon Glenn, Samuel DuBose, Christian Taylor, Jamar Clark, Mario Woods, Quintonio LeGrier, Gregory Gunn, Akiel Denkins, Alton Sterling, Philando Castile, Terrence Sterling, Terence Crutcher, Keith Lamont Scott, Alfred Olango, Jordan Edwards, Stephon Clark, Danny Ray Thomas, DeJuan Guillory, Patrick Harmon, Jonathan Hart, Maurice Granton, Julius Johnson, Jamee Johnson, Michael Dean...

- -
+
+
+ + + +
+
+
+ + +
+
+ +
+ + +

404

+

Page not found

+

Try the homepage, or search the documentation.

+ + + +
+
+
+
+
+ + + - + + + + + + + + + + + + + + + - + + \ No newline at end of file diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html new file mode 100644 index 000000000..08450aee5 --- /dev/null +++ b/api-guide/authentication/index.html @@ -0,0 +1,880 @@ + + + + + + + Authentication - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + 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.

+

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.

+
+

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.

+

If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None.

+

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

+

Setting the authentication scheme

+

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

+
REST_FRAMEWORK = {
+    'DEFAULT_AUTHENTICATION_CLASSES': [
+        'rest_framework.authentication.BasicAuthentication',
+        'rest_framework.authentication.SessionAuthentication',
+    ]
+}
+
+

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.permissions import IsAuthenticated
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+class ExampleView(APIView):
+    authentication_classes = [SessionAuthentication, BasicAuthentication]
+    permission_classes = [IsAuthenticated]
+
+    def get(self, request, format=None):
+        content = {
+            'user': unicode(request.user),  # `django.contrib.auth.User` instance.
+            'auth': unicode(request.auth),  # None
+        }
+        return Response(content)
+
+

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

+
@api_view(['GET'])
+@authentication_classes([SessionAuthentication, BasicAuthentication])
+@permission_classes([IsAuthenticated])
+def example_view(request, format=None):
+    content = {
+        'user': unicode(request.user),  # `django.contrib.auth.User` instance.
+        'auth': unicode(request.auth),  # None
+    }
+    return Response(content)
+
+

Unauthorized and Forbidden responses

+

When an unauthenticated request is denied permission there are two different error codes that may be appropriate.

+ +

HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header.

+

The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response.

+

Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a 403 Permission Denied response will always be used, regardless of the authentication scheme.

+

Apache mod_wsgi specific configuration

+

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

+

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

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

API Reference

+

BasicAuthentication

+

This authentication scheme uses HTTP Basic Authentication, signed against a user's username and password. Basic authentication is generally only appropriate for testing.

+

If successfully authenticated, BasicAuthentication provides the following credentials.

+
    +
  • request.user will be a Django User instance.
  • +
  • request.auth will be None.
  • +
+

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

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

Note: If you use BasicAuthentication in production you must ensure that your API is only available over https. 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 = [
+    ...
+    'rest_framework.authtoken'
+]
+
+
+

Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations.

+
+

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

+
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
+
+

Note: If you want to use a different keyword in the header, such as Bearer, simply subclass TokenAuthentication and set the keyword class variable.

+

If successfully authenticated, TokenAuthentication provides the following credentials.

+
    +
  • request.user will be a Django User instance.
  • +
  • request.auth will be a rest_framework.authtoken.models.Token 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
+
+

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'
+
+
+

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

+
+

Generating Tokens

+
By using signals
+

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.db.models.signals import post_save
+from django.dispatch import receiver
+from rest_framework.authtoken.models import Token
+
+@receiver(post_save, sender=settings.AUTH_USER_MODEL)
+def create_auth_token(sender, instance=None, created=False, **kwargs):
+    if created:
+        Token.objects.create(user=instance)
+
+

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 rest_framework.authtoken.models import Token
+
+for user in User.objects.all():
+    Token.objects.get_or_create(user=user)
+
+
By exposing an api endpoint
+

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
+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' }
+
+

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.

+

By default there are no permissions or throttling applied to the obtain_auth_token view. If you do wish to apply throttling you'll need to override the view class, +and include them using the throttle_classes attribute.

+

If you need a customized version of the obtain_auth_token view, you can do so by subclassing the ObtainAuthToken view class, and using that in your url conf instead.

+

For example, you may return additional user information beyond the token value:

+
from rest_framework.authtoken.views import ObtainAuthToken
+from rest_framework.authtoken.models import Token
+from rest_framework.response import Response
+
+class CustomAuthToken(ObtainAuthToken):
+
+    def post(self, request, *args, **kwargs):
+        serializer = self.serializer_class(data=request.data,
+                                           context={'request': request})
+        serializer.is_valid(raise_exception=True)
+        user = serializer.validated_data['user']
+        token, created = Token.objects.get_or_create(user=user)
+        return Response({
+            'token': token.key,
+            'user_id': user.pk,
+            'email': user.email
+        })
+
+

And in your urls.py:

+
urlpatterns += [
+    url(r'^api-token-auth/', CustomAuthToken.as_view())
+]
+
+
With Django admin
+

It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the TokenAdmin class to customize it to your needs, more specifically by declaring the user field as raw_field.

+

your_app/admin.py:

+
from rest_framework.authtoken.admin import TokenAdmin
+
+TokenAdmin.raw_id_fields = ['user']
+
+

Using Django manage.py command

+

Since version 3.6.4 it's possible to generate a user token using the following command:

+
./manage.py drf_create_token <username>
+
+

this command will return the API token for the given user, creating it if it doesn't exist:

+
Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1
+
+

In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:

+
./manage.py drf_create_token -r <username>
+
+

SessionAuthentication

+

This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.

+

If successfully authenticated, SessionAuthentication provides the following credentials.

+
    +
  • request.user will be a Django User instance.
  • +
  • request.auth will be None.
  • +
+

Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response.

+

If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as PUT, PATCH, POST or DELETE requests. See the Django CSRF documentation for more details.

+

Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.

+

CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.

+

RemoteUserAuthentication

+

This authentication scheme allows you to delegate authentication to your web server, which sets the REMOTE_USER +environment variable.

+

To use it, you must have django.contrib.auth.backends.RemoteUserBackend (or a subclass) in your +AUTHENTICATION_BACKENDS setting. By default, RemoteUserBackend creates User objects for usernames that don't +already exist. To change this and other behaviour, consult the +Django documentation.

+

If successfully authenticated, RemoteUserAuthentication provides the following credentials:

+
    +
  • request.user will be a Django User instance.
  • +
  • request.auth will be None.
  • +
+

Consult your web server's documentation for information about configuring an authentication method, e.g.:

+ +

Custom authentication

+

To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

+

In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.

+

Typically the approach you should take is:

+
    +
  • If authentication is not attempted, return None. Any other authentication schemes also in use will still be checked.
  • +
  • If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
  • +
+

You may also override the .authenticate_header(self, request) method. If implemented, it should return a string that will be used as the value of the WWW-Authenticate header in a HTTP 401 Unauthorized response.

+

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

+
+

Note: When your custom authenticator is invoked by the request object's .user or .auth properties, you may see an AttributeError re-raised as a WrappedAttributeError. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from your custom authenticator and will instead assume that the request object does not have a .user or .auth property. These errors should be fixed or otherwise handled by your authenticator.

+
+

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 rest_framework import authentication
+from rest_framework import exceptions
+
+class ExampleAuthentication(authentication.BaseAuthentication):
+    def authenticate(self, request):
+        username = request.META.get('HTTP_X_USERNAME')
+        if not username:
+            return None
+
+        try:
+            user = User.objects.get(username=username)
+        except User.DoesNotExist:
+            raise exceptions.AuthenticationFailed('No such user')
+
+        return (user, None)
+
+
+

Third party packages

+

The following third party packages are also available.

+

Django OAuth Toolkit

+

The Django OAuth Toolkit package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by Evonove and uses the excellent OAuthLib. The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support.

+

Installation & configuration

+

Install using pip.

+
pip install django-oauth-toolkit
+
+

Add the package to your INSTALLED_APPS and modify your REST framework settings.

+
INSTALLED_APPS = [
+    ...
+    'oauth2_provider',
+]
+
+REST_FRAMEWORK = {
+    'DEFAULT_AUTHENTICATION_CLASSES': [
+        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
+    ]
+}
+
+

For more details see the Django REST framework - Getting started documentation.

+

Django REST framework OAuth

+

The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework.

+

This package was previously included directly in REST framework but is now supported and maintained as a third party package.

+

Installation & configuration

+

Install the package using pip.

+
pip install djangorestframework-oauth
+
+

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

+

JSON Web Token Authentication

+

JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app.

+

Hawk HTTP Authentication

+

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

+

HTTP Signature Authentication

+

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

+

Djoser

+

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

+

django-rest-auth

+

Django-rest-auth library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.

+

django-rest-framework-social-oauth2

+

Django-rest-framework-social-oauth2 library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.

+

django-rest-knox

+

Django-rest-knox library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).

+

drfpasswordless

+

drfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/caching/index.html b/api-guide/caching/index.html new file mode 100644 index 000000000..107c6d099 --- /dev/null +++ b/api-guide/caching/index.html @@ -0,0 +1,531 @@ + + + + + + + Caching - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Caching

+
+

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

+
+

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

+
+

Using cache with apiview and viewsets

+

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

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

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

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html new file mode 100644 index 000000000..f4964e7d5 --- /dev/null +++ b/api-guide/content-negotiation/index.html @@ -0,0 +1,574 @@ + + + + + + + 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/index.html b/api-guide/exceptions/index.html new file mode 100644 index 000000000..fff502414 --- /dev/null +++ b/api-guide/exceptions/index.html @@ -0,0 +1,732 @@ + + + + + + + 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.

+

Most error responses will include a key detail in the body of the response.

+

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."}
+
+

Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting.

+

Any example validation error might look like this:

+
HTTP/1.1 400 Bad Request
+Content-Type: application/json
+Content-Length: 94
+
+{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
+
+

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 pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a 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, context):
+    # Call REST framework's default exception handler first,
+    # to get the standard error response.
+    response = exception_handler(exc, context)
+
+    # Now add the HTTP status code to the response.
+    if response is not None:
+        response.data['status_code'] = response.status_code
+
+    return response
+
+

The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'].

+

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, .default_detail, and default_code attributes on the class.

+

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

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

Inspecting API exceptions

+

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

+

The available attributes and methods are:

+
    +
  • .detail - Return the textual description of the error.
  • +
  • .get_codes() - Return the code identifier of the error.
  • +
  • .get_full_details() - Return both the textual description and the code identifier.
  • +
+

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

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

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

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

ParseError

+

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

+

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

+

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

+

AuthenticationFailed

+

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

+

Raised when an incoming request includes incorrect authentication.

+

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

+

NotAuthenticated

+

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

+

Raised when an unauthenticated request fails the permission checks.

+

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

+

PermissionDenied

+

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

+

Raised when an authenticated request fails the permission checks.

+

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

+

NotFound

+

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

+

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

+

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

+

MethodNotAllowed

+

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

+

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

+

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

+

NotAcceptable

+

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

+

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

+

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

+

UnsupportedMediaType

+

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

+

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

+

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

+

Throttled

+

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

+

Raised when an incoming request fails the throttling checks.

+

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

+

ValidationError

+

Signature: ValidationError(detail, code=None)

+

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

+
    +
  • The detail argument is mandatory, not optional.
  • +
  • The detail argument may be a list or dictionary of error details, and may also be a nested data structure.
  • +
  • By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.')
  • +
+

The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:

+
serializer.is_valid(raise_exception=True)
+
+

The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.

+

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

+
+

Generic Error Views

+

Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and +400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an +API-only application.)

+

Use these as per Django's Customizing error views documentation.

+

rest_framework.exceptions.server_error

+

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

+

Set as handler500:

+
handler500 = 'rest_framework.exceptions.server_error'
+
+

rest_framework.exceptions.bad_request

+

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

+

Set as handler400:

+
handler400 = 'rest_framework.exceptions.bad_request'
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html new file mode 100644 index 000000000..f1902114f --- /dev/null +++ b/api-guide/fields/index.html @@ -0,0 +1,1310 @@ + + + + + + + Serializer fields - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + 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

+
+

Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.

+
+

Note: The serializer fields are declared in fields.py, but by convention you should import them using from rest_framework import serializers and refer to fields as serializers.<FieldName>.

+
+

Core arguments

+

Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:

+

read_only

+

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

+

Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

+

Defaults to False

+

write_only

+

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

+

Defaults to False

+

required

+

Normally an error will be raised if a field is not supplied during deserialization. +Set to false if this field is not required to be present during deserialization.

+

Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.

+

Defaults to True.

+

default

+

If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.

+

The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.

+

May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument.

+

For example:

+
class CurrentUserDefault:
+    """
+    May be applied as a `default=...` value on a serializer field.
+    Returns the current user.
+    """
+    requires_context = True
+
+    def __call__(self, serializer_field):
+        return serializer_field.context['request'].user
+
+

When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance.

+

Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.

+

allow_null

+

Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.

+

Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization.

+

Defaults to False

+

source

+

The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal.

+

The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.

+

Defaults to the name of the field.

+

validators

+

A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.

+

error_messages

+

A dictionary of error codes to error messages.

+

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

+

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

+

initial

+

A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as +you may do with any regular Django Field:

+
import datetime
+from rest_framework import serializers
+class ExampleSerializer(serializers.Serializer):
+    day = serializers.DateField(initial=datetime.date.today)
+
+

style

+

A dictionary of key-value pairs that can be used to control how renderers should render the field.

+

Two examples here are 'input_type' and 'base_template':

+
# Use <input type="password"> for the input.
+password = serializers.CharField(
+    style={'input_type': 'password'}
+)
+
+# Use a radio input instead of a select input.
+color_channel = serializers.ChoiceField(
+    choices=['red', 'green', 'blue'],
+    style={'base_template': 'radio.html'}
+)
+
+

For more details see the HTML & Forms documentation.

+
+

Boolean fields

+

BooleanField

+

A boolean representation.

+

When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False, even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.

+

Note that Django 2.1 removed the blank kwarg from models.BooleanField. +Prior to Django 2.1 models.BooleanField fields were always blank=True. Thus +since Django 2.1 default serializers.BooleanField instances will be generated +without the required kwarg (i.e. equivalent to required=True) whereas with +previous versions of Django, default BooleanField instances will be generated +with a required=False option. If you want to control this behaviour manually, +explicitly declare the BooleanField on the serializer class, or use the +extra_kwargs option to set the required flag.

+

Corresponds to django.db.models.fields.BooleanField.

+

Signature: BooleanField()

+

NullBooleanField

+

A boolean representation that also accepts None as a valid value.

+

Corresponds to django.db.models.fields.NullBooleanField.

+

Signature: NullBooleanField()

+
+

String fields

+

CharField

+

A text representation. Optionally validates the text to be shorter than max_length and longer than min_length.

+

Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField.

+

Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)

+
    +
  • max_length - Validates that the input contains no more than this number of characters.
  • +
  • min_length - Validates that the input contains no fewer than this number of characters.
  • +
  • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • +
  • trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True.
  • +
+

The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.

+

EmailField

+

A text representation, validates the text to be a valid e-mail address.

+

Corresponds to django.db.models.fields.EmailField

+

Signature: EmailField(max_length=None, min_length=None, allow_blank=False)

+

RegexField

+

A text representation, that validates the given value matches against a certain regular expression.

+

Corresponds to django.forms.fields.RegexField.

+

Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False)

+

The mandatory regex argument may either be a string, or a compiled python regular expression object.

+

Uses Django's django.core.validators.RegexValidator for validation.

+

SlugField

+

A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.

+

Corresponds to django.db.models.fields.SlugField.

+

Signature: SlugField(max_length=50, min_length=None, allow_blank=False)

+

URLField

+

A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>.

+

Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation.

+

Signature: URLField(max_length=200, min_length=None, allow_blank=False)

+

UUIDField

+

A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example:

+
"de305d54-75b4-431b-adb2-eb6b9e546013"
+
+

Signature: UUIDField(format='hex_verbose')

+
    +
  • format: Determines the representation format of the uuid value
      +
    • 'hex_verbose' - The canonical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
    • +
    • 'hex' - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a"
    • +
    • 'int' - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114"
    • +
    • 'urn' - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" + Changing the format parameters only affects representation values. All formats are accepted by to_internal_value
    • +
    +
  • +
+

FilePathField

+

A field whose choices are limited to the filenames in a certain directory on the filesystem

+

Corresponds to django.forms.fields.FilePathField.

+

Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)

+
    +
  • path - The absolute filesystem path to a directory from which this FilePathField should get its choice.
  • +
  • match - A regular expression, as a string, that FilePathField will use to filter filenames.
  • +
  • recursive - Specifies whether all subdirectories of path should be included. Default is False.
  • +
  • allow_files - Specifies whether files in the specified location should be included. Default is True. Either this or allow_folders must be True.
  • +
  • allow_folders - Specifies whether folders in the specified location should be included. Default is False. Either this or allow_files must be True.
  • +
+

IPAddressField

+

A field that ensures the input is a valid IPv4 or IPv6 string.

+

Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField.

+

Signature: IPAddressField(protocol='both', unpack_ipv4=False, **options)

+
    +
  • protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
  • +
  • unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
  • +
+
+

Numeric fields

+

IntegerField

+

An integer representation.

+

Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField.

+

Signature: IntegerField(max_value=None, min_value=None)

+
    +
  • max_value Validate that the number provided is no greater than this value.
  • +
  • min_value Validate that the number provided is no less than this value.
  • +
+

FloatField

+

A floating point representation.

+

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

+

Signature: FloatField(max_value=None, min_value=None)

+
    +
  • max_value Validate that the number provided is no greater than this value.
  • +
  • min_value Validate that the number provided is no less than this value.
  • +
+

DecimalField

+

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

+

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

+

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

+
    +
  • max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
  • +
  • decimal_places The number of decimal places to store with the number.
  • +
  • coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True.
  • +
  • max_value Validate that the number provided is no greater than this value.
  • +
  • min_value Validate that the number provided is no less than this value.
  • +
  • localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file.
  • +
  • rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes. Defaults to None.
  • +
+

Example usage

+

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.

+
+

Date and time fields

+

DateTimeField

+

A date and time representation.

+

Corresponds to django.db.models.fields.DateTimeField.

+

Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)

+
    +
  • format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
  • +
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
  • +
  • default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.
  • +
+

DateTimeField format strings.

+

Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')

+

When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.

+

auto_now and auto_now_add model fields.

+

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

+

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

+
class CommentSerializer(serializers.ModelSerializer):
+    created = serializers.DateTimeField()
+
+    class Meta:
+        model = Comment
+
+

DateField

+

A date representation.

+

Corresponds to django.db.models.fields.DateField

+

Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None)

+
    +
  • format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
  • +
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
  • +
+

DateField format strings

+

Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')

+

TimeField

+

A time representation.

+

Corresponds to django.db.models.fields.TimeField

+

Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None)

+
    +
  • format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
  • +
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
  • +
+

TimeField format strings

+

Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')

+

DurationField

+

A Duration representation. +Corresponds to django.db.models.fields.DurationField

+

The validated_data for these fields will contain a datetime.timedelta instance. +The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'.

+

Signature: DurationField(max_value=None, min_value=None)

+
    +
  • max_value Validate that the duration provided is no greater than this value.
  • +
  • min_value Validate that the duration provided is no less than this value.
  • +
+
+

Choice selection fields

+

ChoiceField

+

A field that can accept a value out of a limited set of choices.

+

Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument.

+

Signature: ChoiceField(choices)

+
    +
  • choices - A list of valid values, or a list of (key, display_name) tuples.
  • +
  • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • +
  • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
  • +
  • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
  • +
+

Both the allow_blank and allow_null are valid options on ChoiceField, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices.

+

MultipleChoiceField

+

A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values.

+

Signature: MultipleChoiceField(choices)

+
    +
  • choices - A list of valid values, or a list of (key, display_name) tuples.
  • +
  • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • +
  • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
  • +
  • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
  • +
+

As with ChoiceField, both the allow_blank and allow_null options are valid, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices.

+
+

File upload fields

+

Parsers and file uploads.

+

The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser. Most parsers, such as e.g. JSON don't support file uploads. +Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.

+

FileField

+

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

+

Corresponds to django.forms.fields.FileField.

+

Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

+
    +
  • max_length - Designates the maximum length for the file name.
  • +
  • allow_empty_file - Designates if empty files are allowed.
  • +
  • use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
  • +
+

ImageField

+

An image representation. Validates the uploaded file content as matching a known image format.

+

Corresponds to django.forms.fields.ImageField.

+

Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

+
    +
  • max_length - Designates the maximum length for the file name.
  • +
  • allow_empty_file - Designates if empty files are allowed.
  • +
  • use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
  • +
+

Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained.

+
+

Composite fields

+

ListField

+

A field class that validates a list of objects.

+

Signature: ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)

+
    +
  • child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
  • +
  • allow_empty - Designates if empty lists are allowed.
  • +
  • min_length - Validates that the list contains no fewer than this number of elements.
  • +
  • max_length - Validates that the list contains no more than this number of elements.
  • +
+

For example, to validate a list of integers you might use something like the following:

+
scores = serializers.ListField(
+   child=serializers.IntegerField(min_value=0, max_value=100)
+)
+
+

The ListField class also supports a declarative style that allows you to write reusable list field classes.

+
class StringListField(serializers.ListField):
+    child = serializers.CharField()
+
+

We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.

+

DictField

+

A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values.

+

Signature: DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)

+
    +
  • child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
  • +
  • allow_empty - Designates if empty dictionaries are allowed.
  • +
+

For example, to create a field that validates a mapping of strings to strings, you would write something like this:

+
document = DictField(child=CharField())
+
+

You can also use the declarative style, as with ListField. For example:

+
class DocumentField(DictField):
+    child = CharField()
+
+

HStoreField

+

A preconfigured DictField that is compatible with Django's postgres HStoreField.

+

Signature: HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)

+
    +
  • child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
  • +
  • allow_empty - Designates if empty dictionaries are allowed.
  • +
+

Note that the child field must be an instance of CharField, as the hstore extension stores values as strings.

+

JSONField

+

A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.

+

Signature: JSONField(binary, encoder)

+
    +
  • binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False.
  • +
  • encoder - Use this JSON encoder to serialize input object. Defaults to None.
  • +
+
+

Miscellaneous fields

+

ReadOnlyField

+

A field class that simply returns the value of the field without modification.

+

This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field.

+

Signature: ReadOnlyField()

+

For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField:

+
class AccountSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Account
+        fields = ['id', 'account_name', 'has_expired']
+
+

HiddenField

+

A field class that does not take a value based on user input, but instead takes its value from a default value or callable.

+

Signature: HiddenField()

+

For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:

+
modified = serializers.HiddenField(default=timezone.now)
+
+

The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.

+

For further examples on HiddenField see the validators documentation.

+

ModelField

+

A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.

+

This field is used by ModelSerializer to correspond to custom model field classes.

+

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

+

The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))

+

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.

+

Signature: SerializerMethodField(method_name=None)

+
    +
  • method_name - The name of the method on the serializer to be called. If not included this defaults to get_<field_name>.
  • +
+

The serializer method referred to by the method_name argument 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.utils.timezone import now
+from rest_framework import serializers
+
+class UserSerializer(serializers.ModelSerializer):
+    days_since_joined = serializers.SerializerMethodField()
+
+    class Meta:
+        model = User
+
+    def get_days_since_joined(self, obj):
+        return (now() - obj.date_joined).days
+
+
+

Custom fields

+

If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.

+

The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype.

+

The to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid.

+

Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.

+

Examples

+

A Basic Custom Field

+

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

+
class Color(object):
+    """
+    A color represented in the RGB colorspace.
+    """
+    def __init__(self, red, green, blue):
+        assert(red >= 0 and green >= 0 and blue >= 0)
+        assert(red < 256 and green < 256 and blue < 256)
+        self.red, self.green, self.blue = red, green, blue
+
+class ColorField(serializers.Field):
+    """
+    Color objects are serialized into 'rgb(#, #, #)' notation.
+    """
+    def to_representation(self, value):
+        return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
+
+    def to_internal_value(self, data):
+        data = data.strip('rgb(').rstrip(')')
+        red, green, blue = [int(col) for col in data.split(',')]
+        return Color(red, green, blue)
+
+

By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value().

+

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

+
class ClassNameField(serializers.Field):
+    def get_attribute(self, instance):
+        # We pass the object instance onto `to_representation`,
+        # not just the field attribute.
+        return instance
+
+    def to_representation(self, value):
+        """
+        Serialize the value's class name.
+        """
+        return value.__class__.__name__
+
+

Raising validation errors

+

Our ColorField class above currently does not perform any data validation. +To indicate invalid data, we should raise a serializers.ValidationError, like so:

+
def to_internal_value(self, data):
+    if not isinstance(data, str):
+        msg = 'Incorrect type. Expected a string, but got %s'
+        raise ValidationError(msg % type(data).__name__)
+
+    if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
+        raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')
+
+    data = data.strip('rgb(').rstrip(')')
+    red, green, blue = [int(col) for col in data.split(',')]
+
+    if any([col > 255 or col < 0 for col in (red, green, blue)]):
+        raise ValidationError('Value out of range. Must be between 0 and 255.')
+
+    return Color(red, green, blue)
+
+

The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example:

+
default_error_messages = {
+    'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
+    'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',
+    'out_of_range': 'Value out of range. Must be between 0 and 255.'
+}
+
+def to_internal_value(self, data):
+    if not isinstance(data, str):
+        self.fail('incorrect_type', input_type=type(data).__name__)
+
+    if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
+        self.fail('incorrect_format')
+
+    data = data.strip('rgb(').rstrip(')')
+    red, green, blue = [int(col) for col in data.split(',')]
+
+    if any([col > 255 or col < 0 for col in (red, green, blue)]):
+        self.fail('out_of_range')
+
+    return Color(red, green, blue)
+
+

This style keeps your error messages cleaner and more separated from your code, and should be preferred.

+

Using source='*'

+

Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes.

+
class DataPoint(models.Model):
+    label = models.CharField(max_length=50)
+    x_coordinate = models.SmallIntegerField()
+    y_coordinate = models.SmallIntegerField()
+
+

Using a custom field and source='*' we can provide a nested representation of +the coordinate pair:

+
class CoordinateField(serializers.Field):
+
+    def to_representation(self, value):
+        ret = {
+            "x": value.x_coordinate,
+            "y": value.y_coordinate
+        }
+        return ret
+
+    def to_internal_value(self, data):
+        ret = {
+            "x_coordinate": data["x"],
+            "y_coordinate": data["y"],
+        }
+        return ret
+
+
+class DataPointSerializer(serializers.ModelSerializer):
+    coordinates = CoordinateField(source='*')
+
+    class Meta:
+        model = DataPoint
+        fields = ['label', 'coordinates']
+
+

Note that this example doesn't handle validation. Partly for that reason, in a +real project, the coordinate nesting might be better handled with a nested serializer +using source='*', with two IntegerField instances, each with their own source +pointing to the relevant field.

+

The key points from the example, though, are:

+
    +
  • +

    to_representation is passed the entire DataPoint object and must map from that +to the desired output.

    +
    >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
    +>>> out_serializer = DataPointSerializer(instance)
    +>>> out_serializer.data
    +ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])
    +
    +
  • +
  • +

    Unless our field is to be read-only, to_internal_value must map back to a dict +suitable for updating our target object. With source='*', the return from +to_internal_value will update the root validated data dictionary, rather than a single key.

    +
    >>> data = {
    +...     "label": "Second Example",
    +...     "coordinates": {
    +...         "x": 3,
    +...         "y": 4,
    +...     }
    +... }
    +>>> in_serializer = DataPointSerializer(data=data)
    +>>> in_serializer.is_valid()
    +True
    +>>> in_serializer.validated_data
    +OrderedDict([('label', 'Second Example'),
    +             ('y_coordinate', 4),
    +             ('x_coordinate', 3)])
    +
    +
  • +
+

For completeness lets do the same thing again but with the nested serializer +approach suggested above:

+
class NestedCoordinateSerializer(serializers.Serializer):
+    x = serializers.IntegerField(source='x_coordinate')
+    y = serializers.IntegerField(source='y_coordinate')
+
+
+class DataPointSerializer(serializers.ModelSerializer):
+    coordinates = NestedCoordinateSerializer(source='*')
+
+    class Meta:
+        model = DataPoint
+        fields = ['label', 'coordinates']
+
+

Here the mapping between the target and source attribute pairs (x and +x_coordinate, y and y_coordinate) is handled in the IntegerField +declarations. It's our NestedCoordinateSerializer that takes source='*'.

+

Our new DataPointSerializer exhibits the same behaviour as the custom field +approach.

+

Serializing:

+
>>> out_serializer = DataPointSerializer(instance)
+>>> out_serializer.data
+ReturnDict([('label', 'testing'),
+            ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
+
+

Deserializing:

+
>>> in_serializer = DataPointSerializer(data=data)
+>>> in_serializer.is_valid()
+True
+>>> in_serializer.validated_data
+OrderedDict([('label', 'still testing'),
+             ('x_coordinate', 3),
+             ('y_coordinate', 4)])
+
+

But we also get the built-in validation for free:

+
>>> invalid_data = {
+...     "label": "still testing",
+...     "coordinates": {
+...         "x": 'a',
+...         "y": 'b',
+...     }
+... }
+>>> invalid_serializer = DataPointSerializer(data=invalid_data)
+>>> invalid_serializer.is_valid()
+False
+>>> invalid_serializer.errors
+ReturnDict([('coordinates',
+             {'x': ['A valid integer is required.'],
+              'y': ['A valid integer is required.']})])
+
+

For this reason, the nested serializer approach would be the first to try. You +would use the custom field approach when the nested serializer becomes infeasible +or overly complex.

+

Third party packages

+

The following third party packages are also available.

+

DRF Compound Fields

+

The drf-compound-fields package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.

+

DRF Extra Fields

+

The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes.

+

djangorestframework-recursive

+

the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures

+

django-rest-framework-gis

+

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.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html new file mode 100644 index 000000000..7f6e4ad4c --- /dev/null +++ b/api-guide/filtering/index.html @@ -0,0 +1,826 @@ + + + + + + + Filtering - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + 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

+
+

The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.

+

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the .get_queryset() method.

+

Overriding this method allows you to customize the queryset returned by the view in a number of different ways.

+

Filtering against the current user

+

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.serializers import PurchaseSerializer
+from rest_framework import generics
+
+class PurchaseList(generics.ListAPIView):
+    serializer_class = PurchaseSerializer
+
+    def get_queryset(self):
+        """
+        This view should return a list of all the purchases
+        for the currently authenticated user.
+        """
+        user = self.request.user
+        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.

+

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

+
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):
+    serializer_class = PurchaseSerializer
+
+    def get_queryset(self):
+        """
+        This view should return a list of all the purchases for
+        the user as determined by the username portion of the URL.
+        """
+        username = self.kwargs['username']
+        return Purchase.objects.filter(purchaser__username=username)
+
+

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):
+    serializer_class = PurchaseSerializer
+
+    def get_queryset(self):
+        """
+        Optionally restricts the returned purchases to a given user,
+        by filtering against a `username` query parameter in the URL.
+        """
+        queryset = Purchase.objects.all()
+        username = self.request.query_params.get('username', None)
+        if username is not None:
+            queryset = queryset.filter(purchaser__username=username)
+        return queryset
+
+
+

Generic Filtering

+

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.

+

Generic filters can also present themselves as HTML controls in the browsable API and admin API.

+

Filter Example

+

Setting filter backends

+

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

+
REST_FRAMEWORK = {
+    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
+}
+
+

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

+
import django_filters.rest_framework
+from django.contrib.auth.models import User
+from myapp.serializers import UserSerializer
+from rest_framework import generics
+
+class UserListView(generics.ListAPIView):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
+
+

Filtering and object lookups

+

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

+

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

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

Overriding the initial queryset

+

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

+
class PurchasedProductsList(generics.ListAPIView):
+    """
+    Return a list of all the products that the authenticated
+    user has ever purchased, with optional filtering.
+    """
+    model = Product
+    serializer_class = ProductSerializer
+    filterset_class = ProductFilter
+
+    def get_queryset(self):
+        user = self.request.user
+        return user.purchase_set.all()
+
+
+

API Guide

+

DjangoFilterBackend

+

The django-filter library includes a DjangoFilterBackend class which +supports highly customizable field filtering for REST framework.

+

To use DjangoFilterBackend, first install django-filter. Then add django_filters to Django's INSTALLED_APPS

+
pip install django-filter
+
+

You should now either add the filter backend to your settings:

+
REST_FRAMEWORK = {
+    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
+}
+
+

Or add the filter backend to an individual View or ViewSet.

+
from django_filters.rest_framework import DjangoFilterBackend
+
+class UserListView(generics.ListAPIView):
+    ...
+    filter_backends = [DjangoFilterBackend]
+
+

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

+
class ProductList(generics.ListAPIView):
+    queryset = Product.objects.all()
+    serializer_class = ProductSerializer
+    filter_backends = [DjangoFilterBackend]
+    filterset_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
+
+

For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. +You can read more about FilterSets in the django-filter documentation. +It's also recommended that you read the section on DRF integration.

+

SearchFilter

+

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

+

When in use, the browsable API will include a SearchFilter control:

+

Search Filter

+

The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField.

+
from rest_framework import filters
+
+class UserListView(generics.ListAPIView):
+    queryset = User.objects.all()
+    serializer_class = 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
+
+

You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:

+
search_fields = ['username', 'email', 'profile__profession']
+
+

By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.

+

The search behavior may be restricted by prepending various characters to the search_fields.

+
    +
  • '^' Starts-with search.
  • +
  • '=' Exact matches.
  • +
  • '@' Full-text search. (Currently only supported Django's MySQL backend.)
  • +
  • '$' Regex search.
  • +
+

For example:

+
search_fields = ['=username', '=email']
+
+

By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting.

+

To dynamically change search fields based on request content, it's possible to subclass the SearchFilter and override the get_search_fields() function. For example, the following subclass will only search on title if the query parameter title_only is in the request:

+
from rest_framework import filters
+
+class CustomSearchFilter(filters.SearchFilter):
+    def get_search_fields(self, view, request):
+        if request.query_params.get('title_only'):
+            return ['title']
+        return super(CustomSearchFilter, self).get_search_fields(view, request)
+
+

For more details, see the Django documentation.

+
+

OrderingFilter

+

The OrderingFilter class supports simple query parameter controlled ordering of results.

+

Ordering Filter

+

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
+
+

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

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

Multiple orderings may also be specified:

+
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):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    filter_backends = [filters.OrderingFilter]
+    ordering_fields = ['username', 'email']
+
+

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):
+    queryset = Booking.objects.all()
+    serializer_class = BookingSerializer
+    filter_backends = [filters.OrderingFilter]
+    ordering_fields = '__all__'
+
+

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):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    filter_backends = [filters.OrderingFilter]
+    ordering_fields = ['username', 'email']
+    ordering = ['username']
+
+

The ordering attribute may be either a string or a list/tuple of strings.

+
+

Custom generic filtering

+

You can also provide your own generic filtering backend, or write an installable app for other developers to use.

+

To do so override BaseFilterBackend, and override the .filter_queryset(self, request, queryset, view) method. The method should return a new, filtered queryset.

+

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):
+    """
+    Filter that only allows users to see their own objects.
+    """
+    def filter_queryset(self, request, queryset, view):
+        return queryset.filter(owner=request.user)
+
+

We could achieve the same behavior by overriding get_queryset() on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.

+

Customizing the interface

+

Generic filters may also present an interface in the browsable API. To do so you should implement a to_html() method which returns a rendered HTML representation of the filter. This method should have the following signature:

+

to_html(self, request, queryset, view)

+

The method should return a rendered HTML string.

+

Pagination & schemas

+

You can also make the filter controls available to the schema autogeneration +that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature:

+

get_schema_fields(self, view)

+

The method should return a list of coreapi.Field instances.

+

Third party packages

+

The following third party packages provide additional filter implementations.

+

Django REST framework filters package

+

The django-rest-framework-filters 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.

+

Django REST framework full word search filter

+

The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.

+

Django URL Filter

+

django-url-filter provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django QuerySets.

+

drf-url-filters

+

drf-url-filter is a simple Django app to apply filters on drf ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package Voluptuous is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/format-suffixes/index.html b/api-guide/format-suffixes/index.html new file mode 100644 index 000000000..9fceab821 --- /dev/null +++ b/api-guide/format-suffixes/index.html @@ -0,0 +1,561 @@ + + + + + + + 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.

+

Using with i18n_patterns

+

If using the i18n_patterns function provided by Django, as well as format_suffix_patterns you should make sure that the i18n_patterns function is applied as the final, or outermost function. For example:

+
url patterns = [
+    …
+]
+
+urlpatterns = i18n_patterns(
+    format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
+)
+
+
+

Query parameter formats

+

An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations.

+

To select a representation using its short format, use the format query parameter. For example: http://example.com/organizations/?format=csv.

+

The name of this query parameter can be modified using the URL_FORMAT_OVERRIDE setting. Set the value to None to disable this behavior.

+
+

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/index.html b/api-guide/generic-views/index.html new file mode 100644 index 000000000..8e553d9af --- /dev/null +++ b/api-guide/generic-views/index.html @@ -0,0 +1,854 @@ + + + + + + + Generic views - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + 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

+
+

One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.

+

The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.

+

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 myapp.serializers import UserSerializer
+from rest_framework import generics
+from rest_framework.permissions import IsAdminUser
+
+class UserList(generics.ListCreateAPIView):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    permission_classes = [IsAdminUser]
+
+

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

+
class UserList(generics.ListCreateAPIView):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    permission_classes = [IsAdminUser]
+
+    def list(self, request):
+        # Note the use of `get_queryset()` instead of `self.queryset`
+        queryset = self.get_queryset()
+        serializer = UserSerializer(queryset, many=True)
+        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(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
+
+
+

API Reference

+

GenericAPIView

+

This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views.

+

Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.

+

Attributes

+

Basic settings:

+

The following attributes control the basic view behavior.

+
    +
  • queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.
  • +
  • serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method.
  • +
  • lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk'. Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.
  • +
  • lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field.
  • +
+

Pagination:

+

The following attributes are used to control pagination when used with list views.

+
    +
  • pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination'. Setting pagination_class=None will disable pagination on this view.
  • +
+

Filtering:

+
    +
  • filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.
  • +
+

Methods

+

Base methods:

+

get_queryset(self)

+

Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute.

+

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):
+    user = self.request.user
+    return user.accounts.all()
+
+

get_object(self)

+

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):
+    queryset = self.get_queryset()
+    filter = {}
+    for field in self.multiple_lookup_fields:
+        filter[field] = self.kwargs[field]
+
+    obj = get_object_or_404(queryset, **filter)
+    self.check_object_permissions(self.request, obj)
+    return obj
+
+

Note that if your API doesn't include any object level permissions, you may optionally exclude the self.check_object_permissions, and simply return the object from the get_object_or_404 lookup.

+

filter_queryset(self, queryset)

+

Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.

+

For example:

+
def filter_queryset(self, queryset):
+    filter_backends = [CategoryFilter]
+
+    if 'geo_route' in self.request.query_params:
+        filter_backends = [GeoRouteFilter, CategoryFilter]
+    elif 'geo_point' in self.request.query_params:
+        filter_backends = [GeoPointFilter, CategoryFilter]
+
+    for backend in list(filter_backends):
+        queryset = backend().filter_queryset(self.request, queryset, view=self)
+
+    return queryset
+
+

get_serializer_class(self)

+

Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute.

+

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):
+    if self.request.user.is_staff:
+        return FullAccountSerializer
+    return BasicAccountSerializer
+
+

Save and deletion hooks:

+

The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.

+
    +
  • perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.
  • +
  • perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance.
  • +
  • perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance.
  • +
+

These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

+
def perform_create(self, serializer):
+    serializer.save(user=self.request.user)
+
+

These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.

+
def perform_update(self, serializer):
+    instance = serializer.save()
+    send_email_confirmation(user=self.request.user, modified=instance)
+
+

You can also use these hooks to provide additional validation, by raising a ValidationError(). This can be useful if you need some validation logic to apply at the point of database save. For example:

+
def perform_create(self, serializer):
+    queryset = SignupRequest.objects.filter(user=self.request.user)
+    if queryset.exists():
+        raise ValidationError('You have already signed up')
+    serializer.save(user=self.request.user)
+
+

Note: These methods replace the old-style version 2.x pre_save, post_save, pre_delete and post_delete methods, which are no longer available.

+

Other methods:

+

You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView.

+
    +
  • get_serializer_context(self) - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including 'request', 'view' and 'format' keys.
  • +
  • get_serializer(self, instance=None, data=None, many=False, partial=False) - Returns a serializer instance.
  • +
  • get_paginated_response(self, data) - Returns a paginated style Response object.
  • +
  • paginate_queryset(self, queryset) - Paginate a queryset if required, either returning a page object, or None if pagination is not configured for this view.
  • +
  • filter_queryset(self, queryset) - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
  • +
+
+

Mixins

+

The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.

+

The mixin classes can be imported from rest_framework.mixins.

+

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.

+

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.

+

If the request data provided for creating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response.

+

RetrieveModelMixin

+

Provides a .retrieve(request, *args, **kwargs) method, that implements returning an existing model instance in a response.

+

If an object can be retrieved this returns a 200 OK response, with a serialized representation of the object as the body of the response. Otherwise it will return a 404 Not Found.

+

UpdateModelMixin

+

Provides a .update(request, *args, **kwargs) method, that implements updating and saving an existing model instance.

+

Also provides a .partial_update(request, *args, **kwargs) method, which is similar to the update method, except that all fields for the update will be optional. This allows support for HTTP PATCH requests.

+

If an object is updated this returns a 200 OK response, with a serialized representation of the object as the body of the response.

+

If the request data provided for updating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response.

+

DestroyModelMixin

+

Provides a .destroy(request, *args, **kwargs) method, that implements deletion of an existing model instance.

+

If an object is deleted this returns a 204 No Content response, otherwise it will return a 404 Not Found.

+
+

Concrete View Classes

+

The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.

+

The view classes can be imported from rest_framework.generics.

+

CreateAPIView

+

Used for create-only endpoints.

+

Provides a post method handler.

+

Extends: GenericAPIView, CreateModelMixin

+

ListAPIView

+

Used for read-only endpoints to represent a collection of model instances.

+

Provides a get method handler.

+

Extends: GenericAPIView, ListModelMixin

+

RetrieveAPIView

+

Used for read-only endpoints to represent a single model instance.

+

Provides a get method handler.

+

Extends: GenericAPIView, RetrieveModelMixin

+

DestroyAPIView

+

Used for delete-only endpoints for a single model instance.

+

Provides a delete method handler.

+

Extends: GenericAPIView, DestroyModelMixin

+

UpdateAPIView

+

Used for update-only endpoints for a single model instance.

+

Provides put and patch method handlers.

+

Extends: GenericAPIView, UpdateModelMixin

+

ListCreateAPIView

+

Used for read-write endpoints to represent a collection of model instances.

+

Provides get and post method handlers.

+

Extends: GenericAPIView, ListModelMixin, CreateModelMixin

+

RetrieveUpdateAPIView

+

Used for read or update endpoints to represent a single model instance.

+

Provides get, put and patch method handlers.

+

Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin

+

RetrieveDestroyAPIView

+

Used for read or delete endpoints to represent a single model instance.

+

Provides get and delete method handlers.

+

Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin

+

RetrieveUpdateDestroyAPIView

+

Used for read-write-delete endpoints to represent a single model instance.

+

Provides get, put, patch and delete method handlers.

+

Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin

+
+

Customizing the generic views

+

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):
+    """
+    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.
+    """
+    def get_object(self):
+        queryset = self.get_queryset()             # Get the base queryset
+        queryset = self.filter_queryset(queryset)  # Apply any filter backends
+        filter = {}
+        for field in self.lookup_fields:
+            if self.kwargs[field]: # Ignore empty fields.
+                filter[field] = self.kwargs[field]
+        obj = get_object_or_404(queryset, **filter)  # Lookup the object
+        self.check_object_permissions(self.request, obj)
+        return obj
+
+

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):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    lookup_fields = ['account', 'username']
+
+

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,
+                       generics.RetrieveAPIView):
+    pass
+
+class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
+                                    generics.RetrieveUpdateDestroyAPIView):
+    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 Multiple Models

+

Django Rest Multiple Models provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/metadata/index.html b/api-guide/metadata/index.html new file mode 100644 index 000000000..4b9165649 --- /dev/null +++ b/api-guide/metadata/index.html @@ -0,0 +1,603 @@ + + + + + + + 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.

+
@action(methods=['GET'], detail=False)
+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()
+        }
+
+

Then configure your settings to use this custom class:

+
REST_FRAMEWORK = {
+    'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'
+}
+
+

Third party packages

+

The following third party packages provide additional metadata implementations.

+

DRF-schema-adapter

+

drf-schema-adapter is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate json-schema as well as schema information readable by various libraries.

+

You can also write your own adapter to work with your specific frontend. +If you wish to do so, it also provides an exporter that can export those schema information to json files.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html new file mode 100644 index 000000000..ce26f10b1 --- /dev/null +++ b/api-guide/pagination/index.html @@ -0,0 +1,784 @@ + + + + + + + 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 support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.

+

The pagination API can support either:

+
    +
  • Pagination links that are provided as part of the content of the response.
  • +
  • Pagination links that are included in response headers, such as Content-Range or Link.
  • +
+

The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.

+

Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.

+

Pagination can be turned off by setting the pagination class to None.

+

Setting the pagination style

+

The pagination style may be set globally, using the DEFAULT_PAGINATION_CLASS and PAGE_SIZE setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
+    'PAGE_SIZE': 100
+}
+
+

Note that you need to set both the pagination class, and the page size that should be used. Both DEFAULT_PAGINATION_CLASS and PAGE_SIZE are None by default.

+

You can also set the pagination class on an individual view by using the pagination_class attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.

+

Modifying the pagination style

+

If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change.

+
class LargeResultsSetPagination(PageNumberPagination):
+    page_size = 1000
+    page_size_query_param = 'page_size'
+    max_page_size = 10000
+
+class StandardResultsSetPagination(PageNumberPagination):
+    page_size = 100
+    page_size_query_param = 'page_size'
+    max_page_size = 1000
+
+

You can then apply your new style to a view using the pagination_class attribute:

+
class BillingRecordsView(generics.ListAPIView):
+    queryset = Billing.objects.all()
+    serializer_class = BillingRecordsSerializer
+    pagination_class = LargeResultsSetPagination
+
+

Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'
+}
+
+
+

API Reference

+

PageNumberPagination

+

This pagination style accepts a single number page number in the request query parameters.

+

Request:

+
GET https://api.example.org/accounts/?page=4
+
+

Response:

+
HTTP 200 OK
+{
+    "count": 1023
+    "next": "https://api.example.org/accounts/?page=5",
+    "previous": "https://api.example.org/accounts/?page=3",
+    "results": [
+       …
+    ]
+}
+
+

Setup

+

To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
+    'PAGE_SIZE': 100
+}
+
+

On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.

+

Configuration

+

The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style.

+

To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above.

+
    +
  • django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator, which should be fine for most use cases.
  • +
  • page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key.
  • +
  • page_query_param - A string value indicating the name of the query parameter to use for the pagination control.
  • +
  • page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None, indicating that the client may not control the requested page size.
  • +
  • max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set.
  • +
  • last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',)
  • +
  • template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/numbers.html".
  • +
+
+

LimitOffsetPagination

+

This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an +"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.

+

Request:

+
GET https://api.example.org/accounts/?limit=100&offset=400
+
+

Response:

+
HTTP 200 OK
+{
+    "count": 1023
+    "next": "https://api.example.org/accounts/?limit=100&offset=500",
+    "previous": "https://api.example.org/accounts/?limit=100&offset=300",
+    "results": [
+       …
+    ]
+}
+
+

Setup

+

To enable the LimitOffsetPagination style globally, use the following configuration:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
+}
+
+

Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client.

+

On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis.

+

Configuration

+

The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style.

+

To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above.

+
    +
  • default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key.
  • +
  • limit_query_param - A string value indicating the name of the "limit" query parameter. Defaults to 'limit'.
  • +
  • offset_query_param - A string value indicating the name of the "offset" query parameter. Defaults to 'offset'.
  • +
  • max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None.
  • +
  • template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/numbers.html".
  • +
+
+

CursorPagination

+

The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.

+

Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.

+

Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits:

+
    +
  • Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process.
  • +
  • Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.
  • +
+

Details and limitations

+

Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by "-created". This assumes that there must be a 'created' timestamp field on the model instances, and will present a "timeline" style paginated view, with the most recently added items first.

+

You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination. When used with OrderingFilter you should strongly consider restricting the fields that the user may order by.

+

Proper usage of cursor pagination should have an ordering field that satisfies the following:

+
    +
  • Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.
  • +
  • Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering.
  • +
  • Should be a non-nullable value that can be coerced to a string.
  • +
  • Should not be a float. Precision errors easily lead to incorrect results. + Hint: use decimals instead. + (If you already have a float field and must paginate on that, an + example CursorPagination subclass that uses decimals to limit precision is available here.)
  • +
  • The field should have a database index.
  • +
+

Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.

+

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

+

Setup

+

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

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
+    'PAGE_SIZE': 100
+}
+
+

On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis.

+

Configuration

+

The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style.

+

To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above.

+
    +
  • page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key.
  • +
  • cursor_query_param = A string value indicating the name of the "cursor" query parameter. Defaults to 'cursor'.
  • +
  • ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug'. Defaults to -created. This value may also be overridden by using OrderingFilter on the view.
  • +
  • template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/previous_and_next.html".
  • +
+
+

Custom pagination styles

+

To create a custom pagination serializer class you should subclass pagination.BasePagination and override the paginate_queryset(self, queryset, request, view=None) and get_paginated_response(self, data) methods:

+
    +
  • The paginate_queryset method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
  • +
  • The get_paginated_response method is passed the serialized page data and should return a Response instance.
  • +
+

Note that the paginate_queryset method may set state on the pagination instance, that may later be used by the get_paginated_response method.

+

Example

+

Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:

+
class CustomPagination(pagination.PageNumberPagination):
+    def get_paginated_response(self, data):
+        return Response({
+            'links': {
+                'next': self.get_next_link(),
+                'previous': self.get_previous_link()
+            },
+            'count': self.page.paginator.count,
+            'results': data
+        })
+
+

We'd then need to setup the custom class in our configuration:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
+    'PAGE_SIZE': 100
+}
+
+

Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an OrderedDict when constructing the body of paginated responses, but this is optional.

+

Using your custom pagination class

+

To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting:

+
REST_FRAMEWORK = {
+    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',
+    'PAGE_SIZE': 100
+}
+
+

API responses for list endpoints will now include a Link header, instead of including the pagination links as part of the body of the response, for example:

+

Link Header

+

A custom pagination style, using the 'Link' header'

+

Pagination & schemas

+

You can also make the pagination controls available to the schema autogeneration +that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature:

+

get_schema_fields(self, view)

+

The method should return a list of coreapi.Field instances.

+
+

HTML pagination controls

+

By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The PageNumberPagination and LimitOffsetPagination classes display a list of page numbers with previous and next controls. The CursorPagination class displays a simpler style that only displays a previous and next control.

+

Customizing the controls

+

You can override the templates that render the HTML pagination controls. The two built-in styles are:

+
    +
  • rest_framework/pagination/numbers.html
  • +
  • rest_framework/pagination/previous_and_next.html
  • +
+

Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.

+

Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style.

+

Low-level API

+

The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed.

+

The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.

+
+

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.

+

drf-proxy-pagination

+

The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter.

+ +

The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in Github's developer documentation.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html new file mode 100644 index 000000000..2c505f159 --- /dev/null +++ b/api-guide/parsers/index.html @@ -0,0 +1,717 @@ + + + + + + + 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 request.data 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 only requests with JSON content, instead of the default of JSON or form data.

+
REST_FRAMEWORK = {
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework.parsers.JSONParser',
+    ]
+}
+
+

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

+
from rest_framework.parsers import JSONParser
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+class ExampleView(APIView):
+    """
+    A view that can accept POST requests with JSON content.
+    """
+    parser_classes = [JSONParser]
+
+    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.

+
from rest_framework.decorators import api_view
+from rest_framework.decorators import parser_classes
+from rest_framework.parsers import JSONParser
+
+@api_view(['POST'])
+@parser_classes([JSONParser])
+def example_view(request, format=None):
+    """
+    A view that can accept POST requests with JSON content.
+    """
+    return Response({'received data': request.data})
+
+
+

API Reference

+

JSONParser

+

Parses JSON request content.

+

.media_type: application/json

+

FormParser

+

Parses HTML form content. request.data will be populated with a 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 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 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 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:
+
# views.py
+class FileUploadView(views.APIView):
+    parser_classes = [FileUploadParser]
+
+    def put(self, request, filename, format=None):
+        file_obj = request.data['file']
+        # ...
+        # do some stuff with uploaded file
+        # ...
+        return Response(status=204)
+
+# urls.py
+urlpatterns = [
+    # ...
+    url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
+]
+
+
+

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.

+

YAML

+

REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.

+

Installation & configuration

+

Install using pip.

+
$ pip install djangorestframework-yaml
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework_yaml.parsers.YAMLParser',
+    ],
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework_yaml.renderers.YAMLRenderer',
+    ],
+}
+
+

XML

+

REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.

+

Installation & configuration

+

Install using pip.

+
$ pip install djangorestframework-xml
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework_xml.parsers.XMLParser',
+    ],
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework_xml.renderers.XMLRenderer',
+    ],
+}
+
+

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/index.html b/api-guide/permissions/index.html new file mode 100644 index 000000000..d3c881a74 --- /dev/null +++ b/api-guide/permissions/index.html @@ -0,0 +1,796 @@ + + + + + + + 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.

+

Permissions are used to grant or deny access for different classes of users to different parts of the API.

+

The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.

+

A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the IsAuthenticatedOrReadOnly class in REST framework.

+

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 or exceptions.NotAuthenticated exception will be raised, and the main body of the view will not run.

+

When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:

+
    +
  • The request was successfully authenticated, but permission was denied. — An HTTP 403 Forbidden response will be returned.
  • +
  • The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. — An HTTP 403 Forbidden response will be returned.
  • +
  • The request was not successfully authenticated, and the highest priority authentication class does use WWW-Authenticate headers. — An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.
  • +
+

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(), pk=self.kwargs["pk"])
+    self.check_object_permissions(self.request, obj)
+    return obj
+
+
+

Note: With the exception of DjangoObjectPermissions, the provided +permission classes in rest_framework.permissions do not implement the +methods necessary to check object permissions.

+

If you wish to use the provided permission classes in order to check object +permissions, you must subclass them and implement the +has_object_permission() method described in the Custom +permissions section (below).

+
+

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.

+
from rest_framework.decorators import api_view, permission_classes
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+
+@api_view(['GET'])
+@permission_classes([IsAuthenticated])
+def example_view(request, format=None):
+    content = {
+        'status': 'request was permitted'
+    }
+    return Response(content)
+
+

Note: when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file.

+

Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written:

+
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+class ReadOnly(BasePermission):
+    def has_permission(self, request, view):
+        return request.method in SAFE_METHODS
+
+class ExampleView(APIView):
+    permission_classes = [IsAuthenticated|ReadOnly]
+
+    def get(self, request, format=None):
+        content = {
+            'status': 'request was permitted'
+        }
+        return Response(content)
+
+

Note: it supports & (and), | (or) and ~ (not).

+
+

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 if 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 have 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 sentinel 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 or .get_queryset() method. 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 DjangoObjectPermissions 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 and are using django-guardian for your object-level permissions backend, you'll want to consider using the DjangoObjectPermissionsFilter class provided by the djangorestframework-guardian package. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.

+
+

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. (Function-based views will need to check object permissions explicitly, raising PermissionDenied on failure.)

+
+

Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used.

+
from rest_framework import permissions
+
+class CustomerAccessPermission(permissions.BasePermission):
+    message = 'Adding customers not allowed.'
+
+    def has_permission(self, request, view):
+         ...
+
+

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 - Access Policy

+

The Django REST - Access Policy package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.

+

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.

+

DRY Rest Permissions

+

The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.

+

Django Rest Framework Roles

+

The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.

+

Django REST Framework API Key

+

The Django REST Framework API Key package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. machines) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.

+

Django Rest Framework Role Filters

+

The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html new file mode 100644 index 000000000..a5a193a1e --- /dev/null +++ b/api-guide/relations/index.html @@ -0,0 +1,1071 @@ + + + + + + + Serializer relations - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + relations.py + + + + +

Serializer relations

+
+

Data structures, not algorithms, are central to programming.

+

Rob Pike

+
+

Relational fields are used to represent model relationships. They can be applied to ForeignKey, ManyToManyField and OneToOneField relationships, as well as to reverse relationships, and custom relationships such as GenericForeignKey.

+
+

Note: The relational fields are declared in relations.py, but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers.<FieldName>.

+
+

Inspecting relationships.

+

When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.

+

To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation…

+
>>> from myapp.serializers import AccountSerializer
+>>> serializer = AccountSerializer()
+>>> print(repr(serializer))
+AccountSerializer():
+    id = IntegerField(label='ID', read_only=True)
+    name = CharField(allow_blank=True, max_length=100, required=False)
+    owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
+

API Reference

+

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

+
class Album(models.Model):
+    album_name = models.CharField(max_length=100)
+    artist = models.CharField(max_length=100)
+
+class Track(models.Model):
+    album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
+    order = models.IntegerField()
+    title = models.CharField(max_length=100)
+    duration = models.IntegerField()
+
+    class Meta:
+        unique_together = ['album', 'order']
+        ordering = ['order']
+
+    def __str__(self):
+        return '%d: %s' % (self.order, self.title)
+
+

StringRelatedField

+

StringRelatedField may be used to represent the target of the relationship using its __str__ method.

+

For example, the following serializer.

+
class AlbumSerializer(serializers.ModelSerializer):
+    tracks = serializers.StringRelatedField(many=True)
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

Would serialize to the following representation.

+
{
+    'album_name': 'Things We Lost In The Fire',
+    'artist': 'Low',
+    'tracks': [
+        '1: Sunflower',
+        '2: Whitetail',
+        '3: Dinosaur Act',
+        ...
+    ]
+}
+
+

This field is read only.

+

Arguments:

+
    +
  • many - If applied to a to-many relationship, you should set this argument to True.
  • +
+

PrimaryKeyRelatedField

+

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

+

For example, the following serializer:

+
class AlbumSerializer(serializers.ModelSerializer):
+    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

Would serialize to a representation like this:

+
{
+    'album_name': 'Undun',
+    'artist': 'The Roots',
+    'tracks': [
+        89,
+        90,
+        91,
+        ...
+    ]
+}
+
+

By default this field is read-write, although you can change this behavior using the read_only flag.

+

Arguments:

+
    +
  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • +
  • many - If applied to a to-many relationship, you should set this argument to True.
  • +
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
  • +
  • pk_field - Set to a field to control serialization/deserialization of the primary key's value. For example, pk_field=UUIDField(format='hex') would serialize a UUID primary key into its compact hex representation.
  • +
+

HyperlinkedRelatedField

+

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

+

For example, the following serializer:

+
class AlbumSerializer(serializers.ModelSerializer):
+    tracks = serializers.HyperlinkedRelatedField(
+        many=True,
+        read_only=True,
+        view_name='track-detail'
+    )
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

Would serialize to a representation like this:

+
{
+    'album_name': 'Graceland',
+    'artist': 'Paul Simon',
+    'tracks': [
+        'http://www.example.com/api/tracks/45/',
+        'http://www.example.com/api/tracks/46/',
+        'http://www.example.com/api/tracks/47/',
+        ...
+    ]
+}
+
+

By default this field is read-write, although you can change this behavior using the read_only flag.

+
+

Note: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments.

+

This is suitable for URLs that contain a single primary key or slug argument as part of the URL.

+

If you require more complex hyperlinked representation you'll need to customize the field, as described in the custom hyperlinked fields section, below.

+
+

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 will be a string with the format <modelname>-detail. required.
  • +
  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • +
  • many - If applied to a to-many relationship, you should set this argument to True.
  • +
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
  • +
  • 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'.
  • +
  • lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
  • +
  • format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.
  • +
+

SlugRelatedField

+

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

+

For example, the following serializer:

+
class AlbumSerializer(serializers.ModelSerializer):
+    tracks = serializers.SlugRelatedField(
+        many=True,
+        read_only=True,
+        slug_field='title'
+     )
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

Would serialize to a representation like this:

+
{
+    'album_name': 'Dear John',
+    'artist': 'Loney Dear',
+    'tracks': [
+        'Airport Surroundings',
+        'Everything Turns to You',
+        'I Was Only Going Out',
+        ...
+    ]
+}
+
+

By default this field is read-write, although you can change this behavior using the read_only flag.

+

When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True.

+

Arguments:

+
    +
  • slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, username. required
  • +
  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • +
  • many - If applied to a to-many relationship, you should set this argument to True.
  • +
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
  • +
+

HyperlinkedIdentityField

+

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

+
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
+    track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'track_listing']
+
+

Would serialize to a representation like this:

+
{
+    'album_name': 'The Eraser',
+    'artist': 'Thom Yorke',
+    'track_listing': 'http://www.example.com/api/track_list/12/',
+}
+
+

This field is always read-only.

+

Arguments:

+
    +
  • view_name - The view name that should be used as the target of the relationship. 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'.
  • +
  • lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
  • +
  • format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.
  • +
+
+

Nested relationships

+

As opposed to previously discussed references to another entity, the referred entity can instead also be embedded or nested +in the representation of the object that refers to it. +Such nested relationships can be expressed by using serializers as fields.

+

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

+

Example

+

For example, the following serializer:

+
class TrackSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Track
+        fields = ['order', 'title', 'duration']
+
+class AlbumSerializer(serializers.ModelSerializer):
+    tracks = TrackSerializer(many=True, read_only=True)
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

Would serialize to a nested representation like this:

+
>>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
+>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
+<Track: Track object>
+>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
+<Track: Track object>
+>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
+<Track: Track object>
+>>> serializer = AlbumSerializer(instance=album)
+>>> serializer.data
+{
+    'album_name': 'The Grey Album',
+    'artist': 'Danger Mouse',
+    'tracks': [
+        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
+        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
+        {'order': 3, 'title': 'Encore', 'duration': 159},
+        ...
+    ],
+}
+
+

Writable nested serializers

+

By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved.

+
class TrackSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Track
+        fields = ['order', 'title', 'duration']
+
+class AlbumSerializer(serializers.ModelSerializer):
+    tracks = TrackSerializer(many=True)
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+    def create(self, validated_data):
+        tracks_data = validated_data.pop('tracks')
+        album = Album.objects.create(**validated_data)
+        for track_data in tracks_data:
+            Track.objects.create(album=album, **track_data)
+        return album
+
+>>> data = {
+    'album_name': 'The Grey Album',
+    'artist': 'Danger Mouse',
+    'tracks': [
+        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
+        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
+        {'order': 3, 'title': 'Encore', 'duration': 159},
+    ],
+}
+>>> serializer = AlbumSerializer(data=data)
+>>> serializer.is_valid()
+True
+>>> serializer.save()
+<Album: Album object>
+
+
+

Custom relational fields

+

In rare cases where none of the existing relational styles fit the representation you need, +you can implement a completely custom relational field, that describes exactly how the +output representation should be generated from the model instance.

+

To implement a custom relational field, you should override RelatedField, and implement the .to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.

+

If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method.

+

To provide a dynamic queryset based on the context, you can also override .get_queryset(self) instead of specifying .queryset on the class or when initializing the field.

+

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
+
+class TrackListingField(serializers.RelatedField):
+    def to_representation(self, value):
+        duration = time.strftime('%M:%S', time.gmtime(value.duration))
+        return 'Track %d: %s (%s)' % (value.order, value.name, duration)
+
+class AlbumSerializer(serializers.ModelSerializer):
+    tracks = TrackListingField(many=True)
+
+    class Meta:
+        model = Album
+        fields = ['album_name', 'artist', 'tracks']
+
+

This custom field would then serialize to the following representation.

+
{
+    'album_name': 'Sometimes I Wish We Were an Eagle',
+    'artist': 'Bill Callahan',
+    'tracks': [
+        'Track 1: Jim Cain (04:39)',
+        'Track 2: Eid Ma Clack Shaw (04:19)',
+        'Track 3: The Wind and the Dove (04:34)',
+        ...
+    ]
+}
+
+
+

Custom hyperlinked fields

+

In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.

+

You can achieve this by overriding HyperlinkedRelatedField. There are two methods that may be overridden:

+

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

+

The get_url method is used to map the object instance to its URL representation.

+

May raise a NoReverseMatch if the view_name and lookup_field +attributes are not configured to correctly match the URL conf.

+

get_object(self, view_name, view_args, view_kwargs)

+

If you want to support a writable hyperlinked field then you'll also want to override get_object, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.

+

The return value of this method should the object that corresponds to the matched URL conf arguments.

+

May raise an ObjectDoesNotExist exception.

+

Example

+

Say we have a URL for a customer object that takes two keyword arguments, like so:

+
/api/<organization_slug>/customers/<customer_pk>/
+
+

This cannot be represented with the default implementation, which accepts only a single lookup field.

+

In this case we'd need to override HyperlinkedRelatedField to get the behavior we want:

+
from rest_framework import serializers
+from rest_framework.reverse import reverse
+
+class CustomerHyperlink(serializers.HyperlinkedRelatedField):
+    # We define these as class attributes, so we don't need to pass them as arguments.
+    view_name = 'customer-detail'
+    queryset = Customer.objects.all()
+
+    def get_url(self, obj, view_name, request, format):
+        url_kwargs = {
+            'organization_slug': obj.organization.slug,
+            'customer_pk': obj.pk
+        }
+        return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
+
+    def get_object(self, view_name, view_args, view_kwargs):
+        lookup_kwargs = {
+           'organization__slug': view_kwargs['organization_slug'],
+           'pk': view_kwargs['customer_pk']
+        }
+        return self.get_queryset().get(**lookup_kwargs)
+
+

Note that if you wanted to use this style together with the generic views then you'd also need to override .get_object on the view in order to get the correct lookup behavior.

+

Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.

+
+

Further notes

+

The queryset argument

+

The queryset argument is only ever required for writable relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.

+

In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used.

+

This behavior is now replaced with always using an explicit queryset argument for writable relational fields.

+

Doing so reduces the amount of hidden 'magic' that ModelSerializer provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the ModelSerializer shortcut, or using fully explicit Serializer classes.

+

Customizing the HTML display

+

The built-in __str__ method of the model will be used to generate string representations of the objects used to populate the choices property. These choices are used to populate select HTML inputs in the browsable API.

+

To provide customized representations for such inputs, override display_value() of a RelatedField subclass. This method will receive a model object, and should return a string suitable for representing it. For example:

+
class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
+    def display_value(self, instance):
+        return 'Track: %s' % (instance.title)
+
+

Select field cutoffs

+

When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.

+

This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.

+

There are two keyword arguments you can use to control this behavior:

+
    +
  • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to None to disable any limiting. Defaults to 1000.
  • +
  • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
  • +
+

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

+

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

+
assigned_to = serializers.SlugRelatedField(
+   queryset=User.objects.all(),
+   slug_field='username',
+   style={'base_template': 'input.html'}
+)
+
+

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 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):
+    album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
+    ...
+
+

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 Meta:
+        fields = ['track_set', ...]
+
+

See the Django documentation on reverse relationships for more details.

+

Generic relationships

+

If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to 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):
+    """
+    Tags arbitrary model instances using a generic relation.
+
+    See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/
+    """
+    tag_name = models.SlugField()
+    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
+    object_id = models.PositiveIntegerField()
+    tagged_object = GenericForeignKey('content_type', 'object_id')
+
+    def __str__(self):
+        return self.tag_name
+
+

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

+
class Bookmark(models.Model):
+    """
+    A bookmark consists of a URL, and 0 or more descriptive tags.
+    """
+    url = models.URLField()
+    tags = GenericRelation(TaggedItem)
+
+
+class Note(models.Model):
+    """
+    A note consists of some text, and 0 or more descriptive tags.
+    """
+    text = models.CharField(max_length=1000)
+    tags = GenericRelation(TaggedItem)
+
+

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):
+    """
+    A custom field to use for the `tagged_object` generic relationship.
+    """
+
+    def to_representation(self, value):
+        """
+        Serialize tagged objects to a simple textual representation.
+        """
+        if isinstance(value, Bookmark):
+            return 'Bookmark: ' + value.url
+        elif isinstance(value, Note):
+            return 'Note: ' + value.text
+        raise Exception('Unexpected type of tagged object')
+
+

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

+
    def to_representation(self, value):
+        """
+        Serialize bookmark instances using a bookmark serializer,
+        and note instances using a note serializer.
+        """
+        if isinstance(value, Bookmark):
+            serializer = BookmarkSerializer(value)
+        elif isinstance(value, Note):
+            serializer = NoteSerializer(value)
+        else:
+            raise Exception('Unexpected type of tagged object')
+
+        return serializer.data
+
+

Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.

+

For more information see the Django documentation on generic relations.

+

ManyToManyFields with a Through Model

+

By default, relational fields that target a ManyToManyField with a +through model specified are set to read-only.

+

If you explicitly specify a relational field pointing to a +ManyToManyField with a through model, be sure to set read_only +to True.

+

If you wish to represent extra fields on a through model then you may serialize the through model as a nested object.

+
+

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.

+

Rest Framework Generic Relations

+

The rest-framework-generic-relations library provides read/write serialization for generic foreign keys.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/renderers/index.html b/api-guide/renderers/index.html new file mode 100644 index 000000000..f9cc6281d --- /dev/null +++ b/api-guide/renderers/index.html @@ -0,0 +1,984 @@ + + + + + + + Renderers - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + 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

+
+

REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.

+

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.

+

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 JSON as the main media type and also include the self describing API.

+
REST_FRAMEWORK = {
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework.renderers.JSONRenderer',
+        'rest_framework.renderers.BrowsableAPIRenderer',
+    ]
+}
+
+

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 rest_framework.renderers import JSONRenderer
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+class UserCountView(APIView):
+    """
+    A view that returns the count of active users in JSON.
+    """
+    renderer_classes = [JSONRenderer]
+
+    def get(self, request, format=None):
+        user_count = User.objects.filter(active=True).count()
+        content = {'user_count': user_count}
+        return Response(content)
+
+

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

+
@api_view(['GET'])
+@renderer_classes([JSONRenderer])
+def user_count_view(request, format=None):
+    """
+    A view that returns the count of active users in JSON.
+    """
+    user_count = User.objects.filter(active=True).count()
+    content = {'user_count': user_count}
+    return Response(content)
+
+

Ordering of renderer classes

+

It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an Accept: */* header, or not including an Accept header at all, then REST framework will select the first renderer in the list to use for the response.

+

For example if your API serves JSON responses and the HTML browsable API, you might want to make JSONRenderer your default renderer, in order to send JSON responses to clients that do not specify an Accept header.

+

If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making TemplateHTMLRenderer your default renderer, in order to play nicely with older browsers that send broken accept headers.

+
+

API Reference

+

JSONRenderer

+

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

+

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": "★",
+    "value": 999
+}
+
+

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

+

TemplateHTMLRenderer

+

Renders data to HTML, using Django's standard template rendering. +Unlike other renderers, the data passed to the Response does not need to be serialized. Also, unlike other renderers, you may want to include a template_name argument when creating the Response.

+

The TemplateHTMLRenderer will create a RequestContext, using the response.data as the context dict, and determine a template name to use to render the context.

+

The template name is determined by (in order of preference):

+
    +
  1. An explicit template_name argument passed to the response.
  2. +
  3. An explicit .template_name attribute set on this class.
  4. +
  5. The return result of calling view.get_template_names().
  6. +
+

An example of a view that uses TemplateHTMLRenderer:

+
class UserDetail(generics.RetrieveAPIView):
+    """
+    A view that returns a templated HTML representation of a given user.
+    """
+    queryset = User.objects.all()
+    renderer_classes = [TemplateHTMLRenderer]
+
+    def get(self, request, *args, **kwargs):
+        self.object = self.get_object()
+        return Response({'user': self.object}, template_name='user_detail.html')
+
+

You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.

+

If you're building websites that use TemplateHTMLRenderer along with other renderer classes, you should consider listing TemplateHTMLRenderer as the first class in the renderer_classes list, so that it will be prioritised first even for browsers that send poorly formed ACCEPT: headers.

+

See the HTML & Forms Topic Page for further examples of TemplateHTMLRenderer usage.

+

.media_type: text/html

+

.format: 'html'

+

.charset: utf-8

+

See also: StaticHTMLRenderer

+

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 StaticHTMLRenderer:

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

You can use StaticHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.

+

.media_type: text/html

+

.format: 'html'

+

.charset: utf-8

+

See also: TemplateHTMLRenderer

+

BrowsableAPIRenderer

+

Renders data into HTML for the Browsable API:

+

The BrowsableAPIRenderer

+

This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.

+

.media_type: text/html

+

.format: 'api'

+

.charset: utf-8

+

.template: 'rest_framework/api.html'

+

Customizing BrowsableAPIRenderer

+

By default the response content will be rendered with the highest priority renderer apart from BrowsableAPIRenderer. 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):
+    def get_default_renderer(self, view):
+        return JSONRenderer()
+
+

AdminRenderer

+

Renders data into HTML for an admin-like display:

+

The AdminRender view

+

This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.

+

Note that views that have nested or list serializers for their input won't work well with the AdminRenderer, as the HTML forms are unable to properly support them.

+

Note: The AdminRenderer is only able to include links to detail pages when a properly configured URL_FIELD_NAME (url by default) attribute is present in the data. For HyperlinkedModelSerializer this will be the case, but for ModelSerializer or plain Serializer classes you'll need to make sure to include the field explicitly. For example here we use models get_absolute_url method:

+
class AccountSerializer(serializers.ModelSerializer):
+    url = serializers.CharField(source='get_absolute_url', read_only=True)
+
+    class Meta:
+        model = Account
+
+

.media_type: text/html

+

.format: 'admin'

+

.charset: utf-8

+

.template: 'rest_framework/admin.html'

+

HTMLFormRenderer

+

Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <form> tags, a hidden CSRF input or any submit buttons.

+

This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the render_form template tag.

+
{% load rest_framework %}
+
+<form action="/submit-report/" method="post">
+    {% csrf_token %}
+    {% render_form serializer %}
+    <input type="submit" value="Save" />
+</form>
+
+

For more information see the HTML & Forms documentation.

+

.media_type: text/html

+

.format: 'form'

+

.charset: utf-8

+

.template: 'rest_framework/horizontal/form.html'

+

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.

+

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

+

.format: 'multipart'

+

.charset: utf-8

+
+

Custom renderers

+

To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method.

+

The method should return a bytestring, which will be used as the body of the HTTP response.

+

The arguments passed to the .render() method are:

+

data

+

The request data, as set by the Response() instantiation.

+

media_type=None

+

Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.

+

Depending on the client's Accept: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "application/json; nested=true".

+

renderer_context=None

+

Optional. If provided, this is a dictionary of contextual information provided by the view.

+

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 rest_framework import renderers
+
+
+class PlainTextRenderer(renderers.BaseRenderer):
+    media_type = 'text/plain'
+    format = 'txt'
+
+    def render(self, data, media_type=None, renderer_context=None):
+        return data.encode(self.charset)
+
+

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):
+    media_type = 'text/plain'
+    format = 'txt'
+    charset = 'iso-8859-1'
+
+    def render(self, data, media_type=None, renderer_context=None):
+        return data.encode(self.charset)
+
+

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):
+    media_type = 'image/jpeg'
+    format = 'jpg'
+    charset = None
+    render_style = 'binary'
+
+    def render(self, data, media_type=None, renderer_context=None):
+        return data
+
+
+

Advanced renderer usage

+

You can do some pretty flexible things using REST framework's renderers. Some examples...

+
    +
  • 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.
  • +
+

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'])
+@renderer_classes([TemplateHTMLRenderer, JSONRenderer])
+def list_users(request):
+    """
+    A view that can return JSON or HTML representations
+    of the users in the system.
+    """
+    queryset = Users.objects.filter(active=True)
+
+    if request.accepted_renderer.format == 'html':
+        # TemplateHTMLRenderer takes a context dict,
+        # and additionally requires a 'template_name'.
+        # It does not require serialization.
+        data = {'users': queryset}
+        return Response(data, template_name='list_users.html')
+
+    # JSONRenderer requires serialized data as normal.
+    serializer = UserSerializer(instance=queryset)
+    data = serializer.data
+    return Response(data)
+
+

Underspecifying the media type

+

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')
+
+

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.

+

In the words of Roy Fielding, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".

+

For good examples of custom media types, see GitHub's use of a custom application/vnd.github+json media type, and Mike Amundsen's IANA approved application/vnd.collection+json JSON-based hypermedia.

+

HTML error views

+

Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an Http404 or PermissionDenied exception, or a subclass of APIException.

+

If you're using either the TemplateHTMLRenderer or the StaticHTMLRenderer and an exception is raised, the behavior is slightly different, and mirrors Django's default handling of error views.

+

Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.

+
    +
  • Load and render a template named {status_code}.html.
  • +
  • Load and render a template named api_exception.html.
  • +
  • Render the HTTP status code and text, for example "404 Not Found".
  • +
+

Templates will render with a RequestContext which includes the status_code and details keys.

+

Note: If DEBUG=True, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.

+
+

Third party packages

+

The following third party packages are also available.

+

YAML

+

REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.

+

Installation & configuration

+

Install using pip.

+
$ pip install djangorestframework-yaml
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework_yaml.parsers.YAMLParser',
+    ],
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework_yaml.renderers.YAMLRenderer',
+    ],
+}
+
+

XML

+

REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.

+

Installation & configuration

+

Install using pip.

+
$ pip install djangorestframework-xml
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework_xml.parsers.XMLParser',
+    ],
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework_xml.renderers.XMLRenderer',
+    ],
+}
+
+

JSONP

+

REST framework JSONP provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.

+
+

Warning: If you require cross-domain AJAX requests, you should generally 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.

+
+

Installation & configuration

+

Install using pip.

+
$ pip install djangorestframework-jsonp
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework_jsonp.renderers.JSONPRenderer',
+    ],
+}
+
+

MessagePack

+

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

+

XLSX (Binary Spreadsheet Endpoints)

+

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

+

Installation & configuration

+

Install using pip.

+
$ pip install drf-renderer-xlsx
+
+

Modify your REST framework settings.

+
REST_FRAMEWORK = {
+    ...
+
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework.renderers.JSONRenderer',
+        'rest_framework.renderers.BrowsableAPIRenderer',
+        'drf_renderer_xlsx.renderers.XLSXRenderer',
+    ],
+}
+
+

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

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

CSV

+

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

+

UltraJSON

+

UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Jacob Haslehurst maintains the drf-ujson-renderer package which implements JSON rendering using the UJSON package.

+

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.

+

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.

+

LaTeX

+

Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software).

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html new file mode 100644 index 000000000..c6155630f --- /dev/null +++ b/api-guide/requests/index.html @@ -0,0 +1,631 @@ + + + + + + + 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 and request.FILES attributes except that:

+
    +
  • It includes all parsed content, including file and non-file inputs.
  • +
  • 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.

+

.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 Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests.

+

.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 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 serialization schemes for different media types.

+

.accepted_renderer

+

The renderer instance that 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.

+
+

Note: You may see a WrappedAttributeError raised when calling the .user or .auth properties. These errors originate from an authenticator as a standard AttributeError, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from the authenticator and will instead assume that the request object does not have a .user or .auth property. The authenticator will need to be fixed.

+
+

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.

+
+

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/index.html b/api-guide/responses/index.html new file mode 100644 index 000000000..33d760a48 --- /dev/null +++ b/api-guide/responses/index.html @@ -0,0 +1,591 @@ + + + + + + + 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, serialized data of the response.

+

.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/index.html b/api-guide/reverse/index.html new file mode 100644 index 000000000..0853a0f7c --- /dev/null +++ b/api-guide/reverse/index.html @@ -0,0 +1,530 @@ + + + + + + + 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.urls.reverse, except that it returns a fully qualified URL, using the request to determine the host and port.

+

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

+
from rest_framework.reverse import reverse
+from rest_framework.views import APIView
+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.urls.reverse_lazy, except that it returns a fully qualified URL, using the request to determine the host and port.

+

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

+
api_root = reverse_lazy('api-root', request=request)
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/routers/index.html b/api-guide/routers/index.html new file mode 100644 index 000000000..b45bcb3b5 --- /dev/null +++ b/api-guide/routers/index.html @@ -0,0 +1,801 @@ + + + + + + + Routers - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + 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

+
+

Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.

+

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
+
+router = routers.SimpleRouter()
+router.register(r'users', UserViewSet)
+router.register(r'accounts', AccountViewSet)
+urlpatterns = router.urls
+
+

There are two mandatory arguments to the register() method:

+
    +
  • prefix - The URL prefix to use for this set of routes.
  • +
  • viewset - The viewset class.
  • +
+

Optionally, you may also specify an additional argument:

+
    +
  • basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.
  • +
+

The example above would generate the following URL patterns:

+
    +
  • URL pattern: ^users/$ Name: 'user-list'
  • +
  • URL pattern: ^users/{pk}/$ Name: 'user-detail'
  • +
  • URL pattern: ^accounts/$ Name: 'account-list'
  • +
  • URL pattern: ^accounts/{pk}/$ Name: 'account-detail'
  • +
+
+

Note: The basename argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part.

+

Typically you won't need to specify the basename argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this:

+
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
+
+

This means you'll need to explicitly set the basename argument when registering the viewset, as it could not be automatically determined from the model name.

+
+

Using include with routers

+

The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.

+

For example, you can append router.urls to a list of existing views...

+
router = routers.SimpleRouter()
+router.register(r'users', UserViewSet)
+router.register(r'accounts', AccountViewSet)
+
+urlpatterns = [
+    url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
+]
+
+urlpatterns += router.urls
+
+

Alternatively you can use Django's include function, like so...

+
urlpatterns = [
+    url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
+    url(r'^', include(router.urls)),
+]
+
+

You may use include with an application namespace:

+
urlpatterns = [
+    url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
+    url(r'^api/', include((router.urls, 'app_name'))),
+]
+
+

Or both an application and instance namespace:

+
urlpatterns = [
+    url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
+    url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
+]
+
+

See Django's URL namespaces docs and the include API reference for more details.

+
+

Note: If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters +on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as +view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view.

+

The automatic view_name generation uses a pattern like %(model_name)-detail. Unless your models names actually clash +you may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.

+
+

Routing for extra actions

+

A viewset may mark extra actions for routing by decorating a method with the @action decorator. These extra actions will be included in the generated routes. For example, given the set_password method on the UserViewSet class:

+
from myapp.permissions import IsAdminOrIsSelf
+from rest_framework.decorators import action
+
+class UserViewSet(ModelViewSet):
+    ...
+
+    @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
+    def set_password(self, request, pk=None):
+        ...
+
+

The following route would be generated:

+
    +
  • URL pattern: ^users/{pk}/set_password/$
  • +
  • URL name: 'user-set-password'
  • +
+

By default, the URL pattern is based on the method name, and the URL name is the combination of the ViewSet.basename and the hyphenated method name. +If you don't want to use the defaults for either of these values, you can instead provide the url_path and url_name arguments to the @action decorator.

+

For example, if you want to change the URL for our custom action to ^users/{pk}/change-password/$, you could write:

+
from myapp.permissions import IsAdminOrIsSelf
+from rest_framework.decorators import action
+
+class UserViewSet(ModelViewSet):
+    ...
+
+    @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
+            url_path='change-password', url_name='change_password')
+    def set_password(self, request, pk=None):
+        ...
+
+

The above example would now generate the following URL pattern:

+
    +
  • URL path: ^users/{pk}/change-password/$
  • +
  • URL name: 'user-change_password'
  • +
+

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 @action decorator.

+ + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/GET, or as specified by `methods` argument`@action(detail=False)` decorated method{basename}-{url_name}
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{url_path}/GET, or as specified by `methods` argument`@action(detail=True)` decorated method{basename}-{url_name}
+ +

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)
+
+

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):
+    lookup_field = 'my_model_id'
+    lookup_value_regex = '[0-9a-f]{32}'
+
+

DefaultRouter

+

This router is similar to SimpleRouter as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional .json style format suffixes.

+ + + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
{prefix}/[.format]GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/[.format]GET, or as specified by `methods` argument`@action(detail=False)` decorated method{basename}-{url_name}
{prefix}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{url_path}/[.format]GET, or as specified by `methods` argument`@action(detail=True)` decorated method{basename}-{url_name}
+ +

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)
+
+

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

+

The simplest way to implement a custom router is to subclass one of the existing router classes. The .routes attribute is used to template the URL patterns that will be mapped to each viewset. The .routes attribute is a list of Route named tuples.

+

The arguments to the Route named tuple are:

+

url: A string representing the URL to be routed. May include the following format strings:

+
    +
  • {prefix} - The URL prefix to use for this set of routes.
  • +
  • {lookup} - The lookup field used to match against a single instance.
  • +
  • {trailing_slash} - Either a '/' or an empty string, depending on the trailing_slash argument.
  • +
+

mapping: A mapping of HTTP method names to the view methods

+

name: The name of the URL as used in reverse calls. May include the following format string:

+
    +
  • {basename} - The base to use for the URL names that are created.
  • +
+

initkwargs: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the detail, basename, and suffix arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.

+

Customizing dynamic routes

+

You can also customize how the @action decorator is routed. Include the DynamicRoute named tuple in the .routes list, setting the detail argument as appropriate for the list-based and detail-based routes. In addition to detail, the arguments to DynamicRoute are:

+

url: A string representing the URL to be routed. May include the same format strings as Route, and additionally accepts the {url_path} format string.

+

name: The name of the URL as used in reverse calls. May include the following format strings:

+
    +
  • {basename} - The base to use for the URL names that are created.
  • +
  • {url_name} - The url_name provided to the @action.
  • +
+

initkwargs: 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, DynamicRoute, SimpleRouter
+
+class CustomReadOnlyRouter(SimpleRouter):
+    """
+    A router for read-only APIs, which doesn't use trailing slashes.
+    """
+    routes = [
+        Route(
+            url=r'^{prefix}$',
+            mapping={'get': 'list'},
+            name='{basename}-list',
+            detail=False,
+            initkwargs={'suffix': 'List'}
+        ),
+        Route(
+            url=r'^{prefix}/{lookup}$',
+            mapping={'get': 'retrieve'},
+            name='{basename}-detail',
+            detail=True,
+            initkwargs={'suffix': 'Detail'}
+        ),
+        DynamicRoute(
+            url=r'^{prefix}/{lookup}/{url_path}$',
+            name='{basename}-{url_name}',
+            detail=True,
+            initkwargs={}
+        )
+    ]
+
+

Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.

+

views.py:

+
class UserViewSet(viewsets.ReadOnlyModelViewSet):
+    """
+    A viewset that provides the standard actions
+    """
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+    lookup_field = 'username'
+
+    @action(detail=True)
+    def group_names(self, request, pk=None):
+        """
+        Returns a list of all the group names that the given
+        user belongs to.
+        """
+        user = self.get_object()
+        groups = user.groups.all()
+        return Response([group.name for group in groups])
+
+

urls.py:

+
router = CustomReadOnlyRouter()
+router.register('users', UserViewSet)
+urlpatterns = router.urls
+
+

The following mappings would be generated...

+ + + + + +
URLHTTP MethodActionURL Name
/usersGETlistuser-list
/users/{username}GETretrieveuser-detail
/users/{username}/group_namesGETgroup_namesuser-group-names
+ +

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.

+

You may also want to override the get_default_basename(self, viewset) method, or else always explicitly set the basename argument when registering your viewsets with the router.

+

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.

+

ModelRouter (wq.db.rest)

+

The wq.db package provides an advanced ModelRouter class (and singleton instance) that extends DefaultRouter with a register_model() API. Much like Django's admin.site.register, the only required argument to rest.router.register_model is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.

+
from wq.db import rest
+from myapp.models import MyModel
+
+rest.router.register_model(MyModel)
+
+

DRF-extensions

+

The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/schemas/index.html b/api-guide/schemas/index.html new file mode 100644 index 000000000..767711b46 --- /dev/null +++ b/api-guide/schemas/index.html @@ -0,0 +1,670 @@ + + + + + + + Schemas - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + schemas + + + + +

Schema

+
+

A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.

+

— Heroku, [JSON Schema for the Heroku Platform API][cite]

+
+

API schemas are a useful tool that allow for a range of use cases, including +generating reference documentation, or driving dynamic client libraries that +can interact with your API.

+

Django REST Framework provides support for automatic generation of +OpenAPI schemas.

+

Generating an OpenAPI Schema

+

Install pyyaml

+

You'll need to install pyyaml, so that you can render your generated schema +into the commonly used YAML-based OpenAPI format.

+
pip install pyyaml
+
+

Generating a static schema with the generateschema management command

+

If your schema is static, you can use the generateschema management command:

+
./manage.py generateschema > openapi-schema.yml
+
+ +

Once you've generated a schema in this way you can annotate it with any +additional information that cannot be automatically inferred by the schema +generator.

+

You might want to check your API schema into version control and update it +with each new release, or serve the API schema from your site's static media.

+

Generating a dynamic schema with SchemaView

+

If you require a dynamic schema, because foreign key choices depend on database +values, for example, you can route a SchemaView that will generate and serve +your schema on demand.

+

To route a SchemaView, use the get_schema_view() helper.

+

In urls.py:

+
from rest_framework.schemas import get_schema_view
+
+urlpatterns = [
+    # ...
+    # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
+    #   * `title` and `description` parameters are passed to `SchemaGenerator`.
+    #   * Provide view name for use with `reverse()`.
+    path('openapi', get_schema_view(
+        title="Your Project",
+        description="API for all things …",
+        version="1.0.0"
+    ), name='openapi-schema'),
+    # ...
+]
+
+ +

get_schema_view()

+

The get_schema_view() helper takes the following keyword arguments:

+
    +
  • title: May be used to provide a descriptive title for the schema definition.
  • +
  • description: Longer descriptive text.
  • +
  • version: The version of the API.
  • +
  • +

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

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

    urlconf: A string representing the import path to the URL conf that you want + to generate an API schema for. This defaults to the value of Django's + ROOT_URLCONF setting.

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

    patterns: List of url patterns to limit the schema introspection to. If you + only want the myproject.api urls to be exposed in the schema:

    +
    schema_url_patterns = [
    +    url(r'^api/', include('myproject.api.urls')),
    +]
    +
    +schema_view = get_schema_view(
    +    title='Server Monitoring API',
    +    url='https://www.example.org/api/',
    +    patterns=schema_url_patterns,
    +)
    +
    +
  • +
  • +

    generator_class: May be used to specify a SchemaGenerator subclass to be + passed to the SchemaView.

    +
  • +
  • authentication_classes: May be used to specify the list of authentication + classes that will apply to the schema endpoint. Defaults to + settings.DEFAULT_AUTHENTICATION_CLASSES
  • +
  • permission_classes: May be used to specify the list of permission classes + that will apply to the schema endpoint. Defaults to + settings.DEFAULT_PERMISSION_CLASSES.
  • +
  • renderer_classes: May be used to pass the set of renderer classes that can + be used to render the API root endpoint.
  • +
+

Customizing Schema Generation

+

You may customize schema generation at the level of the schema as a whole, or +on a per-view basis.

+

Schema Level Customization

+

In order to customize the top-level schema sublass +rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument +to the generateschema command or get_schema_view() helper function.

+

SchemaGenerator

+

A class that walks a list of routed URL patterns, requests the schema for each +view and collates the resulting OpenAPI schema.

+

Typically you'll instantiate SchemaGenerator with a title argument, like so:

+
generator = SchemaGenerator(title='Stock Prices API')
+
+

Arguments:

+
    +
  • title required: The name of the API.
  • +
  • description: Longer descriptive text.
  • +
  • version: The version of the API. Defaults to 0.1.0.
  • +
  • url: The root URL of the API schema. This option is not required unless the schema is included under path prefix.
  • +
  • patterns: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
  • +
  • urlconf: A URL conf module name to use when generating the schema. Defaults to settings.ROOT_URLCONF.
  • +
+
get_schema(self, request)
+

Returns a dictionary that represents the OpenAPI schema:

+
generator = SchemaGenerator(title='Stock Prices API')
+schema = generator.get_schema()
+
+

The request argument is optional, and may be used if you want to apply +per-user permissions to the resulting schema generation.

+

This is a good point to override if you want to customize the generated +dictionary, for example to add custom +specification extensions.

+

Per-View Customization

+

By default, view introspection is performed by an AutoSchema instance +accessible via the schema attribute on APIView. This provides the +appropriate Open API operation object for the view, +request method and path:

+
auto_schema = view.schema
+operation = auto_schema.get_operation(...)
+
+

In compiling the schema, SchemaGenerator calls view.schema.get_operation() +for each view, allowed method, and path.

+
+

Note: For basic APIView subclasses, default introspection is essentially +limited to the URL kwarg path parameters. For GenericAPIView +subclasses, which includes all the provided class based views, AutoSchema will +attempt to introspect serializer, pagination and filter fields, as well as +provide richer path field descriptions. (The key hooks here are the relevant +GenericAPIView attributes and methods: get_serializer, pagination_class, +filter_backends and so on.)

+
+

In order to customize the operation generation, you should provide an AutoSchema subclass, overriding get_operation() as you need:

+
    from rest_framework.views import APIView
+    from rest_framework.schemas.openapi import AutoSchema
+
+    class CustomSchema(AutoSchema):
+        def get_operation(...):
+            # Implement custom introspection here (or in other sub-methods)
+
+    class CustomView(APIView):
+        """APIView subclass with custom schema introspection."""
+        schema = CustomSchema()
+
+

This provides complete control over view introspection.

+

You may disable schema generation for a view by setting schema to None:

+
class CustomView(APIView):
+    ...
+    schema = None  # Will not appear in schema
+
+

This also applies to extra actions for ViewSets:

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

If you wish to provide a base AutoSchema subclass to be used throughout your +project you may adjust settings.DEFAULT_SCHEMA_CLASS appropriately.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html new file mode 100644 index 000000000..dd4763d03 --- /dev/null +++ b/api-guide/serializers/index.html @@ -0,0 +1,1588 @@ + + + + + + + Serializers - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + 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 +will take some serious design work.

+

— Russell Keith-Magee, Django users group

+
+

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

+

The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide 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:

+
from datetime import datetime
+
+class Comment(object):
+    def __init__(self, email, content, created=None):
+        self.email = email
+        self.content = content
+        self.created = created or datetime.now()
+
+comment = Comment(email='leila@example.com', content='foo bar')
+
+

We'll declare a serializer that we can use to serialize and deserialize data that corresponds to Comment objects.

+

Declaring a serializer looks very similar to declaring a form:

+
from rest_framework import serializers
+
+class CommentSerializer(serializers.Serializer):
+    email = serializers.EmailField()
+    content = serializers.CharField(max_length=200)
+    created = serializers.DateTimeField()
+
+

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.data
+# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
+
+

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
+
+json = JSONRenderer().render(serializer.data)
+json
+# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
+
+

Deserializing objects

+

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

+
import io
+from rest_framework.parsers import JSONParser
+
+stream = io.BytesIO(json)
+data = JSONParser().parse(stream)
+
+

...then we restore those native datatypes into a dictionary of validated data.

+
serializer = CommentSerializer(data=data)
+serializer.is_valid()
+# True
+serializer.validated_data
+# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
+
+

Saving instances

+

If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and .update() methods. For example:

+
class CommentSerializer(serializers.Serializer):
+    email = serializers.EmailField()
+    content = serializers.CharField(max_length=200)
+    created = serializers.DateTimeField()
+
+    def create(self, validated_data):
+        return Comment(**validated_data)
+
+    def update(self, instance, validated_data):
+        instance.email = validated_data.get('email', instance.email)
+        instance.content = validated_data.get('content', instance.content)
+        instance.created = validated_data.get('created', instance.created)
+        return instance
+
+

If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this:

+
    def create(self, validated_data):
+        return Comment.objects.create(**validated_data)
+
+    def update(self, instance, validated_data):
+        instance.email = validated_data.get('email', instance.email)
+        instance.content = validated_data.get('content', instance.content)
+        instance.created = validated_data.get('created', instance.created)
+        instance.save()
+        return instance
+
+

Now when deserializing data, we can call .save() to return an object instance, based on the validated data.

+
comment = serializer.save()
+
+

Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:

+
# .save() will create a new instance.
+serializer = CommentSerializer(data=data)
+
+# .save() will update the existing `comment` instance.
+serializer = CommentSerializer(comment, data=data)
+
+

Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.

+

Passing additional attributes to .save()

+

Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.

+

You can do so by including additional keyword arguments when calling .save(). For example:

+
serializer.save(owner=request.user)
+
+

Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.

+

Overriding .save() directly.

+

In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.

+

In these cases you might instead choose to override .save() directly, as being more readable and meaningful.

+

For example:

+
class ContactForm(serializers.Serializer):
+    email = serializers.EmailField()
+    message = serializers.CharField()
+
+    def save(self):
+        email = self.validated_data['email']
+        message = self.validated_data['message']
+        send_email(from=email, message=message)
+
+

Note that in the case above we're now having to access the serializer .validated_data property directly.

+

Validation

+

When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. 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.is_valid()
+# False
+serializer.errors
+# {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']}
+
+

Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting.

+

When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.

+

Raising an exception on invalid data

+

The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.

+

These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default.

+
# Return a 400 response if the data was invalid.
+serializer.is_valid(raise_exception=True)
+
+

Field-level validation

+

You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. These are similar to the .clean_<field_name> methods on Django forms.

+

These methods take a single argument, which is the field value that requires validation.

+

Your validate_<field_name> methods should return the validated value or raise a serializers.ValidationError. For example:

+
from rest_framework import serializers
+
+class BlogPostSerializer(serializers.Serializer):
+    title = serializers.CharField(max_length=100)
+    content = serializers.CharField()
+
+    def validate_title(self, value):
+        """
+        Check that the blog post is about Django.
+        """
+        if 'django' not in value.lower():
+            raise serializers.ValidationError("Blog post is not about Django")
+        return value
+
+
+

Note: If your <field_name> is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included.

+
+

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 a dictionary of field values. It should raise a serializers.ValidationError if necessary, or just return the validated values. For example:

+
from rest_framework import serializers
+
+class EventSerializer(serializers.Serializer):
+    description = serializers.CharField(max_length=100)
+    start = serializers.DateTimeField()
+    finish = serializers.DateTimeField()
+
+    def validate(self, data):
+        """
+        Check that start is before finish.
+        """
+        if data['start'] > data['finish']:
+            raise serializers.ValidationError("finish must occur after start")
+        return data
+
+

Validators

+

Individual fields on a serializer can include validators, by declaring them on the field instance, for example:

+
def multiple_of_ten(value):
+    if value % 10 != 0:
+        raise serializers.ValidationError('Not a multiple of ten')
+
+class GameRecord(serializers.Serializer):
+    score = IntegerField(validators=[multiple_of_ten])
+    ...
+
+

Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so:

+
class EventSerializer(serializers.Serializer):
+    name = serializers.CharField()
+    room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
+    date = serializers.DateField()
+
+    class Meta:
+        # Each room only has one event per day.
+        validators = UniqueTogetherValidator(
+            queryset=Event.objects.all(),
+            fields=['room_number', 'date']
+        )
+
+

For more information see the validators documentation.

+

Accessing the initial data and instance

+

When passing an initial object or queryset to a serializer instance, the object will be made available as .instance. If no initial object is passed then the .instance attribute will be None.

+

When passing data to a serializer instance, the unmodified data will be made available as .initial_data. If the data keyword argument is not passed then the .initial_data attribute will not exist.

+

Partial updates

+

By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial argument in order to allow partial updates.

+
# Update `comment` with partial data
+serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
+
+

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):
+    email = serializers.EmailField()
+    username = serializers.CharField(max_length=100)
+
+class CommentSerializer(serializers.Serializer):
+    user = UserSerializer()
+    content = serializers.CharField(max_length=200)
+    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):
+    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):
+    user = UserSerializer(required=False)
+    edits = EditItemSerializer(many=True)  # A nested list of 'edit' items.
+    content = serializers.CharField(max_length=200)
+    created = serializers.DateTimeField()
+
+

Writable nested representations

+

When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.

+
serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
+serializer.is_valid()
+# False
+serializer.errors
+# {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']}
+
+

Similarly, the .validated_data property will include nested data structures.

+

Writing .create() methods for nested representations

+

If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects.

+

The following example demonstrates how you might handle creating a user with a nested profile object.

+
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
+
+

Writing .update() methods for nested representations

+

For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None, or not provided, which of the following should occur?

+
    +
  • Set the relationship to NULL in the database.
  • +
  • Delete the associated instance.
  • +
  • Ignore the data and leave the instance as it is.
  • +
  • Raise a validation error.
  • +
+

Here's an example for an .update() method on our previous UserSerializer class.

+
    def update(self, instance, validated_data):
+        profile_data = validated_data.pop('profile')
+        # Unless the application properly enforces that this field is
+        # always set, the follow could raise a `DoesNotExist`, which
+        # would need to be handled.
+        profile = instance.profile
+
+        instance.username = validated_data.get('username', instance.username)
+        instance.email = validated_data.get('email', instance.email)
+        instance.save()
+
+        profile.is_premium_member = profile_data.get(
+            'is_premium_member',
+            profile.is_premium_member
+        )
+        profile.has_support_contract = profile_data.get(
+            'has_support_contract',
+            profile.has_support_contract
+         )
+        profile.save()
+
+        return instance
+
+

Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations.

+

There are however, third-party packages available such as DRF Writable Nested that support automatic writable nested representations.

+ +

An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.

+

For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this:

+
class UserManager(models.Manager):
+    ...
+
+    def create(self, username, email, is_premium_member=False, has_support_contract=False):
+        user = User(username=username, email=email)
+        user.save()
+        profile = Profile(
+            user=user,
+            is_premium_member=is_premium_member,
+            has_support_contract=has_support_contract
+        )
+        profile.save()
+        return user
+
+

This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method.

+
def create(self, validated_data):
+    return User.objects.create(
+        username=validated_data['username'],
+        email=validated_data['email']
+        is_premium_member=validated_data['profile']['is_premium_member']
+        has_support_contract=validated_data['profile']['has_support_contract']
+    )
+
+

For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.

+

Dealing with multiple objects

+

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()
+serializer = BookSerializer(queryset, many=True)
+serializer.data
+# [
+#     {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
+#     {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
+#     {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
+# ]
+
+

Deserializing multiple objects

+

The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the ListSerializer documentation below.

+

Including extra context

+

There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.

+

You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example:

+
serializer = AccountSerializer(account, context={'request': request})
+serializer.data
+# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
+
+

The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.

+
+

ModelSerializer

+

Often you'll want serializer classes that map closely to Django model definitions.

+

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.

+

The ModelSerializer class is the same as a regular Serializer class, except that:

+
    +
  • It will automatically generate a set of fields for you, based on the model.
  • +
  • It will automatically generate validators for the serializer, such as unique_together validators.
  • +
  • It includes simple default implementations of .create() and .update().
  • +
+

Declaring a ModelSerializer looks like this:

+
class AccountSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Account
+        fields = ['id', 'account_name', 'users', 'created']
+
+

By default, all the model fields on the class will be mapped to a corresponding serializer fields.

+

Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField. Reverse relationships are not included by default unless explicitly included as specified in the serializer relations documentation.

+

Inspecting a ModelSerializer

+

Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with ModelSerializers where you want to determine what set of fields and validators are being automatically created for you.

+

To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation…

+
>>> from myapp.serializers import AccountSerializer
+>>> serializer = AccountSerializer()
+>>> print(repr(serializer))
+AccountSerializer():
+    id = IntegerField(label='ID', read_only=True)
+    name = CharField(allow_blank=True, max_length=100, required=False)
+    owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
+

Specifying which fields to include

+

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. It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change.

+

For example:

+
class AccountSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Account
+        fields = ['id', 'account_name', 'users', 'created']
+
+

You can also set the fields attribute to the special value '__all__' to indicate that all fields in the model should be used.

+

For example:

+
class AccountSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Account
+        fields = '__all__'
+
+

You can set the exclude attribute to a list of fields to be excluded from the serializer.

+

For example:

+
class AccountSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Account
+        exclude = ['users']
+
+

In the example above, if the Account model had 3 fields account_name, users, and created, this will result in the fields account_name and created to be serialized.

+

The names in the fields and exclude attributes will normally map to model fields on the model class.

+

Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class.

+

Since version 3.3.0, it is mandatory to provide one of the attributes fields or exclude.

+

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 Meta:
+        model = Account
+        fields = ['id', 'account_name', 'users', 'created']
+        depth = 1
+
+

The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.

+

If you want to customize the way the serialization is done you'll need to define the field yourself.

+

Specifying fields explicitly

+

You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.

+
class AccountSerializer(serializers.ModelSerializer):
+    url = serializers.CharField(source='get_absolute_url', read_only=True)
+    groups = serializers.PrimaryKeyRelatedField(many=True)
+
+    class Meta:
+        model = Account
+
+

Extra fields can correspond to any property or callable on the model.

+

Specifying read only fields

+

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 shortcut Meta option, read_only_fields.

+

This option should be a list or tuple of field names, and is declared as follows:

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

+
+

Note: There is a special-case where a read-only field is part of a unique_together constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.

+

The right way to deal with this is to specify the field explicitly on the serializer, providing both the read_only=True and default=… keyword arguments.

+

One example of this is a read-only relation to the currently authenticated User which is unique_together with another identifier. In this case you would declare the user field like so:

+
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
+
+

Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.

+
+

Additional keyword arguments

+

There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option. As in the case of read_only_fields, this means you do not need to explicitly declare the field on the serializer.

+

This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:

+
class CreateUserSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = User
+        fields = ['email', 'username', 'password']
+        extra_kwargs = {'password': {'write_only': True}}
+
+    def create(self, validated_data):
+        user = User(
+            email=validated_data['email'],
+            username=validated_data['username']
+        )
+        user.set_password(validated_data['password'])
+        user.save()
+        return user
+
+

Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the extra_kwargs option will be ignored.

+

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.

+

Customizing field mappings

+

The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.

+

Normally if a ModelSerializer does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular Serializer class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.

+

.serializer_field_mapping

+

A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.

+ +

This property should be the serializer field class, that is used for relational fields by default.

+

For ModelSerializer this defaults to PrimaryKeyRelatedField.

+

For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField.

+

serializer_url_field

+

The serializer field class that should be used for any url field on the serializer.

+

Defaults to serializers.HyperlinkedIdentityField

+

serializer_choice_field

+

The serializer field class that should be used for any choice fields on the serializer.

+

Defaults to serializers.ChoiceField

+

The field_class and field_kwargs API

+

The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of (field_class, field_kwargs).

+

.build_standard_field(self, field_name, model_field)

+

Called to generate a serializer field that maps to a standard model field.

+

The default implementation returns a serializer class based on the serializer_field_mapping attribute.

+

.build_relational_field(self, field_name, relation_info)

+

Called to generate a serializer field that maps to a relational model field.

+

The default implementation returns a serializer class based on the serializer_related_field attribute.

+

The relation_info argument is a named tuple, that contains model_field, related_model, to_many and has_through_model properties.

+

.build_nested_field(self, field_name, relation_info, nested_depth)

+

Called to generate a serializer field that maps to a relational model field, when the depth option has been set.

+

The default implementation dynamically creates a nested serializer class based on either ModelSerializer or HyperlinkedModelSerializer.

+

The nested_depth will be the value of the depth option, minus one.

+

The relation_info argument is a named tuple, that contains model_field, related_model, to_many and has_through_model properties.

+

.build_property_field(self, field_name, model_class)

+

Called to generate a serializer field that maps to a property or zero-argument method on the model class.

+

The default implementation returns a ReadOnlyField class.

+

.build_url_field(self, field_name, model_class)

+

Called to generate a serializer field for the serializer's own url field. The default implementation returns a HyperlinkedIdentityField class.

+

.build_unknown_field(self, field_name, model_class)

+

Called when the field name did not map to any model field or model property. +The default implementation raises an error, although subclasses may customize this behavior.

+
+

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 Meta:
+        model = Account
+        fields = ['url', 'id', 'account_name', 'users', 'created']
+
+

Absolute and relative URLs

+

When instantiating a HyperlinkedModelSerializer you must include the current +request in the serializer context, for example:

+
serializer = AccountSerializer(queryset, context={'request': request})
+
+

Doing so will ensure that the hyperlinks can include an appropriate hostname, +so that the resulting representation uses fully qualified URLs, such as:

+
http://api.example.com/accounts/1/
+
+

Rather than relative URLs, such as:

+
/accounts/1/
+
+

If you do want to use relative URLs, you should explicitly pass {'request': None} +in the serializer context.

+

How hyperlinked views are determined

+

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 override a URL field view name and lookup field by using either, or both of, the view_name and lookup_field options in the extra_kwargs setting, like so:

+
class AccountSerializer(serializers.HyperlinkedModelSerializer):
+    class Meta:
+        model = Account
+        fields = ['account_url', 'account_name', 'users', 'created']
+        extra_kwargs = {
+            'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},
+            'users': {'lookup_field': 'username'}
+        }
+
+

Alternatively you can set the fields on the serializer explicitly. For example:

+
class AccountSerializer(serializers.HyperlinkedModelSerializer):
+    url = serializers.HyperlinkedIdentityField(
+        view_name='accounts',
+        lookup_field='slug'
+    )
+    users = serializers.HyperlinkedRelatedField(
+        view_name='user-detail',
+        lookup_field='username',
+        many=True,
+        read_only=True
+    )
+
+    class Meta:
+        model = Account
+        fields = ['url', 'account_name', 'users', 'created']
+
+
+

Tip: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the repr of a HyperlinkedModelSerializer instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.

+
+

Changing the URL field name

+

The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.

+
+

ListSerializer

+

The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer.

+

When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer

+

The following argument can also be passed to a ListSerializer field or a serializer that is passed many=True:

+

allow_empty

+

This is True by default, but can be set to False if you want to disallow empty lists as valid input.

+

Customizing ListSerializer behavior

+

There are a few use cases when you might want to customize the ListSerializer behavior. For example:

+
    +
  • You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.
  • +
  • You want to customize the create or update behavior of multiple objects.
  • +
+

For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class.

+

For example:

+
class CustomListSerializer(serializers.ListSerializer):
+    ...
+
+class CustomSerializer(serializers.Serializer):
+    ...
+    class Meta:
+        list_serializer_class = CustomListSerializer
+
+

Customizing multiple create

+

The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed.

+

For example:

+
class BookListSerializer(serializers.ListSerializer):
+    def create(self, validated_data):
+        books = [Book(**item) for item in validated_data]
+        return Book.objects.bulk_create(books)
+
+class BookSerializer(serializers.Serializer):
+    ...
+    class Meta:
+        list_serializer_class = BookListSerializer
+
+

Customizing multiple update

+

By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.

+

To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:

+
    +
  • How do you determine which instance should be updated for each item in the list of data?
  • +
  • How should insertions be handled? Are they invalid, or do they create new objects?
  • +
  • How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?
  • +
  • How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
  • +
+

You will need to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's update method.

+

Here's an example of how you might choose to implement multiple updates:

+
class BookListSerializer(serializers.ListSerializer):
+    def update(self, instance, validated_data):
+        # Maps for id->instance and id->data item.
+        book_mapping = {book.id: book for book in instance}
+        data_mapping = {item['id']: item for item in validated_data}
+
+        # Perform creations and updates.
+        ret = []
+        for book_id, data in data_mapping.items():
+            book = book_mapping.get(book_id, None)
+            if book is None:
+                ret.append(self.child.create(data))
+            else:
+                ret.append(self.child.update(book, data))
+
+        # Perform deletions.
+        for book_id, book in book_mapping.items():
+            if book_id not in data_mapping:
+                book.delete()
+
+        return ret
+
+class BookSerializer(serializers.Serializer):
+    # We need to identify elements in the list using their primary key,
+    # so use a writable field here, rather than the default which would be read-only.
+    id = serializers.IntegerField()
+    ...
+
+    class Meta:
+        list_serializer_class = BookListSerializer
+
+

It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the allow_add_remove behavior that was present in REST framework 2.

+

Customizing ListSerializer initialization

+

When a serializer with many=True is instantiated, we need to determine which arguments and keyword arguments should be passed to the .__init__() method for both the child Serializer class, and for the parent ListSerializer class.

+

The default implementation is to pass all arguments to both classes, except for validators, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.

+

Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when many=True is passed. You can do so by using the many_init class method.

+
    @classmethod
+    def many_init(cls, *args, **kwargs):
+        # Instantiate the child serializer.
+        kwargs['child'] = cls()
+        # Instantiate the parent list serializer.
+        return CustomListSerializer(*args, **kwargs)
+
+
+

BaseSerializer

+

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 any errors during validation.
  • +
  • .save() - Persists the validated data into an object instance.
  • +
+

There are four methods that can be overridden, depending on what functionality you want the serializer class to support:

+
    +
  • .to_representation() - Override this to support serialization, for read operations.
  • +
  • .to_internal_value() - Override this to support deserialization, for write operations.
  • +
  • .create() and .update() - Override either or both of these to support saving instances.
  • +
+

Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer.

+

The only difference you'll notice when doing so is the BaseSerializer classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.

+
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, instance):
+        return {
+            'score': instance.score,
+            'player_name': instance.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 serializers.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 serializers.ValidationError({
+                'score': 'This field is required.'
+            })
+        if not player_name:
+            raise serializers.ValidationError({
+                'player_name': 'This field is required.'
+            })
+        if len(player_name) > 10:
+            raise serializers.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, instance):
+        return {
+            'score': instance.score,
+            'player_name': instance.player_name
+        }
+
+    def create(self, validated_data):
+        return HighScore.objects.create(**validated_data)
+
+

Creating new base classes

+

The BaseSerializer class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.

+

The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.

+
class ObjectSerializer(serializers.BaseSerializer):
+    """
+    A read-only serializer that coerces arbitrary complex objects
+    into primitive representations.
+    """
+    def to_representation(self, instance):
+        output = {}
+        for attribute_name in dir(instance):
+            attribute = getattr(instance, attribute_name)
+            if attribute_name.startswith('_'):
+                # 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):
+                # Recursively deal with items in lists.
+                output[attribute_name] = [
+                    self.to_representation(item) for item in attribute
+                ]
+            elif isinstance(attribute, dict):
+                # Recursively deal with items in dictionaries.
+                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)
+        return output
+
+
+

Advanced serializer usage

+

Overriding serialization and deserialization behavior

+

If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the .to_representation() or .to_internal_value() methods.

+

Some reasons this might be useful include...

+
    +
  • Adding new behavior for new serializer base classes.
  • +
  • Modifying the behavior slightly for an existing class.
  • +
  • Improving serialization performance for a frequently accessed API endpoint that returns lots of data.
  • +
+

The signatures for these methods are as follows:

+

.to_representation(self, instance)

+

Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.

+

May be overridden in order to modify the representation style. For example:

+
def to_representation(self, instance):
+    """Convert `username` to lowercase."""
+    ret = super().to_representation(instance)
+    ret['username'] = ret['username'].lower()
+    return ret
+
+

.to_internal_value(self, data)

+

Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data. The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class.

+

If any of the validation fails, then the method should raise a serializers.ValidationError(errors). The errors argument should be a dictionary mapping field names (or settings.NON_FIELD_ERRORS_KEY) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the .validate() method.

+

The data argument passed to this method will normally be the value of request.data, so the datatype it provides will depend on the parser classes you have configured for your API.

+

Serializer Inheritance

+

Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,

+
class MyBaseSerializer(Serializer):
+    my_field = serializers.CharField()
+
+    def validate_my_field(self, value):
+        ...
+
+class MySerializer(MyBaseSerializer):
+    ...
+
+

Like Django's Model and ModelForm classes, the inner Meta class on serializers does not implicitly inherit from it's parents' inner Meta classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:

+
class AccountSerializer(MyBaseSerializer):
+    class Meta(MyBaseSerializer.Meta):
+        model = Account
+
+

Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly.

+

Additionally, the following caveats apply to serializer inheritance:

+
    +
  • Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child’s Meta, if it exists, otherwise the Meta of the first parent, etc.
  • +
  • +

    It’s possible to declaratively remove a Field inherited from a parent class by setting the name to be None on the subclass.

    +
    class MyBaseSerializer(ModelSerializer):
    +    my_field = serializers.CharField()
    +
    +class MySerializer(MyBaseSerializer):
    +    my_field = None
    +
    +

    However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won’t prevent the ModelSerializer from generating a default field. To opt-out from default fields, see Specifying which fields to include.

    +
  • +
+

Dynamically modifying fields

+

Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.

+

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):
+    """
+    A ModelSerializer that takes an additional `fields` argument that
+    controls which fields should be displayed.
+    """
+
+    def __init__(self, *args, **kwargs):
+        # Don't pass the 'fields' arg up to the superclass
+        fields = kwargs.pop('fields', None)
+
+        # Instantiate the superclass normally
+        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
+
+        if fields is not None:
+            # Drop any fields that are not specified in the `fields` argument.
+            allowed = set(fields)
+            existing = set(self.fields)
+            for field_name in existing - allowed:
+                self.fields.pop(field_name)
+
+

This would then allow you to do the following:

+
>>> class UserSerializer(DynamicFieldsModelSerializer):
+>>>     class Meta:
+>>>         model = User
+>>>         fields = ['id', 'username', 'email']
+>>>
+>>> print(UserSerializer(user))
+{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
+>>>
+>>> print(UserSerializer(user, fields=('id', 'email')))
+{'id': 2, 'email': 'jon@example.com'}
+
+

Customizing the default fields

+

REST framework 2 provided an API to allow developers to override how a ModelSerializer class would automatically generate the default set of fields.

+

This API included the .get_field(), .get_pk_field() and other methods.

+

Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.

+
+

Third party packages

+

The following third party packages are also available.

+

Django REST marshmallow

+

The django-rest-marshmallow package provides an alternative implementation for serializers, using the python marshmallow library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.

+

Serpy

+

The serpy package is an alternative implementation for serializers that is built for speed. Serpy serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.

+

MongoengineModelSerializer

+

The django-rest-framework-mongoengine package provides a MongoEngineModelSerializer serializer class that supports using MongoDB as the storage layer for Django REST framework.

+

GeoFeatureModelSerializer

+

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.

+

Dynamic REST

+

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

+

Dynamic Fields Mixin

+

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

+

DRF FlexFields

+

The drf-flex-fields package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.

+

Serializer Extensions

+

The django-rest-framework-serializer-extensions +package provides a collection of tools to DRY up your serializers, by allowing +fields to be defined on a per-view/request basis. Fields can be whitelisted, +blacklisted and child serializers can be optionally expanded.

+

HTML JSON Forms

+

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

+

DRF-Base64

+

DRF-Base64 provides a set of field and model serializers that handles the upload of base64-encoded files.

+

QueryFields

+

djangorestframework-queryfields allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.

+

DRF Writable Nested

+

The drf-writable-nested package provides writable nested model serializer which allows to create/update models with nested related data.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html new file mode 100644 index 000000000..05e9ee0b6 --- /dev/null +++ b/api-guide/settings/index.html @@ -0,0 +1,812 @@ + + + + + + + Settings - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + 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 = {
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework.renderers.JSONRenderer',
+    ],
+    'DEFAULT_PARSER_CLASSES': [
+        'rest_framework.parsers.JSONParser',
+    ]
+}
+
+

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
+
+print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
+
+

The api_settings object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.

+
+

API Reference

+

API policy settings

+

The following settings control the basic API policies, and are applied to every APIView class-based view, or @api_view function based view.

+

DEFAULT_RENDERER_CLASSES

+

A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object.

+

Default:

+
[
+    'rest_framework.renderers.JSONRenderer',
+    'rest_framework.renderers.BrowsableAPIRenderer',
+]
+
+

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'
+]
+
+

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. Permission must be granted by every class in the list.

+

Default:

+
[
+    'rest_framework.permissions.AllowAny',
+]
+
+

DEFAULT_THROTTLE_CLASSES

+

A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.

+

Default: []

+

DEFAULT_CONTENT_NEGOTIATION_CLASS

+

A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.

+

Default: 'rest_framework.negotiation.DefaultContentNegotiation'

+

DEFAULT_SCHEMA_CLASS

+

A view inspector class that will be used for schema generation.

+

Default: 'rest_framework.schemas.openapi.AutoSchema'

+
+

Generic view settings

+

The following settings control the behavior of the generic class-based views.

+

DEFAULT_FILTER_BACKENDS

+

A list of filter backend classes that should be used for generic filtering. +If set to None then generic filtering is disabled.

+

DEFAULT_PAGINATION_CLASS

+

The default class to use for queryset pagination. If set to None, pagination +is disabled by default. See the pagination documentation for further guidance on +setting and +modifying the pagination style.

+

Default: None

+

PAGE_SIZE

+

The default page size to use for pagination. If set to None, pagination is disabled by default.

+

Default: None

+

SEARCH_PARAM

+

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 parameter, which can be used to specify the ordering of results returned by OrderingFilter.

+

Default: ordering

+
+

Versioning settings

+

DEFAULT_VERSION

+

The value that should be used for request.version when no versioning information is present.

+

Default: None

+

ALLOWED_VERSIONS

+

If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.

+

Default: None

+

VERSION_PARAM

+

The string that should used for any versioning parameters, such as in the media type or URL query parameters.

+

Default: 'version'

+
+

Authentication settings

+

The following settings control the behavior of unauthenticated requests.

+

UNAUTHENTICATED_USER

+

The class that should be used to initialize request.user for unauthenticated requests. +(If removing authentication entirely, e.g. by removing django.contrib.auth from +INSTALLED_APPS, set UNAUTHENTICATED_USER to None.)

+

Default: django.contrib.auth.models.AnonymousUser

+

UNAUTHENTICATED_TOKEN

+

The class that should be used to initialize request.auth for unauthenticated requests.

+

Default: None

+
+

Test settings

+

The following settings control the behavior of APIRequestFactory and APIClient

+

TEST_REQUEST_DEFAULT_FORMAT

+

The default format that should be used when making test requests.

+

This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting.

+

Default: 'multipart'

+

TEST_REQUEST_RENDERER_CLASSES

+

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'
+]
+
+
+

Schema generation controls

+

SCHEMA_COERCE_PATH_PK

+

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

+

Default: True

+

SCHEMA_COERCE_METHOD_NAMES

+

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

+

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

+
+

Content type controls

+

URL_FORMAT_OVERRIDE

+

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

+

For example: http://example.com/organizations/?format=csv

+

If the value of this setting is None then URL format overrides will be disabled.

+

Default: 'format'

+

FORMAT_SUFFIX_KWARG

+

The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns.

+

For example: http://example.com/organizations.csv/

+

Default: 'format'

+
+

Date and time formatting

+

The following settings are used to control how date and time representations may be parsed and rendered.

+

DATETIME_FORMAT

+

A format string that should be used by default for rendering the output of DateTimeField serializer fields. 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: '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.

+

Default: ['iso-8601']

+

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: '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.

+

Default: ['iso-8601']

+

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: '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

+

STRICT_JSON

+

When set to True, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (nan, inf, -inf) accepted by Python's json module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's JSON.Parse nor PostgreSQL's JSON data type accept these values.

+

When set to False, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.

+

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(self)
+
+
    +
  • self: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing self.__class__.__name__.
  • +
+

If the view instance inherits ViewSet, it may have been initialized with several optional arguments:

+
    +
  • name: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.
  • +
  • suffix: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to name.
  • +
  • detail: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.
  • +
+

Default: 'rest_framework.views.get_view_name'

+

VIEW_DESCRIPTION_FUNCTION

+

A string representing the function that should be used when generating view descriptions.

+

This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API.

+

This should be a function with the following signature:

+
view_description(self, html=False)
+
+
    +
  • self: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing self.__class__.__doc__
  • +
  • html: A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses.
  • +
+

If the view instance inherits ViewSet, it may have been initialized with several optional arguments:

+
    +
  • description: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset actions, and should be used as-is.
  • +
+

Default: 'rest_framework.views.get_view_description'

+

HTML Select Field cutoffs

+

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

+

HTML_SELECT_CUTOFF

+

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

+

Default: 1000

+

HTML_SELECT_CUTOFF_TEXT

+

A string representing a global setting for html_cutoff_text.

+

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

+
+

Miscellaneous settings

+

EXCEPTION_HANDLER

+

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, context)
+
+
    +
  • 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'

+

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

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/status-codes/index.html b/api-guide/status-codes/index.html new file mode 100644 index 000000000..ce230d5b6 --- /dev/null +++ b/api-guide/status-codes/index.html @@ -0,0 +1,616 @@ + + + + + + + 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 your 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
+HTTP_207_MULTI_STATUS
+HTTP_208_ALREADY_REPORTED
+HTTP_226_IM_USED
+
+

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
+HTTP_308_PERMANENT_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_422_UNPROCESSABLE_ENTITY
+HTTP_423_LOCKED
+HTTP_424_FAILED_DEPENDENCY
+HTTP_426_UPGRADE_REQUIRED
+HTTP_428_PRECONDITION_REQUIRED
+HTTP_429_TOO_MANY_REQUESTS
+HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
+HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
+
+

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_506_VARIANT_ALSO_NEGOTIATES
+HTTP_507_INSUFFICIENT_STORAGE
+HTTP_508_LOOP_DETECTED
+HTTP_509_BANDWIDTH_LIMIT_EXCEEDED
+HTTP_510_NOT_EXTENDED
+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/index.html b/api-guide/testing/index.html new file mode 100644 index 000000000..7cf0fc0d7 --- /dev/null +++ b/api-guide/testing/index.html @@ -0,0 +1,909 @@ + + + + + + + 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 that the 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.

+
from rest_framework.test import force_authenticate
+
+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.auth_token)
+
+
+

Note: force_authenticate directly sets request.user to the in-memory user instance. If you are re-using the same user instance across multiple tests that update the saved user state, you may need to call refresh_from_db() between tests.

+
+

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 Django's standard Client class. This means that the 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 entirely and 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().

+
+

RequestsClient

+

REST framework also includes a client for interacting with your application +using the popular Python library, requests. This may be useful if:

+
    +
  • You are expecting to interface with the API primarily from another Python service, +and want to test the service at the same level as the client will see.
  • +
  • You want to write tests in such a way that they can also be run against a staging or +live environment. (See "Live tests" below.)
  • +
+

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

+
from rest_framework.test import RequestsClient
+
+client = RequestsClient()
+response = client.get('http://testserver/users/')
+assert response.status_code == 200
+
+

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

+

RequestsClient and working with the database

+

The RequestsClient class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.

+

If you're using RequestsClient you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that Customer.objects.count() == 3 you would list the customers endpoint, and ensure that it contains three records.

+

Headers & Authentication

+

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

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

CSRF

+

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

+

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

+

For example...

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

Live tests

+

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

+

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

+
+

CoreAPIClient

+

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

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

Headers & Authentication

+

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

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

API 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.urls import reverse
+from rest_framework import status
+from rest_framework.test import APITestCase
+from myproject.apps.core.models import Account
+
+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(Account.objects.count(), 1)
+        self.assertEqual(Account.objects.get().name, 'DabApps')
+
+
+

URLPatternsTestCase

+

REST framework also provides a test case class for isolating urlpatterns on a per-class basis. Note that this inherits from Django's SimpleTestCase, and will most likely need to be mixed with another test case class.

+

Example

+
from django.urls import include, path, reverse
+from rest_framework.test import APITestCase, URLPatternsTestCase
+
+
+class AccountTests(APITestCase, URLPatternsTestCase):
+    urlpatterns = [
+        path('api/', include('api.urls')),
+    ]
+
+    def test_create_account(self):
+        """
+        Ensure we can create a new account object.
+        """
+        url = reverse('account-list')
+        response = self.client.get(url, format='json')
+        self.assertEqual(response.status_code, status.HTTP_200_OK)
+        self.assertEqual(len(response.data), 1)
+
+
+

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='html' 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.TemplateHTMLRenderer'
+    ]
+}
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/throttling/index.html b/api-guide/throttling/index.html new file mode 100644 index 000000000..122cbb76d --- /dev/null +++ b/api-guide/throttling/index.html @@ -0,0 +1,673 @@ + + + + + + + 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 HTTP header and REMOTE_ADDR WSGI variable 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 variable from the WSGI environment 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 value 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:

+
from django.core.cache import caches
+
+class CustomAnonRateThrottle(AnonRateThrottle):
+    cache = caches['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.

+
import random
+
+class RandomRateThrottle(throttling.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/index.html b/api-guide/validators/index.html new file mode 100644 index 000000000..ff562836c --- /dev/null +++ b/api-guide/validators/index.html @@ -0,0 +1,786 @@ + + + + + + + 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.

+

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 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.
  • +
  • lookup - The lookup used to find an existing instance with the value being validated. Defaults to 'exact'.
  • +
+

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

+
from rest_framework.validators import UniqueValidator
+
+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:

+
from rest_framework.validators import UniqueTogetherValidator
+
+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 UniqueTogetherValidator 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:

+
from rest_framework.validators import UniqueForYearValidator
+
+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)
+
+

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 its default value to the validated_data in the serializer.

+
published = serializers.HiddenField(default=timezone.now)
+
+
+

Note: The UniqueFor<Range>Validator classes impose 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 field defaults

+

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=serializers.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(
+    default=serializers.CreateOnlyDefault(timezone.now)
+)
+
+
+

Limitations of validators

+

There are some ambiguous cases where you'll need to instead handle validation +explicitly, rather than relying on the default serializer classes that +ModelSerializer generates.

+

In these cases you may want to disable the automatically generated validators, +by specifying an empty list for the serializer Meta.validators attribute.

+

Optional fields

+

By default "unique together" validation enforces that all fields be +required=True. In some cases, you might want to explicit apply +required=False to one of the fields, in which case the desired behaviour +of the validation is ambiguous.

+

In this case you will typically need to exclude the validator from the +serializer class, and instead write any validation logic explicitly, either +in the .validate() method, or else in the view.

+

For example:

+
class BillingRecordSerializer(serializers.ModelSerializer):
+    def validate(self, attrs):
+        # Apply custom validation either here, or in the view.
+
+    class Meta:
+        fields = ['client', 'date', 'amount']
+        extra_kwargs = {'client': {'required': False}}
+        validators = []  # Remove a default "unique together" constraint.
+
+

Updating nested serializers

+

When applying an update to an existing instance, uniqueness validators will +exclude the current instance from the uniqueness check. The current instance +is available in the context of the uniqueness check, because it exists as +an attribute on the serializer, having initially been passed using +instance=... when instantiating the serializer.

+

In the case of update operations on nested serializers there's no way of +applying this exclusion, because the instance is not available.

+

Again, you'll probably want to explicitly remove the validator from the +serializer class, and write the code the for the validation constraint +explicitly, in a .validate() method, or in the view.

+

Debugging complex cases

+

If you're not sure exactly what behavior a ModelSerializer class will +generate it is usually a good idea to run manage.py shell, and print +an instance of the serializer, so that you can inspect the fields and +validators that it automatically generates for you.

+
>>> serializer = MyComplexModelSerializer()
+>>> print(serializer)
+class MyComplexModelSerializer:
+    my_fields = ...
+
+

Also keep in mind that with complex cases it can often be better to explicitly +define your serializer classes, rather than relying on the default +ModelSerializer behavior. This involves a little more code, but ensures +that the resulting behavior is more transparent.

+
+

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.')
+
+

Field-level validation

+

You can specify custom field-level validation by adding .validate_<field_name> methods +to your Serializer subclass. This is documented in the +Serializer docs

+

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(object):
+    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)
+
+

Accessing the 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 setting +a requires_context = True attribute on the validator. The __call__ method +will then be called with the serializer_field +or serializer as an additional argument.

+
requires_context = True
+
+def __call__(self, value, serializer_field):
+    ...
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/versioning/index.html b/api-guide/versioning/index.html new file mode 100644 index 000000000..f3572acd4 --- /dev/null +++ b/api-guide/versioning/index.html @@ -0,0 +1,686 @@ + + + + + + + Versioning - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + versioning.py + + + + +

Versioning

+
+

Versioning an interface is just a "polite" way to kill deployed clients.

+

Roy Fielding.

+
+

API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.

+

Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.

+

There are a number of valid approaches to approaching versioning. Non-versioned systems can also be appropriate, particularly if you're engineering for very long-term systems with multiple clients outside of your control.

+

Versioning with REST framework

+

When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request.

+

By default, versioning is not enabled, and request.version will always return None.

+

Varying behavior based on the version

+

How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:

+
def get_serializer_class(self):
+    if self.request.version == 'v1':
+        return AccountSerializerVersion1
+    return AccountSerializer
+
+

Reversing URLs for versioned APIs

+

The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so.

+
from rest_framework.reverse import reverse
+
+reverse('bookings-list', request=request)
+
+

The above function will apply any URL transformations appropriate to the request version. For example:

+
    +
  • If NamespaceVersioning was being used, and the API version was 'v1', then the URL lookup used would be 'v1:bookings-list', which might resolve to a URL like http://example.org/v1/bookings/.
  • +
  • If QueryParameterVersioning was being used, and the API version was 1.0, then the returned URL might be something like http://example.org/bookings/?version=1.0
  • +
+

Versioned APIs and hyperlinked serializers

+

When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.

+
def get(self, request):
+    queryset = Booking.objects.all()
+    serializer = BookingsSerializer(queryset, many=True, context={'request': request})
+    return Response({'all_bookings': serializer.data})
+
+

Doing so will allow any returned URLs to include the appropriate versioning.

+

Configuring the versioning scheme

+

The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key.

+
REST_FRAMEWORK = {
+    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
+}
+
+

Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None. In this case the request.version attribute will always return None.

+

You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute.

+
class ProfileList(APIView):
+    versioning_class = versioning.QueryParameterVersioning
+
+

Other versioning settings

+

The following settings keys are also used to control versioning:

+
    +
  • DEFAULT_VERSION. The value that should be used for request.version when no versioning information is present. Defaults to None.
  • +
  • ALLOWED_VERSIONS. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the DEFAULT_VERSION setting is always considered to be part of the ALLOWED_VERSIONS set (unless it is None). Defaults to None.
  • +
  • VERSION_PARAM. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to 'version'.
  • +
+

You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version, allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning:

+
from rest_framework.versioning import URLPathVersioning
+from rest_framework.views import APIView
+
+class ExampleVersioning(URLPathVersioning):
+    default_version = ...
+    allowed_versions = ...
+    version_param = ...
+
+class ExampleView(APIVIew):
+    versioning_class = ExampleVersioning
+
+
+

API Reference

+

AcceptHeaderVersioning

+

This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type.

+

Here's an example HTTP request using the accept header versioning style.

+
GET /bookings/ HTTP/1.1
+Host: example.com
+Accept: application/json; version=1.0
+
+

In the example request above request.version attribute would return the string '1.0'.

+

Versioning based on accept headers is generally considered as best practice, although other styles may be suitable depending on your client requirements.

+

Using accept headers with vendor media types

+

Strictly speaking the json media type is not specified as including additional parameters. If you are building a well-specified public API you might consider using a vendor media type. To do so, configure your renderers to use a JSON based renderer with a custom media type:

+
class BookingsAPIRenderer(JSONRenderer):
+    media_type = 'application/vnd.megacorp.bookings+json'
+
+

Your client requests would now look like this:

+
GET /bookings/ HTTP/1.1
+Host: example.com
+Accept: application/vnd.megacorp.bookings+json; version=1.0
+
+

URLPathVersioning

+

This scheme requires the client to specify the version as part of the URL path.

+
GET /v1/bookings/ HTTP/1.1
+Host: example.com
+Accept: application/json
+
+

Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme.

+
urlpatterns = [
+    re_path(
+        r'^(?P<version>(v1|v2))/bookings/$',
+        bookings_list,
+        name='bookings-list'
+    ),
+    re_path(
+        r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',
+        bookings_detail,
+        name='bookings-detail'
+    )
+]
+
+

NamespaceVersioning

+

To the client, this scheme is the same as URLPathVersioning. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.

+
GET /v1/something/ HTTP/1.1
+Host: example.com
+Accept: application/json
+
+

With this scheme the request.version attribute is determined based on the namespace that matches the incoming request path.

+

In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:

+
# bookings/urls.py
+urlpatterns = [
+    re_path(r'^$', bookings_list, name='bookings-list'),
+    re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
+]
+
+# urls.py
+urlpatterns = [
+    re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
+    re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
+]
+
+

Both URLPathVersioning and NamespaceVersioning are reasonable if you just need a simple versioning scheme. The URLPathVersioning approach might be better suitable for small ad-hoc projects, and the NamespaceVersioning is probably easier to manage for larger projects.

+

HostNameVersioning

+

The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.

+

For example the following is an HTTP request to the http://v1.example.com/bookings/ URL:

+
GET /bookings/ HTTP/1.1
+Host: v1.example.com
+Accept: application/json
+
+

By default this implementation expects the hostname to match this simple regular expression:

+
^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$
+
+

Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.

+

The HostNameVersioning scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as 127.0.0.1. There are various online tutorials on how to access localhost with a custom subdomain which you may find helpful in this case.

+

Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.

+

QueryParameterVersioning

+

This scheme is a simple style that includes the version as a query parameter in the URL. For example:

+
GET /something/?version=0.1 HTTP/1.1
+Host: example.com
+Accept: application/json
+
+
+

Custom versioning schemes

+

To implement a custom versioning scheme, subclass BaseVersioning and override the .determine_version method.

+

Example

+

The following example uses a custom X-API-Version header to determine the requested version.

+
class XAPIVersionScheme(versioning.BaseVersioning):
+    def determine_version(self, request, *args, **kwargs):
+        return request.META.get('HTTP_X_API_VERSION', None)
+
+

If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/views/index.html b/api-guide/views/index.html new file mode 100644 index 000000000..005ef1b83 --- /dev/null +++ b/api-guide/views/index.html @@ -0,0 +1,672 @@ + + + + + + + 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
+from django.contrib.auth.models import User
+
+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)
+
+
+

Note: The full methods, attributes on, and relations between Django REST Framework's APIView, GenericAPIView, various Mixins, and Viewsets can be initially complex. In addition to the documentation here, the Classy Django REST Framework resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.

+
+

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)

+

.get_exception_handler(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=['GET'])

+

The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:

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

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

+

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

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

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.

+

View schema decorator

+

To override the default schema generation for function based views you may use +the @schema decorator. This must come after (below) the @api_view +decorator. For example:

+
from rest_framework.decorators import api_view, schema
+from rest_framework.schemas import AutoSchema
+
+class CustomAutoSchema(AutoSchema):
+    def get_link(self, path, method, base_url):
+        # override view introspection here...
+
+@api_view(['GET'])
+@schema(CustomAutoSchema())
+def view(request):
+    return Response({"message": "Hello for today! See you tomorrow!"})
+
+

This decorator takes a single AutoSchema instance, an AutoSchema subclass +instance or ManualSchema instance as described in the Schemas documentation. +You may pass None in order to exclude the view from schema generation.

+
@api_view(['GET'])
+@schema(None)
+def view(request):
+    return Response({"message": "Will not appear in schema!"})
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api-guide/viewsets/index.html b/api-guide/viewsets/index.html new file mode 100644 index 000000000..6943a7301 --- /dev/null +++ b/api-guide/viewsets/index.html @@ -0,0 +1,789 @@ + + + + + + + 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 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, basename='user')
+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.

+

ViewSet actions

+

The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, 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
+
+

Introspecting ViewSet actions

+

During dispatch, the following attributes are available on the ViewSet.

+
    +
  • basename - the base to use for the URL names that are created.
  • +
  • action - the name of the current action (e.g., list, create).
  • +
  • detail - boolean indicating if the current action is configured for a list or detail view.
  • +
  • suffix - the display suffix for the viewset type - mirrors the detail attribute.
  • +
  • name - the display name for the viewset. This argument is mutually exclusive to suffix.
  • +
  • description - the display description for the individual view of a viewset.
  • +
+

You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this:

+
def get_permissions(self):
+    """
+    Instantiates and returns the list of permissions that this view requires.
+    """
+    if self.action == 'list':
+        permission_classes = [IsAuthenticated]
+    else:
+        permission_classes = [IsAdmin]
+    return [permission() for permission in permission_classes]
+
+

Marking extra actions for routing

+

If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns.

+

A more complete example of extra actions:

+
from django.contrib.auth.models import User
+from rest_framework import status, viewsets
+from rest_framework.decorators import action
+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
+
+    @action(detail=True, 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)
+
+    @action(detail=False)
+    def recent_users(self, request):
+        recent_users = User.objects.all().order_by('-last_login')
+
+        page = self.paginate_queryset(recent_users)
+        if page is not None:
+            serializer = self.get_serializer(page, many=True)
+            return self.get_paginated_response(serializer.data)
+
+        serializer = self.get_serializer(recent_users, many=True)
+        return Response(serializer.data)
+
+

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

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

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

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

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

+

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

+

Routing additional HTTP methods for extra actions

+

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

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

Reversing action URLs

+

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

+

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

+

Using the example from the previous section:

+
>>> view.reverse_action('set-password', args=['1'])
+'http://localhost:8000/api/users/1/set_password'
+
+ +

Alternatively, you can use the url_name attribute set by the @action decorator.

+
>>> view.reverse_action(view.set_password.url_name, args=['1'])
+'http://localhost:8000/api/users/1/set_password'
+
+ +

The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create.

+
+

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(), .partial_update(), and .destroy().

+

Example

+

Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. 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()
+
+

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

+

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

+

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:

+
from rest_framework import mixins
+
+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/community/3.0-announcement/index.html b/community/3.0-announcement/index.html new file mode 100644 index 000000000..a87d0df90 --- /dev/null +++ b/community/3.0-announcement/index.html @@ -0,0 +1,1258 @@ + + + + + + + 3.0 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

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

+

3.0 is the first of three releases that have been funded by our recent Kickstarter campaign.

+

As ever, a huge thank you to our many wonderful sponsors. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.

+
+

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 including new classes such as ListField and MultipleChoiceField.
  • +
  • Super simple default implementations for the generic views.
  • +
  • Support for overriding how validation errors are handled by your API.
  • +
  • A metadata API that allows you to customize how OPTIONS requests are handled by your API.
  • +
  • A more compact JSON output with unicode style encoding turned on by default.
  • +
  • Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
  • +
+

Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.

+
+

REST framework: Under the hood.

+

This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.

+ + +
+

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

+

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, e.g. ExampleModel.objects.create(...). Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.
  • +
  • The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?
  • +
+

We now use single-step object creation, like so:

+
    +
  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 removed, and we instead have two separate methods, .create() and .update(). These methods work slightly different to the previous .restore_object().

+

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

+

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

+

The following example from the tutorial previously used restore_object() to handle both creating and updating object instances.

+
def restore_object(self, attrs, instance=None):
+    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 .is_valid(raise_exception=True)

+

The .is_valid() method now takes an optional boolean flag, raise_exception.

+

Calling .is_valid(raise_exception=True) will cause a ValidationError to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.

+

The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key.

+

This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.

+

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 should prefer using the serializers.ValidationError exception class, and not Django's built-in exception.

+

We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.

+

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 serializers.ValidationError('A non field error')
+
+

Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError, like so:

+
def validate(self, attrs):
+    # serializer.errors == {'my_field': ['A field error']}
+    raise serializers.ValidationError({'my_field': 'A field error'})
+
+

This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.

+

Removal of transform_<field_name>.

+

The under-used transform_<field_name> on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style.

+

For example:

+
def to_representation(self, instance):
+    ret = super(UserSerializer, self).to_representation(instance)
+    ret['username'] = ret['username'].lower()
+    return ret
+
+

Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.

+

If you absolutely need to preserve transform_<field_name> behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:

+
class BaseModelSerializer(ModelSerializer):
+    """
+    A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
+    """
+    def to_representation(self, instance):
+        ret = super(BaseModelSerializer, self).to_representation(instance)
+        for key, value in ret.items():
+            method = getattr(self, 'transform_' + key, None)
+            if method is not None:
+                ret[key] = method(value)
+        return ret
+
+

Differences between ModelSerializer validation and ModelForm.

+

This change also means that we no longer use the .full_clean() method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on ModelSerializer classes that can't also be easily replicated on regular Serializer classes.

+

For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.

+

The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm. Use the serializer .validate() method to perform a final validation step on incoming data where required.

+

There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate(). You can do so by explicitly instantiating a model instance in the .validate() method.

+
def validate(self, attrs):
+    instance = ExampleModel(**attrs)
+    instance.clean()
+    return attrs
+
+

Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.

+

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 support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
+
+

To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly.

+
class UserSerializer(serializers.ModelSerializer):
+    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 ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model:

+
class Invitation(models.Model):
+    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.

+

You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior.

+

See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid(), .data, .save() and so on.

+

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 methods that can be overridden, depending on what functionality you want the serializer class to support:

+
    +
  • .to_representation() - Override this to support serialization, for read operations.
  • +
  • .to_internal_value() - Override this to support deserialization, for write operations.
  • +
  • .create() and .update() - Override either or both of these to support saving instances.
  • +
+

Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer.

+

The only difference you'll notice when doing so is the BaseSerializer classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.

+
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 arbitrary 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.startswith('_'):
+                # 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):
+                # Recursively deal with items in lists.
+                output[attribute_name] = [
+                    self.to_representation(item) for item in attribute
+                ]
+            elif isinstance(attribute, dict):
+                # Recursively deal with items in dictionaries.
+                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_null, allow_blank and default arguments.

+

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

+

Previously the meaning of the required=False keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be None or the empty string.

+

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

+

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_null=True: None is a valid input.
  • +
  • allow_blank=True: '' is valid input. For CharField and subclasses only.
  • +
+

Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required.

+

The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.

+

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.

+

Removal of .validate().

+

The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value().

+
class UppercaseCharField(serializers.CharField):
+    def to_internal_value(self, data):
+        value = super(UppercaseCharField, self).to_internal_value(data)
+        if value != value.upper():
+            raise serializers.ValidationError('The input should be uppercase only.')
+        return value
+
+

Previously validation errors could be raised in either .to_native() or .validate(), making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.

+

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. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...

+
def field_to_native(self, obj, field_name):
+    """A custom read-only field that returns the class name."""
+    return obj.__class__.__name__
+
+

Now if you need to access the entire object you'll instead need to override one or both of the following:

+
    +
  • Use get_attribute to modify the attribute value passed to to_representation().
  • +
  • Use get_value to modify the data value passed to_internal_value().
  • +
+

For example:

+
def get_attribute(self, obj):
+    # Pass the entire object through to `to_representation()`,
+    # instead of the standard attribute lookup.
+    return obj
+
+def to_representation(self, value):
+    return value.__class__.__name__
+
+

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):
+    organizations = serializers.SlugRelatedField(slug_field='name')
+
+    class Meta:
+        model = Account
+
+

However this code would not be valid in 3.0:

+
# Missing `queryset`
+class AccountSerializer(serializers.Serializer):
+    organizations = 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):
+    organizations = serializers.SlugRelatedField(
+        slug_field='name',
+        queryset=Organization.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 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='organization_detail')
+    created = serializers.DateTimeField(read_only=True)
+    name = serializers.CharField(
+        max_length=100,
+        validators=UniqueValidator(queryset=Organization.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)
+
+    class Meta:
+        validators = [UniqueTogetherValidator(
+            queryset=RaceResult.objects.all(),
+            fields=['category', 'position']
+        )]
+
+

The UniqueForDateValidator classes.

+

REST framework also now includes explicit validator classes for validating the unique_for_date, unique_for_month, and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean().

+

These classes are documented in the Validators section of the documentation.

+
+

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-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning 404 responses.

+

Both styles "PUT as 404" and "PUT as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.

+

If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.

+

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.

+
+

Serializers as HTML forms

+

REST framework 3.0 includes templated HTML form rendering for serializers.

+

This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.

+

Significant changes that you do need to be aware of include:

+
    +
  • Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API.
  • +
  • Nested lists of HTML forms are not yet supported, but are planned for 3.1.
  • +
  • Because we now use templated HTML form generation, the widget option is no longer available for serializer fields. You can instead control the template that is used for a given field, by using the style dictionary.
  • +
+

The style keyword argument for serializer fields.

+

The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with.

+

For example, to use a textarea control instead of the default input control, you would use the following…

+
additional_notes = serializers.CharField(
+    style={'base_template': 'textarea.html'}
+)
+
+

Similarly, to use a radio button control instead of the default select control, you would use the following…

+
color_channel = serializers.ChoiceField(
+    choices=['red', 'blue', 'green'],
+    style={'base_template': 'radio.html'}
+)
+
+

This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.

+
+

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(use_url=False)
+
+

Also note that you should pass the request object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form https://example.com/url_path/filename.txt. For example:

+
context = {'request': request}
+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-8601 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-8601' 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 coerce_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 un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.

+
+

Miscellaneous notes

+
    +
  • The serializer ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
  • +
  • Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
  • +
  • Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still create language files with Django if you wish to localize them.
  • +
  • APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string. If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
  • +
+
+

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:

+
    +
  • Public API for using serializers as HTML forms.
  • +
  • Request parsing, mediatypes & the implementation of the browsable API.
  • +
  • Introduction of a new pagination API.
  • +
  • Better support for API versioning.
  • +
+

The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.

+

You can follow development on the GitHub site, where we use milestones to indicate planning timescales.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.1-announcement/index.html b/community/3.1-announcement/index.html new file mode 100644 index 000000000..552ef386b --- /dev/null +++ b/community/3.1-announcement/index.html @@ -0,0 +1,652 @@ + + + + + + + 3.1 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Django REST framework 3.1

+

The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.

+

Some highlights include:

+
    +
  • A super-smart cursor pagination scheme.
  • +
  • An improved pagination API, supporting header or in-body pagination styles.
  • +
  • Pagination controls rendering in the browsable API.
  • +
  • Better support for API versioning.
  • +
  • Built-in internationalization support.
  • +
  • Support for Django 1.8's HStoreField and ArrayField.
  • +
+
+

Pagination

+

The pagination API has been improved, making it both easier to use, and more powerful.

+

A guide to the headline features follows. For full details, see the pagination documentation.

+

Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.

+
    +
  • The PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead.
  • +
  • The PAGINATE_BY_PARAM, MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
  • +
  • The paginate_by, page_query_param, paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
  • +
  • The pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid. The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.
  • +
+

New pagination schemes.

+

Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.

+

The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.

+

Pagination controls in the browsable API.

+

Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:

+

page number based pagination

+

The cursor based pagination renders a more simple style of control:

+

cursor based pagination

+

Support for header-based pagination.

+

The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers.

+

For more information, see the custom pagination styles documentation.

+
+

Versioning

+

We've made it easier to build versioned APIs. Built-in schemes for versioning include both URL based and Accept header based variations.

+

When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.

+

For example, when using NamespaceVersioning, and the following hyperlinked serializer:

+
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
+    class Meta:
+        model = Accounts
+        fields = ['account_name', 'users']
+
+

The output representation would match the version used on the incoming request. Like so:

+
GET http://example.org/v2/accounts/10  # Version 'v2'
+
+{
+    "account_name": "europa",
+    "users": [
+        "http://example.org/v2/users/12",  # Version 'v2'
+        "http://example.org/v2/users/54",
+        "http://example.org/v2/users/87"
+    ]
+}
+
+
+

Internationalization

+

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

+

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

+
LANGUAGE_CODE = "es-es"
+
+

You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting:

+
MIDDLEWARE_CLASSES = [
+    ...
+    'django.middleware.locale.LocaleMiddleware'
+]
+
+

When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type:

+

Request

+
GET /api/users HTTP/1.1
+Accept: application/xml
+Accept-Language: es-es
+Host: example.org
+
+

Response

+
HTTP/1.0 406 NOT ACCEPTABLE
+
+{
+    "detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."
+}
+
+

Note that the structure of the error responses is still the same. We still have a detail key in the response. If needed you can modify this behavior too, by using a custom exception handler.

+

We include built-in translations both for standard exception cases, and for serializer validation errors.

+

The full list of supported languages can be found on our Transifex project page.

+

If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES setting:

+
LANGUAGES = [
+    ('de', _('German')),
+    ('en', _('English')),
+]
+
+

For more details, see the internationalization documentation.

+

Many thanks to Craig Blaszczyk for helping push this through.

+
+

New field types

+

Django 1.8's new ArrayField, HStoreField and UUIDField are now all fully supported.

+

This work also means that we now have both serializers.DictField(), and serializers.ListField() types, allowing you to express and validate a wider set of representations.

+

If you're building a new 1.8 project, then you should probably consider using UUIDField as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:

+
http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d
+
+
+

ModelSerializer API

+

The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.

+

For more information, see the documentation on customizing field mappings for ModelSerializer classes.

+
+

Moving packages out of core

+

We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install the new packages, and change any import paths.

+

We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.

+

The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained Django OAuth toolkit has now been promoted as our recommended option for integrating OAuth support.

+

The following packages are now moved out of core and should be separately installed:

+ +

It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:

+
pip install djangorestframework-xml
+
+

And modify your settings, like so:

+
REST_FRAMEWORK = {
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework.renderers.JSONRenderer',
+        'rest_framework.renderers.BrowsableAPIRenderer',
+        'rest_framework_xml.renderers.XMLRenderer'
+    ]
+}
+
+

Thanks go to the latest member of our maintenance team, José Padilla, for handling this work and taking on ownership of these packages.

+
+

Deprecations

+

The request.DATA, request.FILES and request.QUERY_PARAMS attributes move from pending deprecation, to deprecated. Use request.data and request.query_params instead, as discussed in the 3.0 release notes.

+

The ModelSerializer Meta options for write_only_fields, view_name and lookup_field are also moved from pending deprecation, to deprecated. Use extra_kwargs instead, as discussed in the 3.0 release notes.

+

All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.

+
+

What's next?

+

The next focus will be on HTML renderings of API output and will include:

+
    +
  • HTML form rendering of serializers.
  • +
  • Filtering controls built-in to the browsable API.
  • +
  • An alternative admin-style interface.
  • +
+

This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.10-announcement/index.html b/community/3.10-announcement/index.html new file mode 100644 index 000000000..ea4659d74 --- /dev/null +++ b/community/3.10-announcement/index.html @@ -0,0 +1,610 @@ + + + + + + + 3.10 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + +

Django REST framework 3.10

+

The 3.10 release drops support for Python 2.

+
    +
  • Our supported Python versions are now: 3.5, 3.6, and 3.7.
  • +
  • Our supported Django versions are now: 1.11, 2.0, 2.1, and 2.2.
  • +
+

OpenAPI Schema Generation

+

Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs.

+

This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place.

+
+

Continuing to use CoreAPI

+

If you're currently using the CoreAPI schemas, you'll need to make sure to +update your REST framework settings to include DEFAULT_SCHEMA_CLASS explicitly.

+

settings.py:

+
REST_FRAMEWORK = {
+  ...
+  'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
+}
+
+ +

You'll still be able to keep using CoreAPI schemas, API docs, and client for the +foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains +available as a third party package, even once it has eventually been removed +from REST framework, scheduled for version 3.12.

+

We have removed the old documentation for the CoreAPI based schema generation. +You may view the Legacy CoreAPI documentation here.

+
+

OpenAPI Quickstart

+

You can generate a static OpenAPI schema, using the generateschema management +command.

+

Alternately, to have the project serve an API schema, use the get_schema_view() +shortcut.

+

In your urls.py:

+
from rest_framework.schemas import get_schema_view
+
+urlpatterns = [
+    # ...
+    # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
+    #   * `title` and `description` parameters are passed to `SchemaGenerator`.
+    #   * Provide view name for use with `reverse()`.
+    path('openapi', get_schema_view(
+        title="Your Project",
+        description="API for all things …"
+    ), name='openapi-schema'),
+    # ...
+]
+
+ +

Customization

+

For customizations that you want to apply across the entire API, you can subclass rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument +to the generateschema command or get_schema_view() helper function.

+

For specific per-view customizations, you can subclass AutoSchema, +making sure to set schema = <YourCustomClass> on the view.

+

For more details, see the API Schema documentation.

+

API Documentation

+

There are some great third party options for documenting your API, based on the +OpenAPI schema.

+

See the Documenting you API section for more details.

+
+

Feature Roadmap

+

Given that our OpenAPI schema generation is a new feature, it's likely that there +will still be some iterative improvements for us to make. There will be two +main cases here:

+
    +
  • Expanding the supported range of OpenAPI schemas that are generated by default.
  • +
  • Improving the ability for developers to customize the output.
  • +
+

We'll aim to bring the first type of change quickly in point releases. For the +second kind we'd like to adopt a slower approach, to make sure we keep the API +simple, and as widely applicable as possible, before we bring in API changes.

+

It's also possible that we'll end up implementing API documentation and API client +tooling that are driven by the OpenAPI schema. The apistar project has a +significant amount of work towards this. However, if we do so, we'll plan +on keeping any tooling outside of the core framework.

+
+

Funding

+

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

+

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

+ + +
+ +

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, and Lights On Software.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.11-announcement/index.html b/community/3.11-announcement/index.html new file mode 100644 index 000000000..2b098d72c --- /dev/null +++ b/community/3.11-announcement/index.html @@ -0,0 +1,588 @@ + + + + + + + 3.11 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+ +
+ +
+ + + + + +

Django REST framework 3.11

+

The 3.11 release adds support for Django 3.0.

+
    +
  • Our supported Python versions are now: 3.5, 3.6, 3.7, and 3.8.
  • +
  • Our supported Django versions are now: 1.11, 2.0, 2.1, 2.2, and 3.0.
  • +
+

This release will be the last to support Python 3.5 or Django 1.11.

+

OpenAPI Schema Generation Improvements

+

The OpenAPI schema generation continues to mature. Some highlights in 3.11 +include:

+
    +
  • Automatic mapping of Django REST Framework renderers and parsers into OpenAPI + request and response media-types.
  • +
  • Improved mapping JSON schema mapping types, for example in HStoreFields, and + with large integer values.
  • +
  • Porting of the old CoreAPI parsing of docstrings to form OpenAPI operation + descriptions.
  • +
+

In this example view operation descriptions for the get and post methods will +be extracted from the class docstring:

+
class DocStringExampleListView(APIView):
+"""
+get: A description of my GET operation.
+post: A description of my POST operation.
+"""
+    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
+
+    def get(self, request, *args, **kwargs):
+        ...
+
+    def post(self, request, *args, **kwargs):
+        ...
+
+ +

Validator / Default Context

+

In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the .context with which the serializer was instantiated. In particular:

+
    +
  • Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
  • +
  • The CurrentUserDefault needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
  • +
+

Previous our approach to this was that implementations could include a set_context method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.

+

Instead, validators or defaults which require the serializer context, should include a requires_context = True attribute on the class.

+

The __call__ method should then include an additional serializer_field argument.

+

Validator implementations will look like this:

+
class CustomValidator:
+    requires_context = True
+
+    def __call__(self, value, serializer_field):
+        ...
+
+ +

Default implementations will look like this:

+
class CustomDefault:
+    requires_context = True
+
+    def __call__(self, serializer_field):
+        ...
+
+ +
+

Funding

+

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

+

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

+ + +
+ +

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, Lights On Software, and Retool.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.2-announcement/index.html b/community/3.2-announcement/index.html new file mode 100644 index 000000000..8c92c2174 --- /dev/null +++ b/community/3.2-announcement/index.html @@ -0,0 +1,581 @@ + + + + + + + 3.2 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Django REST framework 3.2

+

The 3.2 release is the first version to include an admin interface for the browsable API.

+

The AdminRenderer

+

This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing BrowsableAPIRenderer, or used together with it, allowing you to switch between the two styles as required.

+

We've also fixed a huge number of issues, and made numerous cleanups and improvements.

+

Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month.

+

None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.

+

AdminRenderer

+

To include AdminRenderer simply add it to your settings:

+
REST_FRAMEWORK = {
+    'DEFAULT_RENDERER_CLASSES': [
+        'rest_framework.renderers.JSONRenderer',
+        'rest_framework.renderers.AdminRenderer',
+        'rest_framework.renderers.BrowsableAPIRenderer'
+    ],
+    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
+    'PAGE_SIZE': 100
+}
+
+

There are some limitations to the AdminRenderer, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.

+

Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.

+

The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.

+

Supported versions

+

This release drops support for Django 1.4.

+

Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.

+

Deprecations

+

There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.

+
    +
  • request.DATA was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.data instead.
  • +
  • request.QUERY_PARAMS was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.query_params instead.
  • +
  • The following ModelSerializer.Meta options have now been removed: write_only_fields, view_name, lookup_field. Use the more general extra_kwargs option instead.
  • +
+

The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.

+
    +
  • view.paginate_by - Use paginator.page_size instead.
  • +
  • view.page_query_param - Use paginator.page_query_param instead.
  • +
  • view.paginate_by_param - Use paginator.page_size_query_param instead.
  • +
  • view.max_paginate_by - Use paginator.max_page_size instead.
  • +
  • settings.PAGINATE_BY - Use paginator.page_size instead.
  • +
  • settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.
  • +
  • settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.
  • +
+

Modifications to list behaviors

+

There are a couple of bug fixes that are worth calling out as they introduce differing behavior.

+

These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.

+

ManyToMany fields and blank=True

+

We've now added an allow_empty argument, which can be used with ListSerializer, or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input.

+

As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated.

+

Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set.

+

Here's what the mapping looks like in practice:

+
    +
  • models.ManyToManyField()serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)
  • +
  • models.ManyToManyField(blank=True)serializers.PrimaryKeyRelatedField(many=True)
  • +
+

The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.

+

List fields and allow_null

+

When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list.

+

For example, take the following field:

+
NestedSerializer(many=True, allow_null=True)
+
+

Previously the validation behavior would be:

+
    +
  • [{…}, null, {…}] is valid.
  • +
  • null is invalid.
  • +
+

Our validation behavior as of 3.2.0 is now:

+
    +
  • [{…}, null, {…}] is invalid.
  • +
  • null is valid.
  • +
+

If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True. For example:

+
ListField(child=NestedSerializer(allow_null=True))
+
+

What's next?

+

The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.

+

This release is planned to include:

+
    +
  • Search and filtering controls in the browsable API and admin interface.
  • +
  • Improvements and public API for the admin interface.
  • +
  • Improvements and public API for our templated HTML forms and fields.
  • +
  • Nested object and list support in HTML forms.
  • +
+

Thanks once again to all our sponsors and supporters.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.3-announcement/index.html b/community/3.3-announcement/index.html new file mode 100644 index 000000000..19c2ffc2f --- /dev/null +++ b/community/3.3-announcement/index.html @@ -0,0 +1,529 @@ + + + + + + + 3.3 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Django REST framework 3.3

+

The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding thank you to all our wonderful sponsors and supporters.

+

The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.

+

In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow @_tomchristie to keep up to date with these announcements, and be among the first set of sign ups.

+

We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.

+
+

Release notes

+

Significant new functionality in the 3.3 release includes:

+
    +
  • Filters presented as HTML controls in the browsable API.
  • +
  • A forms API, allowing serializers to be rendered as HTML forms.
  • +
  • Django 1.9 support.
  • +
  • A JSONField serializer field, corresponding to Django 1.9's Postgres JSONField model field.
  • +
  • Browsable API support via AJAX, rather than server side request overloading.
  • +
+

Filter Controls

+

Example of the new filter controls

+
+

Supported versions

+

This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.

+

This brings our supported versions into line with Django's currently supported versions

+

Deprecations

+

The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent:

+
    +
  • To support form based PUT and DELETE, or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
  • +
  • The accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class.
  • +
  • The custom HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware.
  • +
+

The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.

+
    +
  • view.paginate_by - Use paginator.page_size instead.
  • +
  • view.page_query_param - Use paginator.page_query_param instead.
  • +
  • view.paginate_by_param - Use paginator.page_size_query_param instead.
  • +
  • view.max_paginate_by - Use paginator.max_page_size instead.
  • +
  • settings.PAGINATE_BY - Use paginator.page_size instead.
  • +
  • settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.
  • +
  • settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.
  • +
+

The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.4-announcement/index.html b/community/3.4-announcement/index.html new file mode 100644 index 000000000..1ed023b8c --- /dev/null +++ b/community/3.4-announcement/index.html @@ -0,0 +1,653 @@ + + + + + + + 3.4 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + +

Django REST framework 3.4

+

The 3.4 release is the first in a planned series that will be addressing schema +generation, hypermedia support, API clients, and finally realtime support.

+
+

Funding

+

The 3.4 release has been made possible a recent Mozilla grant, and by our +collaborative funding model. If you use REST framework commercially, and would +like to see this work continue, we strongly encourage you to invest in its +continued development by signing up for a paid plan.

+

The initial aim is to provide a single full-time position on REST framework. +Right now we're over 60% of the way towards achieving that. +Every single sign-up makes a significant impact.

+ + +
+ +

Many thanks to all our awesome sponsors, and in particular to our premium backers, Rover, Sentry, and Stream.

+
+

Schemas & client libraries

+

REST framework 3.4 brings built-in support for generating API schemas.

+

We provide this support by using Core API, a Document Object Model +for describing APIs.

+

Because Core API represents the API schema in an format-independent +manner, we're able to render the Core API Document object into many different +schema formats, by allowing the renderer class to determine how the internal +representation maps onto the external schema format.

+

This approach should also open the door to a range of auto-generated API +documentation options in the future, by rendering the Document object into +HTML documentation pages.

+

Alongside the built-in schema support, we're also now providing the following:

+ +

These API clients are dynamically driven, and able to interact with any API +that exposes a supported schema format.

+

Dynamically driven clients allow you to interact with an API at an application +layer interface, rather than a network layer interface, while still providing +the benefits of RESTful Web API design.

+

We're expecting to expand the range of languages that we provide client libraries +for over the coming months.

+

Further work on maturing the API schema support is also planned, including +documentation on supporting file upload and download, and improved support for +documentation generation and parameter annotation.

+
+

Current support for schema formats is as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameSupportPyPI package
Core JSONSchema generation & client support.Built-in support in coreapi.
Swagger / OpenAPISchema generation & client support.The openapi-codec package.
JSON Hyper-SchemaCurrently client support only.The hyperschema-codec package.
API BlueprintNot yet available.Not yet available.
+
+

You can read more about any of this new functionality in the following:

+ +

It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of +the popular Django REST Swagger package, which will tie in with our new built-in support.

+
+

Supported versions

+

The 3.4.0 release adds support for Django 1.10.

+

The following versions of Python and Django are now supported:

+
    +
  • Django versions 1.8, 1.9, and 1.10.
  • +
  • Python versions 2.7, 3.2(*), 3.3(*), 3.4, 3.5.
  • +
+

(*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.

+
+

Deprecations and changes

+

The 3.4 release includes very limited deprecation or behavioral changes, and +should present a straightforward upgrade.

+

Use fields or exclude on serializer classes.

+

The following change in 3.3.0 is now escalated from "pending deprecation" to +"deprecated". Its usage will continue to function but will raise warnings:

+

ModelSerializer and HyperlinkedModelSerializer should include either a fields +option, or an exclude option. The fields = '__all__' shortcut may be used +to explicitly include all fields.

+

Microsecond precision when returning time or datetime.

+

Using the default JSON renderer and directly returning a datetime or time +instance will now render with microsecond precision (6 digits), rather than +millisecond precision (3 digits). This makes the output format consistent with the +default string output of serializers.DateTimeField and serializers.TimeField.

+

This change does not affect the default behavior when using serializers, +which is to serialize datetime and time instances into strings with +microsecond precision.

+

The serializer behavior can be modified if needed, using the DATETIME_FORMAT +and TIME_FORMAT settings.

+

The renderer behavior can be modified by setting a custom encoder_class +attribute on a JSONRenderer subclass.

+

Relational choices no longer displayed in OPTIONS requests.

+

Making an OPTIONS request to views that have a serializer choice field +will result in a list of the available choices being returned in the response.

+

In cases where there is a relational field, the previous behavior would be +to return a list of available instances to choose from for that relational field.

+

In order to minimise exposed information the behavior now is to not return +choices information for relational fields.

+

If you want to override this new behavior you'll need to implement a custom +metadata class.

+

See issue #3751 for more information on this behavioral change.

+
+

Other improvements

+

This release includes further work from a huge number of pull requests and issues.

+

Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.

+

The full set of itemized release notes are available here.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.5-announcement/index.html b/community/3.5-announcement/index.html new file mode 100644 index 000000000..7031729e0 --- /dev/null +++ b/community/3.5-announcement/index.html @@ -0,0 +1,715 @@ + + + + + + + 3.5 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + +

Django REST framework 3.5

+

The 3.5 release is the second in a planned series that is addressing schema +generation, hypermedia support, API client libraries, and finally realtime support.

+
+

Funding

+

The 3.5 release would not have been possible without our collaborative funding model. +If you use REST framework commercially and would like to see this work continue, +we strongly encourage you to invest in its continued development by +signing up for a paid plan.

+ + +
+ +

Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, and Machinalis.

+
+

Improved schema generation

+

Docstrings on views are now pulled through into schema definitions, allowing +you to use the schema definition to document your API.

+

There is now also a shortcut function, get_schema_view(), which makes it easier to +adding schema views to your API.

+

For example, to include a swagger schema to your API, you would do the following:

+
    +
  • +

    Run pip install django-rest-swagger.

    +
  • +
  • +

    Add 'rest_framework_swagger' to your INSTALLED_APPS setting.

    +
  • +
  • +

    Include the schema view in your URL conf:

    +
  • +
+
from rest_framework.schemas import get_schema_view
+from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
+
+schema_view = get_schema_view(
+    title='Example API',
+    renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
+)
+
+urlpatterns = [
+    url(r'^swagger/$', schema_view),
+    ...
+]
+
+ +

There have been a large number of fixes to the schema generation. These should +resolve issues for anyone using the latest version of the django-rest-swagger +package.

+

Some of these changes do affect the resulting schema structure, +so if you're already using schema generation you should make sure to review +the deprecation notes, particularly if you're currently using +a dynamic client library to interact with your API.

+

Finally, we're also now exposing the schema generation as a +publicly documented API, allowing you to more easily +override the behaviour.

+

Requests test client

+

You can now test your project using the requests library.

+

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

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

Rather than sending any HTTP requests to the network, this interface will +coerce all outgoing requests into WSGI, and call into your application directly.

+

Core API client

+

You can also now test your project by interacting with it using the coreapi +client library.

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

Again, this will call directly into the application using the WSGI interface, +rather than making actual network calls.

+

This is a good option if you are planning for clients to mainly interact with +your API using the coreapi client library, or some other auto-generated client.

+

Live tests

+

One interesting aspect of both the requests client and the coreapi client +is that they allow you to write tests in such a way that they can also be made +to run against a live service.

+

By switching the WSGI based client instances to actual instances of requests.Session +or coreapi.Client you can have the test cases make actual network calls.

+

Being able to write test cases that can exercise your staging or production +environment is a powerful tool. However in order to do this, you'll need to pay +close attention to how you handle setup and teardown to ensure a strict isolation +of test data from other live or staging data.

+

RAML support

+

We now have preliminary support for RAML documentation generation.

+

RAML Example

+

Further work on the encoding and documentation generation is planned, in order to +make features such as the 'Try it now' support available at a later date.

+

This work also now means that you can use the Core API client libraries to interact +with APIs that expose a RAML specification. The RAML codec gives some examples of +interacting with the Spotify API in this way.

+

Validation codes

+

Exceptions raised by REST framework now include short code identifiers. +When used together with our customizable error handling, this now allows you to +modify the style of API error messages.

+

As an example, this allows for the following style of error responses:

+
{
+    "message": "You do not have permission to perform this action.",
+    "code": "permission_denied"
+}
+
+

This is particularly useful with validation errors, which use appropriate +codes to identify differing kinds of failure...

+
{
+    "name": {"message": "This field is required.", "code": "required"},
+    "age": {"message": "A valid integer is required.", "code": "invalid"}
+}
+
+

Client upload & download support

+

The Python coreapi client library and the Core API command line tool both +now fully support file uploads and downloads.

+
+

Deprecations

+

Generating schemas from Router

+

The router arguments for generating a schema view, such as schema_title, +are now pending deprecation.

+

Instead of using DefaultRouter(schema_title='Example API'), you should use +the get_schema_view() function, and include the view in your URL conf.

+

Make sure to include the view before your router urls. For example:

+
from rest_framework.schemas import get_schema_view
+from my_project.routers import router
+
+schema_view = get_schema_view(title='Example API')
+
+urlpatterns = [
+    url('^$', schema_view),
+    url(r'^', include(router.urls)),
+]
+
+

Schema path representations

+

The 'pk' identifier in schema paths is now mapped onto the actually model field +name by default. This will typically be 'id'.

+

This gives a better external representation for schemas, with less implementation +detail being exposed. It also reflects the behaviour of using a ModelSerializer +class with fields = '__all__'.

+

You can revert to the previous behaviour by setting 'SCHEMA_COERCE_PATH_PK': False +in the REST framework settings.

+

Schema action name representations

+

The internal retrieve() and destroy() method names are now coerced to an +external representation of read and delete.

+

You can revert to the previous behaviour by setting 'SCHEMA_COERCE_METHOD_NAMES': {} +in the REST framework settings.

+

DjangoFilterBackend

+

The functionality of the built-in DjangoFilterBackend is now completely +included by the django-filter package.

+

You should change your imports and REST framework filter settings as follows:

+
    +
  • rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.
  • +
  • rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.
  • +
+

The existing imports will continue to work but are now pending deprecation.

+

CoreJSON media type

+

The media type for CoreJSON is now application/json+coreapi, rather than +the previous application/vnd.json+coreapi. This brings it more into line with +other custom media types, such as those used by Swagger and RAML.

+

The clients currently accept either media type. The old style-media type will +be deprecated at a later date.

+

ModelSerializer 'fields' and 'exclude'

+

ModelSerializer and HyperlinkedModelSerializer must include either a fields +option, or an exclude option. The fields = '__all__' shortcut may be used to +explicitly include all fields.

+

Failing to set either fields or exclude raised a pending deprecation warning +in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.

+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.6-announcement/index.html b/community/3.6-announcement/index.html new file mode 100644 index 000000000..1f851891e --- /dev/null +++ b/community/3.6-announcement/index.html @@ -0,0 +1,657 @@ + + + + + + + 3.6 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + +

Django REST framework 3.6

+

The 3.6 release adds two major new features to REST framework.

+
    +
  1. Built-in interactive API documentation support.
  2. +
  3. A new JavaScript client library.
  4. +
+

API Documentation

+

Above: The interactive API documentation.

+
+

Funding

+

The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding model.

+

If you use REST framework commercially and would like to see this work continue, +we strongly encourage you to invest in its continued development by +signing up for a paid plan.

+ + +
+ +

Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Machinalis, Rollbar, and MicroPyramid.

+
+

Interactive API documentation

+

REST framework's new API documentation supports a number of features:

+
    +
  • Live API interaction.
  • +
  • Support for various authentication schemes.
  • +
  • Code snippets for the Python, JavaScript, and Command Line clients.
  • +
+

The coreapi library is required as a dependency for the API docs. Make sure +to install the latest version (2.3.0 or above). The pygments and markdown +libraries are optional but recommended.

+

To install the API documentation, you'll need to include it in your projects URLconf:

+
from rest_framework.documentation import include_docs_urls
+
+API_TITLE = 'API title'
+API_DESCRIPTION = '...'
+
+urlpatterns = [
+    ...
+    url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
+]
+
+

Once installed you should see something a little like this:

+

API Documentation

+

We'll likely be making further refinements to the API documentation over the +coming weeks. Keep in mind that this is a new feature, and please do give +us feedback if you run into any issues or limitations.

+

For more information on documenting your API endpoints see the "Documenting your API" section.

+
+

JavaScript client library

+

The JavaScript client library allows you to load an API schema, and then interact +with that API at an application layer interface, rather than constructing fetch +requests explicitly.

+

Here's a brief example that demonstrates:

+
    +
  • Loading the client library and schema.
  • +
  • Instantiating an authenticated client.
  • +
  • Making an API request using the client.
  • +
+

index.html

+
<html>
+    <head>
+        <script src="/static/rest_framework/js/coreapi-0.1.0.js"></script>
+        <script src="/docs/schema.js"></script>
+        <script>
+            const coreapi = window.coreapi
+            const schema = window.schema
+
+            // Instantiate a client...
+            let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})
+            let client = coreapi.Client({auth: auth})
+
+            // Make an API request...
+            client.action(schema, ['projects', 'list']).then(function(result) {
+                alert(result)
+            })
+        </script>
+    </head>
+</html>
+
+

The JavaScript client library supports various authentication schemes, and can be +used by your project itself, or as an external client interacting with your API.

+

The client is not limited to usage with REST framework APIs, although it does +currently only support loading CoreJSON API schemas. Support for Swagger and +other API schemas is planned.

+

For more details see the JavaScript client library documentation.

+

Authentication classes for the Python client library

+

Previous authentication support in the Python client library was limited to +allowing users to provide explicit header values.

+

We now have better support for handling the details of authentication, with +the introduction of the BasicAuthentication, TokenAuthentication, and +SessionAuthentication schemes.

+

You can include the authentication scheme when instantiating a new client.

+
auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')
+client = coreapi.Client(auth=auth)
+
+

For more information see the Python client library documentation.

+
+

Deprecations

+

Updating coreapi

+

If you're using REST framework's schema generation, or want to use the API docs, +then you'll need to update to the latest version of coreapi. (2.3.0)

+

Generating schemas from Router

+

The 3.5 "pending deprecation" of router arguments for generating a schema view, such as schema_title, schema_url and schema_renderers, have now been escalated to a +"deprecated" warning.

+

Instead of using DefaultRouter(schema_title='Example API'), you should use the get_schema_view() function, and include the view explicitly in your URL conf.

+

DjangoFilterBackend

+

The 3.5 "pending deprecation" warning of the built-in DjangoFilterBackend has now +been escalated to a "deprecated" warning.

+

You should change your imports and REST framework filter settings as follows:

+
    +
  • rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.
  • +
  • rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.
  • +
+
+

What's next

+

There are likely to be a number of refinements to the API documentation and +JavaScript client library over the coming weeks, which could include some of the following:

+
    +
  • Support for private API docs, requiring login.
  • +
  • File upload and download support in the JavaScript client & API docs.
  • +
  • Comprehensive documentation for the JavaScript client library.
  • +
  • Automatically including authentication details in the API doc code snippets.
  • +
  • Adding authentication support in the command line client.
  • +
  • Support for loading Swagger and other schemas in the JavaScript client.
  • +
  • Improved support for documenting parameter schemas and response schemas.
  • +
  • Refining the API documentation interaction modal.
  • +
+

Once work on those refinements is complete, we'll be starting feature work +on realtime support, for the 3.7 release.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.7-announcement/index.html b/community/3.7-announcement/index.html new file mode 100644 index 000000000..4cbe35d5e --- /dev/null +++ b/community/3.7-announcement/index.html @@ -0,0 +1,591 @@ + + + + + + + 3.7 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+ +
+ +
+ + + + + +

Django REST framework 3.7

+

The 3.7 release focuses on improvements to schema generation and the interactive API documentation.

+

This release has been made possible by Bayer who have sponsored the release.

+

+
+

Funding

+

If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by +signing up for a paid plan.

+ + +
+ +

As well as our release sponsor, we'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.

+
+

Customizing API docs & schema generation.

+

The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.

+

In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.

+

Let's take a quick look at using the new functionality...

+

The APIView class has a schema attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the AutoSchema class.

+
from rest_framework.views import APIView
+from rest_framework.schemas import AutoSchema
+
+class CustomView(APIView):
+    schema = AutoSchema()  # Included for demonstration only. This is the default behavior.
+
+

We can remove a view from the API schema and docs, like so:

+
class CustomView(APIView):
+    schema = None
+
+

If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...

+
class CustomView(APIView):
+    schema = AutoSchema(manual_fields=[
+        coreapi.Field('search', location='query')
+    ])
+
+

To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the ManualSchema class instead...

+
class CustomView(APIView):
+    schema = ManualSchema(fields=[...])
+
+

For more advanced behaviors you can subclass AutoSchema to provide for customized schema generation, and apply that to particular views.

+
class CustomView(APIView):
+    schema = CustomizedSchemaGeneration()
+
+

For full details on the new functionality, please see the Schema Documentation.

+
+

Django 2.0 support

+

REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.

+
+

Minor fixes and improvements

+

There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.

+

The number of open tickets against the project currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.

+
+

Deprecations

+

exclude_from_schema

+

Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator and now PendingDeprecation. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.

+

For APIView you should instead set a schema = None attribute on the view class.

+

For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).

+

DjangoFilterBackend

+

The DjangoFilterBackend was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.

+

The functionality remains fully available, but is instead provided in the django-filter package.

+
+

What's next

+

We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.

+

This will likely be timed so that any REST framework development here ties in with similar work on API Star.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.8-announcement/index.html b/community/3.8-announcement/index.html new file mode 100644 index 000000000..be328a3f9 --- /dev/null +++ b/community/3.8-announcement/index.html @@ -0,0 +1,560 @@ + + + + + + + 3.8 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + + + +

Django REST framework 3.8

+

The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying +the foundations for future changes.

+
+

Funding

+

If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by +signing up for a paid plan.

+

We'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.

+
+

Breaking Changes

+

Altered the behaviour of read_only plus default on Field.

+

#5886 read_only fields will now always be excluded from writable fields.

+

Previously read_only fields when combined with a default value would use the default for create and update +operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted source +attributes on nullable relations.

+

In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in +the view:

+
def perform_create(self, serializer):
+    serializer.save(owner=self.request.user)
+
+

Alternatively you may override save() or create() or update() on the serializer as appropriate.

+
+

Deprecations

+

action decorator replaces list_route and detail_route

+

#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.

+

Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely +in 3.10.

+

The new action decorator takes a boolean detail argument.

+
    +
  • Replace detail_route uses with @action(detail=True).
  • +
  • Replace list_route uses with @action(detail=False).
  • +
+

exclude_from_schema

+

Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator are now deprecated. They will be removed entirely in 3.9.

+

For APIView you should instead set a schema = None attribute on the view class.

+

For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).

+
+

Minor fixes and improvements

+

There are a large number of minor fixes and improvements in this release. See the release notes page +for a complete listing.

+

What's next

+

We're currently working towards moving to using OpenAPI as our default schema output. We'll also be revisiting our API documentation generation and client libraries.

+

We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the coreapi and coreschema libraries, and instead use apistar for the API documentation generation, schema generation, and API client libraries.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/3.9-announcement/index.html b/community/3.9-announcement/index.html new file mode 100644 index 000000000..487096101 --- /dev/null +++ b/community/3.9-announcement/index.html @@ -0,0 +1,659 @@ + + + + + + + 3.9 Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + +

Django REST framework 3.9

+

The 3.9 release gives access to extra actions in the Browsable API, introduces composable permissions and built-in OpenAPI schema support. (Formerly known as Swagger)

+
+

Funding

+

If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by +signing up for a paid plan.

+ + +
+ +

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Auklet, Rollbar, Cadre, Load Impact, and Kloudless.

+
+

Built-in OpenAPI schema support

+

REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger)

+

Specifically:

+
    +
  • There are now OpenAPIRenderer, and JSONOpenAPIRenderer classes that deal with encoding coreapi.Document instances into OpenAPI YAML or OpenAPI JSON.
  • +
  • The get_schema_view(...) method now defaults to OpenAPI YAML, with CoreJSON as a secondary +option if it is selected via HTTP content negotiation.
  • +
  • There is a new management command generateschema, which you can use to dump +the schema into your repository.
  • +
+

Here's an example of adding an OpenAPI schema to the URL conf:

+
from rest_framework.schemas import get_schema_view
+from rest_framework.renderers import JSONOpenAPIRenderer
+
+schema_view = get_schema_view(
+    title='Server Monitoring API',
+    url='https://www.example.org/api/',
+    renderer_classes=[JSONOpenAPIRenderer]
+)
+
+urlpatterns = [
+    url('^schema.json$', schema_view),
+    ...
+]
+
+ +

And here's how you can use the generateschema management command:

+
$ python manage.py generateschema --format openapi > schema.yml
+
+ +

There's lots of different tooling that you can use for working with OpenAPI +schemas. One option that we're working on is the API Star +command line tool.

+

You can use apistar to validate your API schema:

+
$ apistar validate --path schema.json --format openapi
+✓ Valid OpenAPI schema.
+
+ +

Or to build API documentation:

+
$ apistar docs --path schema.json --format openapi
+✓ Documentation built at "build/index.html".
+
+ +

API Star also includes a dynamic client library +that uses an API schema to automatically provide a client library interface for making requests.

+

Composable permission classes

+

You can now compose permission classes using the and/or operators, & and |.

+

For example...

+
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
+
+ +

If you're using custom permission classes then make sure that you are subclassing +from BasePermission in order to enable this support.

+

ViewSet Extra Actions available in the Browsable API

+

Following the introduction of the action decorator in v3.8, extra actions defined on a ViewSet are now available +from the Browsable API.

+

Extra Actions displayed in the Browsable API

+

When defined, a dropdown of "Extra Actions", appropriately filtered to detail/non-detail actions, is displayed.

+
+

Supported Versions

+

REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1.

+
+

Deprecations

+

DjangoObjectPermissionsFilter moved to third-party package.

+

The DjangoObjectPermissionsFilter class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11.

+

It has been moved to the third-party djangorestframework-guardian +package. Please use this instead.

+

Router argument/method renamed to use basename for consistency.

+
    +
  • The Router.register base_name argument has been renamed in favor of basename.
  • +
  • The Router.get_default_base_name method has been renamed in favor of Router.get_default_basename. #5990
  • +
+

See #5990.

+

base_name and get_default_base_name() are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11.

+

action decorator replaces list_route and detail_route

+

Both list_route and detail_route are now deprecated in favour of the single action decorator. +They will be removed entirely in 3.10.

+

The action decorator takes a boolean detail argument.

+
    +
  • Replace detail_route uses with @action(detail=True).
  • +
  • Replace list_route uses with @action(detail=False).
  • +
+

exclude_from_schema

+

Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view have now been removed.

+

For APIView you should instead set a schema = None attribute on the view class.

+

For function-based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).

+
+

Minor fixes and improvements

+

There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.

+

What's next

+

We're planning to iteratively work towards OpenAPI becoming the standard schema +representation. This will mean that the coreapi dependency will gradually become +removed, and we'll instead generate the schema directly, rather than building +a CoreAPI Document object.

+

OpenAPI has clearly become the standard for specifying Web APIs, so there's not +much value any more in our schema-agnostic document model. Making this change +will mean that we'll more easily be able to take advantage of the full set of +OpenAPI functionality.

+

This will also make a wider range of tooling available.

+

We'll focus on continuing to develop the API Star +library and client tool into a recommended option for generating API docs, +validating API schemas, and providing a dynamic client library.

+

There's also a huge amount of ongoing work on maturing the ASGI landscape, +with the possibility that some of this work will eventually feed back into +Django.

+

There will be further work on the Uvicorn +web server, as well as lots of functionality planned for the Starlette +web framework, which is building a foundational set of tooling for working with +ASGI.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/contributing/index.html b/community/contributing/index.html new file mode 100644 index 000000000..fb66cb01a --- /dev/null +++ b/community/contributing/index.html @@ -0,0 +1,673 @@ + + + + + + + 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, first create a Fork from the +Django REST Framework repo on GitHub.

+

Then clone your fork. The clone command will look like this, with your GitHub +username instead of YOUR-USERNAME:

+
git clone https://github.com/YOUR-USERNAME/Spoon-Knife
+
+

See GitHub's Fork a Repo Guide for more help.

+

Changes should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.

+

Testing

+

To run the tests, clone the repository, and then:

+
# Setup the virtual environment
+python3 -m venv env
+source env/bin/activate
+pip install django
+pip install -r requirements.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 on all supported versions of Python and 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 documentation into the site directory.

+

You can build the documentation and open a preview in a browser window by using the serve command.

+
mkdocs serve
+
+

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.
  • +
  • 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.
+
+---
+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/funding/index.html b/community/funding/index.html new file mode 100644 index 000000000..859ad1b94 --- /dev/null +++ b/community/funding/index.html @@ -0,0 +1,873 @@ + + + + + + + Funding - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + + + +

Funding

+

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

+

We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.

+

Signing up for a paid plan will:

+
    +
  • Directly contribute to faster releases, more features, and higher quality software.
  • +
  • Allow more time to be invested in documentation, issue triage, and community support.
  • +
  • Safeguard the future development of REST framework.
  • +
+

REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.

+
+

What funding has enabled so far

+
    +
  • The 3.4 and 3.5 releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
  • +
  • The 3.6 release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
  • +
  • The 3.7 release, made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
  • +
  • The recent 3.8 release.
  • +
  • Tom Christie, the creator of Django REST framework, working on the project full-time.
  • +
  • Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
  • +
  • A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
  • +
  • Contracting development time for the work on the JavaScript client library and API documentation tooling.
  • +
+
+

What future funding will enable

+
    +
  • Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
  • +
  • Better authentication defaults, possibly bringing JWT & CORs support into the core package.
  • +
  • Securing the community & operations manager position long-term.
  • +
  • Opening up and securing a part-time position to focus on ticket triage and resolution.
  • +
  • Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
  • +
+

Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.

+
+

What our sponsors and users say

+
+

As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.

+

— José Padilla, Django REST framework contributor

+
+

 

+
+

The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.

+

— Filipe Ximenes, Vinta Software

+
+

 

+
+

It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality. +DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.

+

— Andrew Conti, Django REST framework user

+
+
+

Individual plan

+

This subscription is recommended for individuals with an interest in seeing REST framework continue to improve.

+

If you are using REST framework as a full-time employee, consider recommending that your company takes out a corporate plan.

+
+
+
+
+ {{ symbol }} + {{ rates.personal1 }} + /month{% if vat %} +VAT{% endif %} +
+
Individual
+
+
+ Support ongoing development +
+
+ Credited on the site +
+
+ +
+
+
+ +
+ +

Billing is monthly and you can cancel at any time.

+
+

Corporate plans

+

These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.

+

In exchange for funding you'll also receive advertising space on our site, allowing you to promote your company or product to many tens of thousands of developers worldwide.

+

Our professional and premium plans also include priority support. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.

+
+
+
+
+ {{ symbol }} + {{ rates.corporate1 }} + /month{% if vat %} +VAT{% endif %} +
+
Basic
+
+
+ Support ongoing development +
+
+ Funding page ad placement +
+
+ +
+
+
+
+
+ {{ symbol }} + {{ rates.corporate2 }} + /month{% if vat %} +VAT{% endif %} +
+
Professional
+
+
+ Support ongoing development +
+
+ Sidebar ad placement +
+
+ Priority support for your engineers +
+
+ +
+
+
+
+
+ {{ symbol }} + {{ rates.corporate3 }} + /month{% if vat %} +VAT{% endif %} +
+
Premium
+
+
+ Support ongoing development +
+
+ Homepage ad placement +
+
+ Sidebar ad placement +
+
+ Priority support for your engineers +
+
+ +
+
+
+ +
+ +

Billing is monthly and you can cancel at any time.

+

Once you've signed up, we will contact you via email and arrange your ad placements on the site.

+

For further enquires please contact funding@django-rest-framework.org.

+
+

Accountability

+

In an effort to keep the project as transparent as possible, we are releasing monthly progress reports and regularly include financial reports and cost breakdowns.

+ + +

+ +

+
+
+

Stay up to date, with our monthly progress reports...

+
+ + +
+
+ + +
+ +
+
+
+
+ +

+
+

Frequently asked questions

+

Q: Can you issue monthly invoices? +A: Yes, we are happy to issue monthly invoices. Please just email us and let us know who to issue the invoice to (name and address) and which email address to send it to each month.

+

Q: Does sponsorship include VAT? +A: Sponsorship is VAT exempt.

+

Q: Do I have to sign up for a certain time period? +A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.

+

Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time? +A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.

+

Q: Are you only looking for corporate sponsors? +A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.

+
+

Our sponsors

+
+ + + + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/jobs/index.html b/community/jobs/index.html new file mode 100644 index 000000000..2130f0336 --- /dev/null +++ b/community/jobs/index.html @@ -0,0 +1,500 @@ + + + + + + + Jobs - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Jobs

+

Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring.

+

Places to look for Django REST Framework Jobs

+ +

Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us.

+

Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/kickstarter-announcement/index.html b/community/kickstarter-announcement/index.html new file mode 100644 index 000000000..65bfa4f25 --- /dev/null +++ b/community/kickstarter-announcement/index.html @@ -0,0 +1,619 @@ + + + + + + + Kickstarter Announcement - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Kickstarting Django REST framework 3

+
+ + +
+

In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.

+

Project details

+

This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:

+
    +
  • Faster, simpler and easier-to-use serializers.
  • +
  • An alternative admin-style interface for the browsable API.
  • +
  • Search and filtering controls made accessible in the browsable API.
  • +
  • Alternative API pagination styles.
  • +
  • Documentation around API versioning.
  • +
  • Triage of outstanding tickets.
  • +
  • Improving the ongoing quality and maintainability of the project.
  • +
+

Full details are available now on the project page.

+

If you're interested in helping make sustainable open source development a reality please visit the Kickstarter page and consider funding the project.

+

I can't wait to see where this takes us!

+

Many thanks to everyone for your support so far,

+

Tom Christie :)

+
+

Sponsors

+

We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.

+
+

Platinum sponsors

+

Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.

+ + + + +
+ +
+

Gold sponsors

+

Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.

+ + +
+ +
+

Silver sponsors

+

The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have chosen to privately support the project at this level.

+ + +
+ +

Individual backers: Paul Hallett, Paul Whipp, Dylan Roy, Jannis Leidel, Xavier Ordoquy, Johannes Spielmann, Rob Spectre, Chris Heisel, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.

+
+

Advocates

+

The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!

+

Individual backers: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.

+

Corporate backers: Savannah Informatics, Prism Skylabs, Musical Operating Devices.

+
+

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!

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/mozilla-grant/index.html b/community/mozilla-grant/index.html new file mode 100644 index 000000000..0ae0ec1c9 --- /dev/null +++ b/community/mozilla-grant/index.html @@ -0,0 +1,548 @@ + + + + + + + Mozilla Grant - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Mozilla Grant

+

We have recently been awarded a Mozilla grant, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.

+

Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.

+

The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format.

+

Specifically, the work includes:

+

Client libraries

+

This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.

+
    +
  • Client library support in REST framework.
  • +
  • Schema & hypermedia support for REST framework APIs.
  • +
  • A test client, allowing you to write tests that emulate a client library interacting with your API.
  • +
  • New tutorial sections on using client libraries to interact with REST framework APIs.
  • +
  • Python client library.
  • +
  • JavaScript client library.
  • +
  • Command line client.
  • +
+

Realtime APIs

+

The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.

+
    +
  • Support for API subscription endpoints, using REST framework and Django Channels.
  • +
  • New tutorial section on building realtime API endpoints with REST framework.
  • +
  • Realtime support in the Python & Javascript client libraries.
  • +
+

Accountability

+

In order to ensure that I can be fully focused on trying to secure a sustainable +& well-funded open source business I will be leaving my current role at DabApps +at the end of May 2016.

+

I have formed a UK limited company, Encode, which will +act as the business entity behind REST framework. I will be issuing monthly reports +from Encode on progress both towards the Mozilla grant, and for development time +funded via the REST framework paid plans.

+ + +

+ +

+
+
+

Stay up to date, with our monthly progress reports...

+
+ + +
+
+ + +
+ +
+
+
+
+ +

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/project-management/index.html b/community/project-management/index.html new file mode 100644 index 000000000..c67871f70 --- /dev/null +++ b/community/project-management/index.html @@ -0,0 +1,663 @@ + + + + + + + Project management - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Project management

+
+

"No one can whistle a symphony; it takes a whole orchestra to play it"

+

— Halford E. Luccock

+
+

This document outlines our project management processes for REST framework.

+

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

+
+

Maintenance team

+

We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.

+

Current team

+

The maintenance team for Q4 2015:

+ +

Maintenance cycles

+

Each maintenance cycle is initiated by an issue being opened with the Process label.

+
    +
  • To be considered for a maintainer role simply comment against the issue.
  • +
  • Existing members must explicitly opt-in to the next cycle by check-marking their name.
  • +
  • The final decision on the incoming team will be made by @tomchristie.
  • +
+

Members of the maintenance team will be added as collaborators to the repository.

+

The following template should be used for the description of the issue, and serves as the formal process for selecting the team.

+
This issue is for determining the maintenance team for the *** period.
+
+Please see the [Project management](https://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
+
+---
+
+#### Renewing existing members.
+
+The following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.
+
+- [ ] @***
+- [ ] @***
+- [ ] @***
+- [ ] @***
+- [ ] @***
+
+---
+
+#### New members.
+
+If you wish to be considered for this or a future date, please comment against this or subsequent issues.
+
+To modify this process for future maintenance cycles make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
+
+

Responsibilities of team members

+

Team members have the following responsibilities.

+
    +
  • Close invalid or resolved tickets.
  • +
  • Add triage labels and milestones to tickets.
  • +
  • Merge finalized pull requests.
  • +
  • Build and deploy the documentation, using mkdocs gh-deploy.
  • +
  • Build and update the included translation packs.
  • +
+

Further notes for maintainers:

+
    +
  • Code changes should come in the form of a pull request - do not push directly to master.
  • +
  • Maintainers should typically not merge their own pull requests.
  • +
  • Each issue/pull request should have exactly one label once triaged.
  • +
  • Search for un-triaged issues with is:open no:label.
  • +
+

It should be noted that participating actively in the REST framework project clearly does not require being part of the maintenance team. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.

+
+

Release process

+

The release manager is selected on every quarterly maintenance cycle.

+
    +
  • The manager should be selected by @tomchristie.
  • +
  • The manager will then have the maintainer role added to PyPI package.
  • +
  • The previous manager will then have the maintainer role removed from the PyPI package.
  • +
+

Our PyPI releases will be handled by either the current release manager, or by @tomchristie. Every release should have an open issue tagged with the Release label and marked against the appropriate milestone.

+

The following template should be used for the description of the issue, and serves as a release checklist.

+
Release manager is @***.
+Pull request is #***.
+
+During development cycle:
+
+- [ ] Upload the new content to be translated to [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
+
+
+Checklist:
+
+- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).
+- [ ] Update supported versions:
+    - [ ] `setup.py` `python_requires` list
+    - [ ] `setup.py` Python & Django version trove classifiers
+    - [ ] `README` Python & Django versions
+    - [ ] `docs` Python & Django versions
+- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
+- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
+- [ ] Confirm with @tomchristie that release is finalized and ready to go.
+- [ ] Ensure that release date is included in pull request.
+- [ ] Merge the release pull request.
+- [ ] Push the package to PyPI with `./setup.py publish`.
+- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.
+- [ ] Deploy the documentation with `mkdocs gh-deploy`.
+- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
+- [ ] Make a release announcement on twitter.
+- [ ] Close the milestone on GitHub.
+
+To modify this process for future releases make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
+
+

When pushing the release to PyPI ensure that your environment has been installed from our development requirement.txt, so that documentation and PyPI installs are consistently being built against a pinned set of packages.

+
+

Translations

+

The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the transifex service.

+

Managing Transifex

+

The official Transifex client is used to upload and download translations to Transifex. The client is installed using pip:

+
pip install transifex-client
+
+

To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a ~/.transifexrc file which contains your credentials.

+
[https://www.transifex.com]
+username = ***
+token = ***
+password = ***
+hostname = https://www.transifex.com
+
+

Upload new source files

+

When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:

+
# 1. Update the source django.po file, which is the US English version.
+cd rest_framework
+django-admin makemessages -l en_US
+# 2. Push the source django.po file to Transifex.
+cd ..
+tx push -s
+
+

When pushing source files, Transifex will update the source strings of a resource to match those from the new source file.

+

Here's how differences between the old and new source files will be handled:

+
    +
  • New strings will be added.
  • +
  • Modified strings will be added as well.
  • +
  • Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then Transifex Translation Memory will automatically include the translation string.
  • +
+

Download translations

+

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

+
# 3. Pull the translated django.po files from Transifex.
+tx pull -a --minimum-perc 10
+cd rest_framework
+# 4. Compile the binary .mo files for all supported languages.
+django-admin compilemessages
+
+
+

Project requirements

+

All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the requirements directory. The requirements files are referenced from the tox.ini configuration file, ensuring we have a single source of truth for package versions used in testing.

+

Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the pip list --outdated.

+
+

Project ownership

+

The PyPI package is owned by @tomchristie. As a backup @j4mie also has ownership of the package.

+

If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties.

+

Outstanding management & ownership issues

+

The following issues still need to be addressed:

+
    +
  • Ensure @jamie has back-up access to the django-rest-framework.org domain setup and admin.
  • +
  • Document ownership of the live example API.
  • +
  • Document ownership of the mailing list and IRC channel.
  • +
  • Document ownership and management of the security mailing list.
  • +
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/release-notes/index.html b/community/release-notes/index.html new file mode 100644 index 000000000..81bcacece --- /dev/null +++ b/community/release-notes/index.html @@ -0,0 +1,1699 @@ + + + + + + + Release Notes - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Release Notes

+

Versioning

+

Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.

+

Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy. You should read the release notes carefully before upgrading between medium point releases.

+

Major version numbers (x.0.0) are reserved for substantial project milestones.

+

Deprecation policy

+

REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy.

+

The timeline for deprecation of a feature present in version 1.0 would work as follows:

+
    +
  • +

    Version 1.1 would remain fully backwards compatible with 1.0, but would raise RemovedInDRF13Warning warnings, subclassing PendingDeprecationWarning, if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test, you'll be warned of any API changes you need to make.

    +
  • +
  • +

    Version 1.2 would escalate these warnings to subclass DeprecationWarning, which is loud by default.

    +
  • +
  • +

    Version 1.3 would remove the deprecated bits of API entirely.

    +
  • +
+

Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.

+

Upgrading

+

To upgrade Django REST framework to the latest version, use pip:

+
pip install -U djangorestframework
+
+

You can determine your currently installed version using pip show:

+
pip show djangorestframework
+
+
+

3.10.x series

+

3.10.3

+
    +
  • Include API version in OpenAPI schema generation, defaulting to empty string.
  • +
  • Add pagination properties to OpenAPI response schemas.
  • +
  • Add missing "description" property to OpenAPI response schemas.
  • +
  • Only include "required" for non-empty cases in OpenAPI schemas.
  • +
  • Fix response schemas for "DELETE" case in OpenAPI schemas.
  • +
  • Use an array type for list view response schemas.
  • +
  • Use consistent lowerInitialCamelCase style in OpenAPI operation IDs.
  • +
  • Fix minLength/maxLength/minItems/maxItems properties in OpenAPI schemas.
  • +
  • Only call FileField.url once in serialization, for improved performance.
  • +
  • +

    Fix an edge case where throttling calcualtions could error after a configuration change.

    +
  • +
  • +

    TODO

    +
  • +
+

3.10.2

+

Date: 29th July 2019

+
    +
  • Various OpenAPI schema fixes.
  • +
  • Ability to specify urlconf in include_docs_urls.
  • +
+

3.10.1

+

Date: 17th July 2019

+
    +
  • Don't include autocomplete fields on TokenAuth admin, since it forces constraints on custom user models & admin.
  • +
  • Require uritemplate for OpenAPI schema generation, but not coreapi.
  • +
+

3.10.0

+

Date: 15th July 2019

+
    +
  • Switch to OpenAPI schema generation.
  • +
  • Drop Python 2 support.
  • +
  • Add generateschema --generator_class CLI option
  • +
  • Updated PyYaml dependency for OpenAPI schema generation to pyyaml>=5.1 #6680
  • +
  • Resolve DeprecationWarning with markdown. #6317
  • +
  • Use user.get_username in templates, in preference to user.username.
  • +
  • Fix for cursor pagination issue that could occur after object deletions.
  • +
  • Fix for nullable fields with source="*"
  • +
  • Always apply all throttle classes during throttling checks.
  • +
  • Updates to jQuery and Markdown dependencies.
  • +
  • Don't strict disallow redundant SerializerMethodField field name arguments.
  • +
  • Don't render extra actions in browable API if not authenticated.
  • +
  • Strip null characters from search parameters.
  • +
+

3.9.x series

+

3.9.4

+

Date: 10th May 2019

+

This is a maintenance release that fixes an error handling bug under Python 2.

+

3.9.3

+

Date: 29th April 2019

+

This is the last Django REST Framework release that will support Python 2. +Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.

+
    +
  • Adjusted the compat check for django-guardian to allow the last guardian + version (v1.4.9) compatible with Python 2. #6613
  • +
+

3.9.2

+

Date: 3rd March 2019

+
    +
  • Routers: invalidate _urls cache on register() #6407
  • +
  • Deferred schema renderer creation to avoid requiring pyyaml. #6416
  • +
  • Added 'request_forms' block to base.html #6340
  • +
  • Fixed SchemaView to reset renderer on exception. #6429
  • +
  • Update Django Guardian dependency. #6430
  • +
  • Ensured support for Django 2.2 #6422 & #6455
  • +
  • Made templates compatible with session-based CSRF. #6207
  • +
  • Adjusted field validators to accept non-list iterables. #6282
  • +
  • Added SearchFilter.get_search_fields() hook. #6279
  • +
  • Fix DeprecationWarning when accessing collections.abc classes via collections #6268
  • +
  • Allowed Q objects in limit_choices_to introspection. #6472
  • +
  • Added lazy evaluation to composed permissions. #6463
  • +
  • Add negation ~ operator to permissions composition #6361
  • +
  • Avoided calling distinct on annotated fields in SearchFilter. #6240
  • +
  • Introduced RemovedInDRF…Warning classes to simplify deprecations. #6480
  • +
+

3.9.1

+

Date: 16th January 2019

+
    +
  • Resolve XSS issue in browsable API. #6330
  • +
  • Upgrade Bootstrap to 3.4.0 to resolve XSS issue.
  • +
  • Resolve issues with composable permissions. #6299
  • +
  • Respect limit_choices_to on foreign keys. #6371
  • +
+

3.9.0

+

Date: 18th October 2018

+
    +
  • Improvements to ViewSet extra actions #5605
  • +
  • Fix action support for ViewSet suffixes #6081
  • +
  • Allow action docs sections #6060
  • +
  • Deprecate the Router.register base_name argument in favor of basename. #5990
  • +
  • Deprecate the Router.get_default_base_name method in favor of Router.get_default_basename. #5990
  • +
  • Change CharField to disallow null bytes. #6073 + To revert to the old behavior, subclass CharField and remove ProhibitNullCharactersValidator from the validators. + python + class NullableCharField(serializers.CharField): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)]
  • +
  • Add OpenAPIRenderer and generate_schema management command. #6229
  • +
  • Add OpenAPIRenderer by default, and add schema docs. #6233
  • +
  • Allow permissions to be composed #5753
  • +
  • Allow nullable BooleanField in Django 2.1 #6183
  • +
  • Add testing of Python 3.7 support #6141
  • +
  • Test using Django 2.1 final release. #6109
  • +
  • Added djangorestframework-datatables to third-party packages #5931
  • +
  • Change ISO 8601 date format to exclude year/month #5936
  • +
  • Update all pypi.python.org URLs to pypi.org #5942
  • +
  • Ensure that html forms (multipart form data) respect optional fields #5927
  • +
  • Allow hashing of ErrorDetail. #5932
  • +
  • Correct schema parsing for JSONField #5878
  • +
  • Render descriptions (from help_text) using safe #5869
  • +
  • Removed input value from deault_error_message #5881
  • +
  • Added min_value/max_value support in DurationField #5643
  • +
  • Fixed instance being overwritten in pk-only optimization try/except block #5747
  • +
  • Fixed AttributeError from items filter when value is None #5981
  • +
  • Fixed Javascript e.indexOf is not a function error #5982
  • +
  • Fix schemas for extra actions #5992
  • +
  • Improved get_error_detail to use error_dict/error_list #5785
  • +
  • Imprvied URLs in Admin renderer #5988
  • +
  • Add "Community" section to docs, minor cleanup #5993
  • +
  • Moved guardian imports out of compat #6054
  • +
  • Deprecate the DjangoObjectPermissionsFilter class, moved to the djangorestframework-guardian package. #6075
  • +
  • Drop Django 1.10 support #5657
  • +
  • Only catch TypeError/ValueError for object lookups #6028
  • +
  • Handle models without .objects manager in ModelSerializer. #6111
  • +
  • Improve ModelSerializer.create() error message. #6112
  • +
  • Fix CSRF cookie check failure when using session auth with django 1.11.6+ #6113
  • +
  • Updated JWT docs. #6138
  • +
  • Fix autoescape not getting passed to urlize_quoted_links filter #6191
  • +
+

3.8.x series

+

3.8.2

+

Date: 6th April 2018

+
    +
  • Fix read_only + default unique_together validation. #5922
  • +
  • authtoken.views import coreapi from rest_framework.compat, not directly. #5921
  • +
  • Docs: Add missing argument 'detail' to Route #5920
  • +
+

3.8.1

+

Date: 4th April 2018

+
    +
  • +

    Use old url_name behavior in route decorators #5915

    +

    For list_route and detail_route maintain the old behavior of url_name, +basing it on the url_path instead of the function name.

    +
  • +
+

3.8.0

+

Date: 3rd April 2018

+
    +
  • +

    Breaking Change: Alter read_only plus default behaviour. #5886

    +

    read_only fields will now always be excluded from writable fields.

    +

    Previously read_only fields with a default value would use the default for create and update operations.

    +

    In order to maintain the old behaviour you may need to pass the value of read_only fields when calling save() in +the view:

    +
    def perform_create(self, serializer):
    +    serializer.save(owner=self.request.user)
    +
    +

    Alternatively you may override save() or create() or update() on the serializer as appropriate.

    +
  • +
  • +

    Correct allow_null behaviour when required=False #5888

    +

    Without an explicit default, allow_null implies a default of null for outgoing serialization. Previously such +fields were being skipped when read-only or otherwise not required.

    +

    Possible backwards compatibility break if you were relying on such fields being excluded from the outgoing +representation. In order to restore the old behaviour you can override data to exclude the field when None.

    +

    For example:

    +
    @property
    +def data(self):
    +    """
    +    Drop `maybe_none` field if None.
    +    """
    +    data = super().data
    +    if 'maybe_none' in data and data['maybe_none'] is None:
    +        del data['maybe_none']
    +    return data
    +
    +
  • +
  • +

    Refactor dynamic route generation and improve viewset action introspectibility. #5705

    +

    ViewSets have been provided with new attributes and methods that allow +it to introspect its set of actions and the details of the current action.

    +
      +
    • Merged list_route and detail_route into a single action decorator.
    • +
    • Get all extra actions on a ViewSet with .get_extra_actions().
    • +
    • Extra actions now set the url_name and url_path on the decorated method.
    • +
    • url_name is now based on the function name, instead of the url_path, + as the path is not always suitable (e.g., capturing arguments in the path).
    • +
    • Enable action url reversing through .reverse_action() method (added in 3.7.4)
    • +
    • Example reverse call: self.reverse_action(self.custom_action.url_name)
    • +
    • Add detail initkwarg to indicate if the current action is operating on a + collection or a single instance.
    • +
    +

    Additional changes:

    +
      +
    • Deprecated list_route & detail_route in favor of action decorator with detail boolean.
    • +
    • Deprecated dynamic list/detail route variants in favor of DynamicRoute with detail boolean.
    • +
    • Refactored the router's dynamic route generation.
    • +
    • list_route and detail_route maintain the old behavior of url_name, + basing it on the url_path instead of the function name.
    • +
    +
  • +
  • +

    Fix formatting of the 3.7.4 release note #5704

    +
  • +
  • Docs: Update DRF Writable Nested Serializers references #5711
  • +
  • Docs: Fixed typo in auth URLs example. #5713
  • +
  • Improve composite field child errors #5655
  • +
  • Disable HTML inputs for dict/list fields #5702
  • +
  • Fix typo in HostNameVersioning doc #5709
  • +
  • Use rsplit to get module and classname for imports #5712
  • +
  • Formalize URLPatternsTestCase #5703
  • +
  • Add exception translation test #5700
  • +
  • Test staticfiles #5701
  • +
  • Add drf-yasg to documentation and schema 3rd party packages #5720
  • +
  • Remove unused compat._resolve_model() #5733
  • +
  • Drop compat workaround for unsupported Python 3.2 #5734
  • +
  • Prefer iter(dict) over iter(dict.keys()) #5736
  • +
  • Pass python_requires argument to setuptools #5739
  • +
  • Remove unused links from docs #5735
  • +
  • Prefer https protocol for links in docs when available #5729
  • +
  • Add HStoreField, postgres fields tests #5654
  • +
  • Always fully qualify ValidationError in docs #5751
  • +
  • Remove unreachable code from ManualSchema #5766
  • +
  • Allowed customising API documentation code samples #5752
  • +
  • Updated docs to use pip show #5757
  • +
  • Load 'static' instead of 'staticfiles' in templates #5773
  • +
  • Fixed a typo in fields docs #5783
  • +
  • Refer to "NamespaceVersioning" instead of "NamespacedVersioning" in the documentation #5754
  • +
  • ErrorDetail: add __eq__/__ne__ and __repr__ #5787
  • +
  • Replace background-attachment: fixed in docs #5777
  • +
  • Make 404 & 403 responses consistent with exceptions.APIException output #5763
  • +
  • Small fix to API documentation: schemas #5796
  • +
  • Fix schema generation for PrimaryKeyRelatedField #5764
  • +
  • Represent serializer DictField as an Object in schema #5765
  • +
  • Added docs example reimplementing ObtainAuthToken #5802
  • +
  • Add schema to the ObtainAuthToken view #5676
  • +
  • Fix request formdata handling #5800
  • +
  • Fix authtoken views imports #5818
  • +
  • Update pytest, isort #5815 #5817 #5894
  • +
  • Fixed active timezone handling for non ISO8601 datetimes. #5833
  • +
  • Made TemplateHTMLRenderer render IntegerField inputs when value is 0. #5834
  • +
  • Corrected endpoint in tutorial instructions #5835
  • +
  • Add Django Rest Framework Role Filters to Third party packages #5809
  • +
  • Use single copy of static assets. Update jQuery #5823
  • +
  • Changes ternary conditionals to be PEP308 compliant #5827
  • +
  • Added links to 'A Todo List API with React' and 'Blog API' tutorials #5837
  • +
  • Fix comment typo in ModelSerializer #5844
  • +
  • Add admin to installed apps to avoid test failures. #5870
  • +
  • Fixed schema for UUIDField in SimpleMetadata. #5872
  • +
  • Corrected docs on router include with namespaces. #5843
  • +
  • Test using model objects for dotted source default #5880
  • +
  • Allow traversing nullable related fields #5849
  • +
  • Added: Tutorial: Django REST with React (Django 2.0) #5891
  • +
  • Add LimitOffsetPagination.get_count to allow method override #5846
  • +
  • Don't show hidden fields in metadata #5854
  • +
  • Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. #5899
  • +
  • Added generic 500 and 400 JSON error handlers. #5904
  • +
+

3.7.x series

+

3.7.7

+

Date: 21st December 2017

+
    +
  • Fix typo to include *.mo locale files to packaging. #5697, #5695
  • +
+

3.7.6

+

Date: 21st December 2017

+
    +
  • Add missing *.ico icon files to packaging.
  • +
+

3.7.5

+

Date: 21st December 2017

+
    +
  • Add missing *.woff2 font files to packaging. #5692
  • +
  • Add missing *.mo locale files to packaging. #5695, #5696
  • +
+

3.7.4

+

Date: 20th December 2017

+
    +
  • +

    Schema: Extract method for manual_fields processing #5633

    +

    Allows for easier customisation of manual_fields processing, for example +to provide per-method manual fields. AutoSchema adds get_manual_fields, +as the intended override point, and a utility method update_fields, to +handle by-name field replacement from a list, which, in general, you are not +expected to override.

    +

    Note: AutoSchema.__init__ now ensures manual_fields is a list. +Previously may have been stored internally as None.

    +
  • +
  • +

    Remove ulrparse compatibility shim; use six instead #5579

    +
  • +
  • Drop compat wrapper for TimeDelta.total_seconds() #5577
  • +
  • Clean up all whitespace throughout project #5578
  • +
  • Compat cleanup #5581
  • +
  • Add pygments CSS block in browsable API views #5584 #5587
  • +
  • Remove set_rollback() from compat #5591
  • +
  • Fix request body/POST access #5590
  • +
  • Rename test to reference correct issue #5610
  • +
  • Documentation Fixes #5611 #5612
  • +
  • Remove references to unsupported Django versions in docs and code #5602
  • +
  • Test Serializer exclude for declared fields #5599
  • +
  • Fixed schema generation for filter backends #5613
  • +
  • Minor cleanup for ModelSerializer tests #5598
  • +
  • Reimplement request attribute access w/ __getattr__ #5617
  • +
  • Fixed SchemaJSRenderer renders invalid Javascript #5607
  • +
  • Make Django 2.0 support official/explicit #5619
  • +
  • Perform type check on passed request argument #5618
  • +
  • Fix AttributeError hiding on request authenticators #5600
  • +
  • Update test requirements #5626
  • +
  • Docs: Serializer._declared_fields enable modifying fields on a serializer #5629
  • +
  • Fix packaging #5624
  • +
  • Fix readme rendering for PyPI, add readme build to CI #5625
  • +
  • Update tutorial #5622
  • +
  • Non-required fields with allow_null=True should not imply a default value #5639
  • +
  • Docs: Add allow_null serialization output note #5641
  • +
  • Update to use the Django 2.0 release in tox.ini #5645
  • +
  • Fix Serializer.data for Browsable API rendering when provided invalid data #5646
  • +
  • Docs: Note AutoSchema limitations on bare APIView #5649
  • +
  • Add .basename and .reverse_action() to ViewSet #5648
  • +
  • Docs: Fix typos in serializers documentation #5652
  • +
  • Fix override_settings compat #5668
  • +
  • Add DEFAULT_SCHEMA_CLASS setting #5658
  • +
  • Add docs note re generated BooleanField being required=False #5665
  • +
  • Add 'dist' build #5656
  • +
  • Fix typo in docstring #5678
  • +
  • Docs: Add UNAUTHENTICATED_USER = None note #5679
  • +
  • Update OPTIONS example from “Documenting Your API” #5680
  • +
  • Docs: Add note on object permissions for FBVs #5681
  • +
  • Docs: Add example to to_representation docs #5682
  • +
  • Add link to Classy DRF in docs #5683
  • +
  • Document ViewSet.action #5685
  • +
  • Fix schema docs typo #5687
  • +
  • Fix URL pattern parsing in schema generation #5689
  • +
  • Add example using source=‘*’ to custom field docs. #5688
  • +
  • Fix format_suffix_patterns behavior with Django 2 path() routes #5691
  • +
+

3.7.3

+

Date: 6th November 2017

+
    +
  • Fix AppRegistryNotReady error from contrib.auth view imports #5567
  • +
+

3.7.2

+

Date: 6th November 2017

+
    +
  • Fixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. #5510
  • +
  • Add missing import for TextLexer. #5512
  • +
  • Adding examples and documentation for caching #5514
  • +
  • Include date and date-time format for schema generation #5511
  • +
  • Use triple backticks for markdown code blocks #5513
  • +
  • Interactive docs - make bottom sidebar items sticky #5516
  • +
  • Clarify pagination system check #5524
  • +
  • Stop JSONBoundField mangling invalid JSON #5527
  • +
  • Have JSONField render as textarea in Browsable API #5530
  • +
  • Schema: Exclude OPTIONS/HEAD for ViewSet actions #5532
  • +
  • Fix ordering for dotted sources #5533
  • +
  • Fix: Fields with allow_null=True should imply a default serialization value #5518
  • +
  • Ensure Location header is strictly a 'str', not subclass. #5544
  • +
  • Add import to example in api-guide/parsers #5547
  • +
  • Catch OverflowError for "out of range" datetimes #5546
  • +
  • Add djangorestframework-rapidjson to third party packages #5549
  • +
  • Increase test coverage for drf_create_token command #5550
  • +
  • Add trove classifier for Python 3.6 support. #5555
  • +
  • Add pip cache support to the Travis CI configuration #5556
  • +
  • Rename [wheel] section to [bdist_wheel] as the former is legacy #5557
  • +
  • Fix invalid escape sequence deprecation warnings #5560
  • +
  • Add interactive docs error template #5548
  • +
  • Add rounding parameter to DecimalField #5562
  • +
  • Fix all BytesWarning caught during tests #5561
  • +
  • Use dict and set literals instead of calls to dict() and set() #5559
  • +
  • Change ImageField validation pattern, use validators from DjangoImageField #5539
  • +
  • Fix processing unicode symbols in query_string by Python 2 #5552
  • +
+

3.7.1

+

Date: 16th October 2017

+
    +
  • Fix Interactive documentation always uses false for boolean fields in requests #5492
  • +
  • Improve compatibility with Django 2.0 alpha. #5500 #5503
  • +
  • Improved handling of schema naming collisions #5486
  • +
  • Added additional docs and tests around providing a default value for dotted source fields #5489
  • +
+

3.7.0

+

Date: 6th October 2017

+
    +
  • Fix DjangoModelPermissions to ensure user authentication before calling the view's get_queryset() method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. #5376
  • +
  • Deprecated exclude_from_schema on APIView and api_view decorator. Set schema = None or @schema(None) as appropriate. #5422
  • +
  • +

    Timezone-aware DateTimeFields now respect active or default timezone during serialization, instead of always using UTC. #5435

    +

    Resolves inconsistency whereby instances were serialized with supplied datetime for create but UTC for retrieve. #3732

    +

    Possible backwards compatibility break if you were relying on datetime strings being UTC. Have client interpret datetimes or set default or active timezone (docs) to UTC if needed.

    +
  • +
  • +

    Removed DjangoFilterBackend inline with deprecation policy. Use django_filters.rest_framework.FilterSet and/or django_filters.rest_framework.DjangoFilterBackend instead. #5273

    +
  • +
  • Don't strip microseconds from time when encoding. Makes consistent with datetime. + BC Change: Previously only milliseconds were encoded. #5440
  • +
  • Added STRICT_JSON setting (default True) to raise exception for the extended float values (nan, inf, -inf) accepted by Python's json module. + BC Change: Previously these values would converted to corresponding strings. Set STRICT_JSON to False to restore the previous behaviour. #5265
  • +
  • Add support for page_size parameter in CursorPaginator class #5250
  • +
  • Make DEFAULT_PAGINATION_CLASS None by default. + BC Change: If your were just setting PAGE_SIZE to enable pagination you will need to add DEFAULT_PAGINATION_CLASS. + The previous default was rest_framework.pagination.PageNumberPagination. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. #5170
  • +
  • Catch APIException from get_serializer_fields in schema generation. #5443
  • +
  • Allow custom authentication and permission classes when using include_docs_urls #5448
  • +
  • Defer translated string evaluation on validators. #5452
  • +
  • Added default value for 'detail' param into 'ValidationError' exception #5342
  • +
  • Adjust schema get_filter_fields rules to match framework #5454
  • +
  • Updated test matrix to add Django 2.0 and drop Django 1.8 & 1.9 + BC Change: This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. #5457
  • +
  • Fixed a deprecation warning in serializers.ModelField #5058
  • +
  • Added a more explicit error message when get_queryset returned None #5348
  • +
  • Fix docs for Response data description #5361
  • +
  • Fix pycache/.pyc excludes when packaging #5373
  • +
  • Fix default value handling for dotted sources #5375
  • +
  • Ensure content_type is set when passing empty body to RequestFactory #5351
  • +
  • Fix ErrorDetail Documentation #5380
  • +
  • Allow optional content in the generic content form #5372
  • +
  • Updated supported values for the NullBooleanField #5387
  • +
  • Fix ModelSerializer custom named fields with source on model #5388
  • +
  • Fixed the MultipleFieldLookupMixin documentation example to properly check for object level permission #5398
  • +
  • Update get_object() example in permissions.md #5401
  • +
  • Fix authtoken management command #5415
  • +
  • Fix schema generation markdown #5421
  • +
  • Allow ChoiceField.choices to be set dynamically #5426
  • +
  • Add the project layout to the quickstart #5434
  • +
  • Reuse 'apply_markdown' function in 'render_markdown' templatetag #5469
  • +
  • Added links to drf-openapi package in docs #5470
  • +
  • Added docstrings code highlighting with pygments #5462
  • +
  • Fixed documentation rendering for views named data #5472
  • +
  • Docs: Clarified 'to_internal_value()' validation behavior #5466
  • +
  • Fix missing six.text_type() call on APIException.str #5476
  • +
  • Document documentation.py #5478
  • +
  • Fix naming collisions in Schema Generation #5464
  • +
  • Call Django's authenticate function with the request object #5295
  • +
  • Update coreapi JS to 0.1.1 #5479
  • +
  • Have is_list_view recognise RetrieveModel… views #5480
  • +
  • Remove Django 1.8 & 1.9 compatibility code #5481
  • +
  • Remove deprecated schema code from DefaultRouter #5482
  • +
  • Refactor schema generation to allow per-view customisation. + BC Change: SchemaGenerator.get_serializer_fields has been refactored as AutoSchema.get_serializer_fields and drops the view argument [#5354][gh5354]
  • +
+

3.6.x series

+

3.6.4

+

Date: 21st August 2017

+
    +
  • Ignore any invalidly formed query parameters for OrderingFilter. #5131
  • +
  • Improve memory footprint when reading large JSON requests. #5147
  • +
  • Fix schema generation for pagination. #5161
  • +
  • Fix exception when HTML_CUTOFF is set to None. #5174
  • +
  • Fix browsable API not supporting multipart/form-data correctly. #5176
  • +
  • Fixed test_hyperlinked_related_lookup_url_encoded_exists. #5179
  • +
  • Make sure max_length is in FileField kwargs. #5186
  • +
  • Fix list_route & detail_route with kwargs contains curly bracket in url_path #5187
  • +
  • Add Django manage command to create a DRF user Token. #5188
  • +
  • Ensure API documentation templates do not check for user authentication #5162
  • +
  • Fix special case where OneToOneField is also primary key. #5192
  • +
  • Added aria-label and a new region for accessibility purposes in base.html #5196
  • +
  • Quote nested API parameters in api.js. #5214
  • +
  • Set ViewSet args/kwargs/request before dispatch. #5229
  • +
  • Added unicode support to SlugField. #5231
  • +
  • Fix HiddenField appears in Raw Data form initial content. #5259
  • +
  • Raise validation error on invalid timezone parsing. #5261
  • +
  • Fix SearchFilter to-many behavior/performance. #5264
  • +
  • Simplified chained comparisons and minor code fixes. #5276
  • +
  • RemoteUserAuthentication, docs, and tests. #5306
  • +
  • Revert "Cached the field's root and context property" #5313
  • +
  • Fix introspection of list field in schema. #5326
  • +
  • Fix interactive docs for multiple nested and extra methods. #5334
  • +
  • Fix/remove undefined template var "schema" #5346
  • +
+

3.6.3

+

Date: 12th May 2017

+
    +
  • Raise 404 if a URL lookup results in ValidationError. (#5126)
  • +
  • Honor http_method_names on class based view, when generating API schemas. (#5085)
  • +
  • Allow overridden get_limit in LimitOffsetPagination to return all records. (#4437)
  • +
  • Fix partial update for the ListSerializer. (#4222)
  • +
  • Render JSONField control correctly in browsable API. (#4999, #5042)
  • +
  • Raise validation errors for invalid datetime in given timezone. (#4987)
  • +
  • Support restricting doc & schema shortcuts to a subset of urls. (#4979)
  • +
  • Resolve SchemaGenerator error with paginators that have no page_size attribute. (#5086, #3692)
  • +
  • Resolve HyperlinkedRelatedField exception on string with %20 instead of space. (#4748, #5078)
  • +
  • Customizable schema generator classes. (#5082)
  • +
  • Update existing vary headers in response instead of overwriting them. (#5047)
  • +
  • Support passing .as_view() to view instance. (#5053)
  • +
  • Use correct exception handler when settings overridden on a view. (#5055, #5054)
  • +
  • Update Boolean field to support 'yes' and 'no' values. (#5038)
  • +
  • Fix unique validator for ChoiceField. (#5004, #5026, #5028)
  • +
  • JavaScript cleanups in API Docs. (#5001)
  • +
  • Include URL path regexs in API schemas where valid. (#5014)
  • +
  • Correctly set scheme in coreapi TokenAuthentication. (#5000, #4994)
  • +
  • HEAD requests on ViewSets should not return 405. (#4705, #4973, #4864)
  • +
  • Support usage of 'source' in extra_kwargs. (#4688)
  • +
  • Fix invalid content type for schema.js (#4968)
  • +
  • Fix DjangoFilterBackend inheritance issues. (#5089, #5117)
  • +
+

3.6.2

+

Date: 10th March 2017

+
    +
  • Support for Safari & IE in API docs. (#4959, #4961)
  • +
  • Add missing mark_safe in API docs template tags. (#4952, #4953)
  • +
  • Add missing glyphicon fonts. (#4950, #4951)
  • +
  • Fix One-to-one fields in API docs. (#4955, #4956)
  • +
  • Test clean ups. (#4949)
  • +
+

3.6.1

+

Date: 9th March 2017

+
    +
  • Ensure markdown dependency is optional. (#4947)
  • +
+

3.6.0

+

Date: 9th March 2017

+

See the release announcement.

+
+

3.5.x series

+

3.5.4

+

Date: 10th February 2017

+
    +
  • Add max_length and min_length arguments for ListField. (#4877)
  • +
  • Add per-view custom exception handler support. (#4753)
  • +
  • Support disabling of declared fields on serializer subclasses. (#4764)
  • +
  • Support custom view names on @list_route and @detail_route endpoints. (#4821)
  • +
  • Correct labels for fields in login template when custom user model is used. (#4841)
  • +
  • Whitespace fixes for descriptions generated from docstrings. (#4759, #4869, #4870)
  • +
  • Better error reporting when schemas are returned by views without a schema renderer. (#4790)
  • +
  • Fix for returned response of PUT requests when prefetch_related is used. (#4661, #4668)
  • +
  • Fix for breadcrumb view names. (#4750)
  • +
  • Fix for RequestsClient ensuring fully qualified URLs. (#4678)
  • +
  • Fix for incorrect behavior of writable-nested fields check in some cases. (#4634, #4669)
  • +
  • Resolve Django deprecation warnings. (#4712)
  • +
  • Various cleanup of test cases.
  • +
+

3.5.3

+

Date: 7th November 2016

+
    +
  • Don't raise incorrect FilterSet deprecation warnings. (#4660, #4643, #4644)
  • +
  • Schema generation should not raise 404 when a view permission class does. (#4645, #4646)
  • +
  • Add autofocus support for input controls. (#4650)
  • +
+

3.5.2

+

Date: 1st November 2016

+
    +
  • Restore exception tracebacks in Python 2.7. (#4631, #4638)
  • +
  • Properly display dicts in the admin console. (#4532, #4636)
  • +
  • Fix is_simple_callable with variable args, kwargs. (#4622, #4602)
  • +
  • Support 'on'/'off' literals with BooleanField. (#4640, #4624)
  • +
  • Enable cursor pagination of value querysets. (#4569)
  • +
  • Fix support of get_full_details() for Throttled exceptions. (#4627)
  • +
  • Fix FilterSet proxy. (#4620)
  • +
  • Make serializer fields import explicit. (#4628)
  • +
  • Drop redundant requests adapter. (#4639)
  • +
+

3.5.1

+

Date: 21st October 2016

+
    +
  • Make rest_framework/compat.py imports. (#4612, #4608, #4601)
  • +
  • Fix bug in schema base path generation. (#4611, #4605)
  • +
  • Fix broken case of ListSerializer with single item. (#4609, #4606)
  • +
  • Remove bare raise for Python 3.5 compat. (#4600)
  • +
+

3.5.0

+

Date: 20th October 2016

+
+

3.4.x series

+

3.4.7

+

Date: 21st September 2016

+
    +
  • Fallback behavior for request parsing when request.POST already accessed. (#3951, #4500)
  • +
  • Fix regression of RegexField. (#4489, #4490, #2617)
  • +
  • Missing comma in admin.html causing CSRF error. (#4472, #4473)
  • +
  • Fix response rendering with empty context. (#4495)
  • +
  • Fix indentation regression in API listing. (#4493)
  • +
  • Fixed an issue where the incorrect value is set to ResolverMatch.func_name of api_view decorated view. (#4465, #4462)
  • +
  • Fix APIClient.get() when path contains unicode arguments (#4458)
  • +
+

3.4.6

+

Date: 23rd August 2016

+
    +
  • Fix malformed Javascript in browsable API. (#4435)
  • +
  • Skip HiddenField from Schema fields. (#4425, #4429)
  • +
  • Improve Create to show the original exception traceback. (#3508)
  • +
  • Fix AdminRenderer display of PK only related fields. (#4419, #4423)
  • +
+

3.4.5

+

Date: 19th August 2016

+
    +
  • Improve debug error handling. (#4416, #4409)
  • +
  • Allow custom CSRF_HEADER_NAME setting. (#4415, #4410)
  • +
  • Include .action attribute on viewsets when generating schemas. (#4408, #4398)
  • +
  • Do not include request.FILES items in request.POST. (#4407)
  • +
  • Fix rendering of checkbox multiple. (#4403)
  • +
  • Fix docstring of Field.get_default. (#4404)
  • +
  • Replace utf8 character with its ascii counterpart in README. (#4412)
  • +
+

3.4.4

+

Date: 12th August 2016

+
    +
  • Ensure views are fully initialized when generating schemas. (#4373, #4382, #4383, #4279, #4278)
  • +
  • Add form field descriptions to schemas. (#4387)
  • +
  • Fix category generation for schema endpoints. (#4391, #4394, #4390, #4386, #4376, #4329)
  • +
  • Don't strip empty query params when paginating. (#4392, #4393, #4260)
  • +
  • Do not re-run query for empty results with LimitOffsetPagination. (#4201, #4388)
  • +
  • Stricter type validation for CharField. (#4380, #3394)
  • +
  • RelatedField.choices should preserve non-string values. (#4111, #4379, #3365)
  • +
  • Test case for rendering checkboxes in vertical form style. (#4378, #3868, #3868)
  • +
  • Show error traceback HTML in browsable API (#4042, #4172)
  • +
  • Fix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. #4370
  • +
  • Allow max_digits=None on DecimalField. (#4377, #4372)
  • +
  • Limit queryset when rendering relational choices. (#4375, #4122, #3329, #3330, #3877)
  • +
  • Resolve form display with ChoiceField, MultipleChoiceField and non-string choices. (#4374, #4119, #4121, #4137, #4120)
  • +
  • Fix call to TemplateHTMLRenderer.resolve_context() fallback method. (#4371)
  • +
+

3.4.3

+

Date: 5th August 2016

+
    +
  • Include fallback for users of older TemplateHTMLRenderer internal API. (#4361)
  • +
+

3.4.2

+

Date: 5th August 2016

+
    +
  • Include kwargs passed to 'as_view' when generating schemas. (#4359, #4330, #4331)
  • +
  • Access request.user.is_authenticated as property not method, under Django 1.10+ (#4358, #4354)
  • +
  • Filter HEAD out from schemas. (#4357)
  • +
  • extra_kwargs takes precedence over uniqueness kwargs. (#4198, #4199, #4349)
  • +
  • Correct descriptions when tabs are used in code indentation. (#4345, #4347)*
  • +
  • Change template context generation in TemplateHTMLRenderer. (#4236)
  • +
  • Serializer defaults should not be included in partial updates. (#4346, #3565)
  • +
  • Consistent behavior & descriptive error from FileUploadParser when filename not included. (#4340, #3610, #4292, #4296)
  • +
  • DecimalField quantizes incoming digitals. (#4339, #4318)
  • +
  • Handle non-string input for IP fields. (#4335, #4336, #4338)
  • +
  • Fix leading slash handling when Schema generation includes a root URL. (#4332)
  • +
  • Test cases for DictField with allow_null options. (#4348)
  • +
  • Update tests from Django 1.10 beta to Django 1.10. (#4344)
  • +
+

3.4.1

+

Date: 28th July 2016

+
    +
  • Added root_renderers argument to DefaultRouter. (#4323, #4268)
  • +
  • Added url and schema_url arguments. (#4321, #4308, #4305)
  • +
  • Unique together checks should apply to read-only fields which have a default. (#4316, #4294)
  • +
  • Set view.format_kwarg in schema generator. (#4293, #4315)
  • +
  • Fix schema generator for views with pagination_class = None. (#4314, #4289)
  • +
  • Fix schema generator for views with no get_serializer_class. (#4265, #4285)
  • +
  • Fixes for media type parameters in Accept and Content-Type headers. (#4287, #4313, #4281)
  • +
  • Use verbose_name instead of object_name in error messages. (#4299)
  • +
  • Minor version update to Twitter Bootstrap. (#4307)
  • +
  • SearchFilter raises error when using with related field. (#4302, #4303, #4298)
  • +
  • Adding support for RFC 4918 status codes. (#4291)
  • +
  • Add LICENSE.md to the built wheel. (#4270)
  • +
  • Serializing "complex" field returns None instead of the value since 3.4 (#4272, #4273, #4288)
  • +
+

3.4.0

+

Date: 14th July 2016

+
    +
  • Don't strip microseconds in JSON output. (#4256)
  • +
  • Two slightly different iso 8601 datetime serialization. (#4255)
  • +
  • Resolve incorrect inclusion of media type parameters. (#4254)
  • +
  • Response Content-Type potentially malformed. (#4253)
  • +
  • Fix setup.py error on some platforms. (#4246)
  • +
  • Move alternate formats in coreapi into separate packages. (#4244)
  • +
  • Add localize keyword argument to DecimalField. (#4233)
  • +
  • Fix issues with routers for custom list-route and detail-routes. (#4229)
  • +
  • Namespace versioning with nested namespaces. (#4219)
  • +
  • Robust uniqueness checks. (#4217)
  • +
  • Minor refactoring of must_call_distinct. (#4215)
  • +
  • Overridable offset cutoff in CursorPagination. (#4212)
  • +
  • Pass through strings as-in with date/time fields. (#4196)
  • +
  • Add test confirming that required=False is valid on a relational field. (#4195)
  • +
  • In LimitOffsetPagination limit=0 should revert to default limit. (#4194)
  • +
  • Exclude read_only=True fields from unique_together validation & add docs. (#4192)
  • +
  • Handle bytestrings in JSON. (#4191)
  • +
  • JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (#4187)
  • +
  • JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. (#4185)
  • +
  • More robust form rendering in the browsable API. (#4181)
  • +
  • Empty cases of .validated_data and .errors as lists not dicts for ListSerializer. (#4180)
  • +
  • Schemas & client libraries. (#4179)
  • +
  • Removed AUTH_USER_MODEL compat property. (#4176)
  • +
  • Clean up existing deprecation warnings. (#4166)
  • +
  • Django 1.10 support. (#4158)
  • +
  • Updated jQuery version to 1.12.4. (#4157)
  • +
  • More robust default behavior on OrderingFilter. (#4156)
  • +
  • description.py codes and tests removal. (#4153)
  • +
  • Wrap guardian.VERSION in tuple. (#4149)
  • +
  • Refine validator for fields with kwargs. (#4146)
  • +
  • Fix None values representation in childs of ListField, DictField. (#4118)
  • +
  • Resolve TimeField representation for midnight value. (#4107)
  • +
  • Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. (#4106)
  • +
  • TimeField render returns None instead of 00:00:00. (#4105)
  • +
  • Fix incorrectly named zh-hans and zh-hant locale path. (#4103)
  • +
  • Prevent raising exception when limit is 0. (#4098)
  • +
  • TokenAuthentication: Allow custom keyword in the header. (#4097)
  • +
  • Handle incorrectly padded HTTP basic auth header. (#4090)
  • +
  • LimitOffset pagination crashes Browseable API when limit=0. (#4079)
  • +
  • Fixed DecimalField arbitrary precision support. (#4075)
  • +
  • Added support for custom CSRF cookie names. (#4049)
  • +
  • Fix regression introduced by #4035. (#4041)
  • +
  • No auth view failing permission should raise 403. (#4040)
  • +
  • Fix string_types / text_types confusion. (#4025)
  • +
  • Do not list related field choices in OPTIONS requests. (#4021)
  • +
  • Fix typo. (#4008)
  • +
  • Reorder initializing the view. (#4006)
  • +
  • Type error in DjangoObjectPermissionsFilter on Python 3.4. (#4005)
  • +
  • Fixed use of deprecated Query.aggregates. (#4003)
  • +
  • Fix blank lines around docstrings. (#4002)
  • +
  • Fixed admin pagination when limit is 0. (#3990)
  • +
  • OrderingFilter adjustments. (#3983)
  • +
  • Non-required serializer related fields. (#3976)
  • +
  • Using safer calling way of "@api_view" in tutorial. (#3971)
  • +
  • ListSerializer doesn't handle unique_together constraints. (#3970)
  • +
  • Add missing migration file. (#3968)
  • +
  • OrderingFilter should call get_serializer_class() to determine default fields. (#3964)
  • +
  • Remove old Django checks from tests and compat. (#3953)
  • +
  • Support callable as the value of initial for any serializer.Field. (#3943)
  • +
  • Prevented unnecessary distinct() call in SearchFilter. (#3938)
  • +
  • Fix None UUID ForeignKey serialization. (#3936)
  • +
  • Drop EOL Django 1.7. (#3933)
  • +
  • Add missing space in serializer error message. (#3926)
  • +
  • Fixed _force_text_recursive typo. (#3908)
  • +
  • Attempt to address Django 2.0 deprecate warnings related to field.rel. (#3906)
  • +
  • Fix parsing multipart data using a nested serializer with list. (#3820)
  • +
  • Resolving APIs URL to different namespaces. (#3816)
  • +
  • Do not HTML-escape help_text in Browsable API forms. (#3812)
  • +
  • OPTIONS fetches and shows all possible foreign keys in choices field. (#3751)
  • +
  • Django 1.9 deprecation warnings (#3729)
  • +
  • Test case for #3598 (#3710)
  • +
  • Adding support for multiple values for search filter. (#3541)
  • +
  • Use get_serializer_class in ordering filter. (#3487)
  • +
  • Serializers with many=True should return empty list rather than empty dict. (#3476)
  • +
  • LimitOffsetPagination limit=0 fix. (#3444)
  • +
  • Enable Validators to defer string evaluation and handle new string format. (#3438)
  • +
  • Unique validator is executed and breaks if field is invalid. (#3381)
  • +
  • Do not ignore overridden View.get_view_name() in breadcrumbs. (#3273)
  • +
  • Retry form rendering when rendering with serializer fails. (#3164)
  • +
  • Unique constraint prevents nested serializers from updating. (#2996)
  • +
  • Uniqueness validators should not be run for excluded (read_only) fields. (#2848)
  • +
  • UniqueValidator raises exception for nested objects. (#2403)
  • +
  • lookup_type is deprecated in favor of lookup_expr. (#4259)
  • +
+
+

3.3.x series

+

3.3.3

+

Date: 14th March 2016.

+
    +
  • Remove version string from templates. Thanks to @blag for the report and fixes. (#3878, #3913, #3912)
  • +
  • Fixes vertical html layout for BooleanField. Thanks to Mikalai Radchuk for the fix. (#3910)
  • +
  • Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. (#3903)
  • +
  • Internationalization for authtoken. Thanks to Michael Nacharov for the fix. (#3887, #3968)
  • +
  • Fix Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. (#3860, #3858)
  • +
  • Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. (#3604, #3842)
  • +
  • QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. (#3833)
  • +
  • Add an explicit on_delete on the models. Thanks to Mads Jensen for the fix. (#3832)
  • +
  • Fix DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. (#3819)
  • +
  • Fixed TimeField not handling string times. Thanks to Areski Belaid for the fix. (#3809)
  • +
  • Avoid updates of Meta.extra_kwargs. Thanks to Kevin Massey for the report and fix. (#3805, #3804)
  • +
  • Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. (#3801)
  • +
  • Document how to avoid CSRF and missing button issues with django-crispy-forms. Thanks to Emmanuelle Delescolle, José Padilla and Luis San Pablo for the report, analysis and fix. (#3787, #3636, #3637)
  • +
  • Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. (#3786, #3815)
  • +
  • Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. (#3785)
  • +
  • Fix Min/MaxValueValidator transfer from a model's DecimalField. Thanks to Kevin Brown for the fix. (#3774)
  • +
  • Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. (#3769)
  • +
  • Fix AutoFilterSet to inherit from default_filter_set. Thanks to Tom Linford for the fix. (#3753)
  • +
  • Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. (#3739)
  • +
  • DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. (#3731, #3726)
  • +
  • Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. (#3715)
  • +
  • Add missing csrf_token in AdminRenderer post form. Thanks to Piotr Śniegowski for the fix. (#3703)
  • +
  • Refactored _get_reverse_relationships() to use correct to_field. Thanks to Benjamin Phillips for the fix. (#3696)
  • +
  • Document the use of get_queryset for RelatedField. Thanks to Ryan Hiebert for the fix. (#3605)
  • +
  • Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix (#3962)
  • +
+

3.3.2

+

Date: 14th December 2015.

+
    +
  • ListField enforces input is a list. (#3513)
  • +
  • Fix regression hiding raw data form. (#3600, #3578)
  • +
  • Fix Python 3.5 compatibility. (#3534, #3626)
  • +
  • Allow setting a custom Django Paginator in pagination.PageNumberPagination. (#3631, #3684)
  • +
  • Fix relational fields without to_fields attribute. (#3635, #3634)
  • +
  • Fix template.render deprecation warnings for Django 1.9. (#3654)
  • +
  • Sort response headers in browsable API renderer. (#3655)
  • +
  • Use related_objects api for Django 1.9+. (#3656, #3252)
  • +
  • Add confirm modal when deleting. (#3228, #3662)
  • +
  • Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. (#3668)
  • +
  • Make DRF compatible with multi template engine in Django 1.8. (#3672)
  • +
  • Update NestedBoundField to also handle empty string when rendering its form. (#3677)
  • +
  • Fix UUID validation to properly catch invalid input types. (#3687, #3679)
  • +
  • Fix caching issues. (#3628, #3701)
  • +
  • Fix Admin and API browser for views without a filter_class. (#3705, #3596, #3597)
  • +
  • Add app_name to rest_framework.urls. (#3714)
  • +
  • Improve authtoken's views to support url versioning. (#3718, #3723)
  • +
+

3.3.1

+

Date: 4th November 2015.

+
    +
  • Resolve parsing bug when accessing request.POST (#3592)
  • +
  • Correctly deal with to_field referring to primary key. (#3593)
  • +
  • Allow filter HTML to render when no filter_class is defined. (#3560)
  • +
  • Fix admin rendering issues. (#3564, #3556)
  • +
  • Fix issue with DecimalValidator. (#3568)
  • +
+

3.3.0

+

Date: 28th October 2015.

+
    +
  • HTML controls for filters. (#3315)
  • +
  • Forms API. (#3475)
  • +
  • AJAX browsable API. (#3410)
  • +
  • Added JSONField. (#3454)
  • +
  • Correctly map to_field when creating ModelSerializer relational fields. (#3526)
  • +
  • Include keyword arguments when mapping FilePathField to a serializer field. (#3536)
  • +
  • Map appropriate model error_messages on ModelSerializer uniqueness constraints. (#3435)
  • +
  • Include max_length constraint for ModelSerializer fields mapped from TextField. (#3509)
  • +
  • Added support for Django 1.9. (#3450, #3525)
  • +
  • Removed support for Django 1.5 & 1.6. (#3421, #3429)
  • +
  • Removed 'south' migrations. (#3495)
  • +
+
+

3.2.x series

+

3.2.5

+

Date: 27th October 2015.

+
    +
  • Escape username in optional logout tag. (#3550)
  • +
+

3.2.4

+

Date: 21th September 2015.

+
    +
  • Don't error on missing ViewSet.search_fields attribute. (#3324, #3323)
  • +
  • Fix allow_empty not working on serializers with many=True. (#3361, #3364)
  • +
  • Let DurationField accepts integers. (#3359)
  • +
  • Multi-level dictionaries not supported in multipart requests. (#3314)
  • +
  • Fix ListField truncation on HTTP PATCH (#3415, #2761)
  • +
+

3.2.3

+

Date: 24th August 2015.

+
    +
  • Added html_cutoff and html_cutoff_text for limiting select dropdowns. (#3313)
  • +
  • Added regex style to SearchFilter. (#3316)
  • +
  • Resolve issues with setting blank HTML fields. (#3318) (#3321)
  • +
  • Correctly display existing 'select multiple' values in browsable API forms. (#3290)
  • +
  • Resolve duplicated validation message for IPAddressField. ([#3249gh3249) (#3250)
  • +
  • Fix to ensure admin renderer continues to work when pagination is disabled. (#3275)
  • +
  • Resolve error with LimitOffsetPagination when count=0, offset=0. (#3303)
  • +
+

3.2.2

+

Date: 13th August 2015.

+
    +
  • Add display_value() method for use when displaying relational field select inputs. (#3254)
  • +
  • Fix issue with BooleanField checkboxes incorrectly displaying as checked. (#3258)
  • +
  • Ensure empty checkboxes properly set BooleanField to False in all cases. (#2776)
  • +
  • Allow WSGIRequest.FILES property without raising incorrect deprecated error. (#3261)
  • +
  • Resolve issue with rendering nested serializers in forms. (#3260)
  • +
  • Raise an error if user accidentally pass a serializer instance to a response, rather than data. (#3241)
  • +
+

3.2.1

+

Date: 7th August 2015.

+
    +
  • Fix for relational select widgets rendering without any choices. (#3237)
  • +
  • Fix for 1, 0 rendering as true, false in the admin interface. #3227)
  • +
  • Fix for ListFields with single value in HTML form input. (#3238)
  • +
  • Allow request.FILES for compat with Django's HTTPRequest class. (#3239)
  • +
+

3.2.0

+

Date: 6th August 2015.

+
    +
  • Add AdminRenderer. (#2926)
  • +
  • Add FilePathField. (#1854)
  • +
  • Add allow_empty to ListField. (#2250)
  • +
  • Support django-guardian 1.3. (#3165)
  • +
  • Support grouped choices. (#3225)
  • +
  • Support error forms in browsable API. (#3024)
  • +
  • Allow permission classes to customize the error message. (#2539)
  • +
  • Support source=<method> on hyperlinked fields. (#2690)
  • +
  • ListField(allow_null=True) now allows null as the list value, not null items in the list. (#2766)
  • +
  • ManyToMany() maps to allow_empty=False, ManyToMany(blank=True) maps to allow_empty=True. (#2804)
  • +
  • Support custom serialization styles for primary key fields. (#2789)
  • +
  • OPTIONS requests support nested representations. (#2915)
  • +
  • Set view.action == "metadata" for viewsets with OPTIONS requests. (#3115)
  • +
  • Support allow_blank on UUIDField. ([#3130][gh#3130])
  • +
  • Do not display view docstrings with 401 or 403 response codes. (#3216)
  • +
  • Resolve Django 1.8 deprecation warnings. (#2886)
  • +
  • Fix for DecimalField validation. (#3139)
  • +
  • Fix behavior of allow_blank=False when used with trim_whitespace=True. (#2712)
  • +
  • Fix issue with some field combinations incorrectly mapping to an invalid allow_blank argument. (#3011)
  • +
  • Fix for output representations with prefetches and modified querysets. (#2704, #2727)
  • +
  • Fix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920)gh2920.
  • +
  • Fix UnicodeDecodeError when invalid characters included in header with TokenAuthentication. (#2928)
  • +
  • Fix transaction rollbacks with @non_atomic_requests decorator. (#3016)
  • +
  • Fix duplicate results issue with Oracle databases using SearchFilter. (#2935)
  • +
  • Fix checkbox alignment and rendering in browsable API forms. (#2783)
  • +
  • Fix for unsaved file objects which should use "url": null in the representation. (#2759)
  • +
  • Fix field value rendering in browsable API. (#2416)
  • +
  • Fix HStoreField to include allow_blank=True in DictField mapping. (#2659)
  • +
  • Numerous other cleanups, improvements to error messaging, private API & minor fixes.
  • +
+
+

3.1.x series

+

3.1.3

+

Date: 4th June 2015.

+
    +
  • Add DurationField. (#2481, #2989)
  • +
  • Add format argument to UUIDField. (#2788, #3000)
  • +
  • MultipleChoiceField empties incorrectly on a partial update using multipart/form-data (#2993, #2894)
  • +
  • Fix a bug in options related to read-only RelatedField. (#2981, #2811)
  • +
  • Fix nested serializers with unique_together relations. (#2975)
  • +
  • Allow unexpected values for ChoiceField/MultipleChoiceField representations. (#2839, #2940)
  • +
  • Rollback the transaction on error if ATOMIC_REQUESTS is set. (#2887, #2034)
  • +
  • Set the action on a view when override_method regardless of its None-ness. (#2933)
  • +
  • DecimalField accepts 2E+2 as 200 and validates decimal place correctly. (#2948, #2947)
  • +
  • Support basic authentication with custom UserModel that change username. (#2952)
  • +
  • IPAddressField improvements. (#2747, #2618, #3008)
  • +
  • Improve DecimalField for easier subclassing. (#2695)
  • +
+

3.1.2

+

Date: 13rd May 2015.

+
    +
  • DateField.to_representation can handle str and empty values. (#2656, #2687, #2869)
  • +
  • Use default reason phrases from HTTP standard. (#2764, #2763)
  • +
  • Raise error when ModelSerializer used with abstract model. (#2757, #2630)
  • +
  • Handle reversal of non-API view_name in HyperLinkedRelatedField (#2724, #2711)
  • +
  • Don't require pk strictly for related fields. (#2745, #2754)
  • +
  • Metadata detects null boolean field type. (#2762)
  • +
  • Proper handling of depth in nested serializers. (#2798)
  • +
  • Display viewset without paginator. (#2807)
  • +
  • Don't check for deprecated .model attribute in permissions (#2818)
  • +
  • Restrict integer field to integers and strings. (#2835, #2836)
  • +
  • Improve IntegerField to use compiled decimal regex. (#2853)
  • +
  • Prevent empty queryset to raise AssertionError. (#2862)
  • +
  • DjangoModelPermissions rely on get_queryset. (#2863)
  • +
  • Check AcceptHeaderVersioning with content negotiation in place. (#2868)
  • +
  • Allow DjangoObjectPermissions to use views that define get_queryset. (#2905)
  • +
+

3.1.1

+

Date: 23rd March 2015.

+
    +
  • Security fix: Escape tab switching cookie name in browsable API.
  • +
  • Display input forms in browsable API if serializer_class is used, even when get_serializer method does not exist on the view. (#2743)
  • +
  • Use a password input for the AuthTokenSerializer. (#2741)
  • +
  • Fix missing anchor closing tag after next button. (#2691)
  • +
  • Fix lookup_url_kwarg handling in viewsets. (#2685, #2591)
  • +
  • Fix problem with importing rest_framework.views in apps.py (#2678)
  • +
  • LimitOffsetPagination raises TypeError if PAGE_SIZE not set (#2667, #2700)
  • +
  • German translation for min_value field error message references max_value. (#2645)
  • +
  • Remove MergeDict. (#2640)
  • +
  • Support serializing unsaved models with related fields. (#2637, #2641)
  • +
  • Allow blank/null on radio.html choices. (#2631)
  • +
+

3.1.0

+

Date: 5th March 2015.

+

For full details see the 3.1 release announcement.

+
+

3.0.x series

+

3.0.5

+

Date: 10th February 2015.

+
    +
  • Fix a bug where _closable_objects breaks pickling. (#1850, #2492)
  • +
  • Allow non-standard User models with Throttling. (#2524)
  • +
  • Support custom User.db_table in TokenAuthentication migration. (#2479)
  • +
  • Fix misleading AttributeError tracebacks on Request objects. (#2530, #2108)
  • +
  • ManyRelatedField.get_value clearing field on partial update. (#2475)
  • +
  • Removed '.model' shortcut from code. (#2486)
  • +
  • Fix detail_route and list_route mutable argument. (#2518)
  • +
  • Prefetching the user object when getting the token in TokenAuthentication. (#2519)
  • +
+

3.0.4

+

Date: 28th January 2015.

+
    +
  • Django 1.8a1 support. (#2425, #2446, #2441)
  • +
  • Add DictField and support Django 1.8 HStoreField. (#2451, #2106)
  • +
  • Add UUIDField and support Django 1.8 UUIDField. (#2448, #2433, #2432)
  • +
  • BaseRenderer.render now raises NotImplementedError. (#2434)
  • +
  • Fix timedelta JSON serialization on Python 2.6. (#2430)
  • +
  • ResultDict and ResultList now appear as standard dict/list. (#2421)
  • +
  • Fix visible HiddenField in the HTML form of the web browsable API page. (#2410)
  • +
  • Use OrderedDict for RelatedField.choices. (#2408)
  • +
  • Fix ident format when using HTTP_X_FORWARDED_FOR. (#2401)
  • +
  • Fix invalid key with memcached while using throttling. (#2400)
  • +
  • Fix FileUploadParser with version 3.x. (#2399)
  • +
  • Fix the serializer inheritance. (#2388)
  • +
  • Fix caching issues with ReturnDict. (#2360)
  • +
+

3.0.3

+

Date: 8th January 2015.

+
    +
  • Fix MinValueValidator on models.DateField. (#2369)
  • +
  • Fix serializer missing context when pagination is used. (#2355)
  • +
  • Namespaced router URLs are now supported by the DefaultRouter. (#2351)
  • +
  • required=False allows omission of value for output. (#2342)
  • +
  • Use textarea input for models.TextField. (#2340)
  • +
  • Use custom ListSerializer for pagination if required. (#2331, #2327)
  • +
  • Better behavior with null and '' for blank HTML fields. (#2330)
  • +
  • Ensure fields in exclude are model fields. (#2319)
  • +
  • Fix IntegerField and max_length argument incompatibility. (#2317)
  • +
  • Fix the YAML encoder for 3.0 serializers. (#2315, #2283)
  • +
  • Fix the behavior of empty HTML fields. (#2311, #1101)
  • +
  • Fix Metaclass attribute depth ignoring fields attribute. (#2287)
  • +
  • Fix format_suffix_patterns to work with Django's i18n_patterns. (#2278)
  • +
  • Ability to customize router URLs for custom actions, using url_path. (#2010)
  • +
  • Don't install Django REST Framework as egg. (#2386)
  • +
+

3.0.2

+

Date: 17th December 2014.

+
    +
  • Ensure request.user is made available to response middleware. (#2155)
  • +
  • Client.logout() also cancels any existing force_authenticate. (#2218, #2259)
  • +
  • Extra assertions and better checks to preventing incorrect serializer API use. (#2228, #2234, #2262, #2263, #2266, #2267, #2289, #2291)
  • +
  • Fixed min_length message for CharField. (#2255)
  • +
  • Fix UnicodeDecodeError, which can occur on serializer repr. (#2270, #2279)
  • +
  • Fix empty HTML values when a default is provided. (#2280, #2294)
  • +
  • Fix SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. (#2290)
  • +
+

3.0.1

+

Date: 11th December 2014.

+
    +
  • More helpful error message when the default Serializer create() fails. (#2013)
  • +
  • Raise error when attempting to save serializer if data is not valid. (#2098)
  • +
  • Fix FileUploadParser breaks with empty file names and multiple upload handlers. (#2109)
  • +
  • Improve BindingDict to support standard dict-functions. (#2135, #2163)
  • +
  • Add validate() to ListSerializer. (#2168, #2225, #2232)
  • +
  • Fix JSONP renderer failing to escape some characters. (#2169, #2195)
  • +
  • Add missing default style for FileField. (#2172)
  • +
  • Actions are required when calling ViewSet.as_view(). (#2175)
  • +
  • Add allow_blank to ChoiceField. (#2184, #2239)
  • +
  • Cosmetic fixes in the HTML renderer. (#2187)
  • +
  • Raise error if fields on serializer is not a list of strings. (#2193, #2213)
  • +
  • Improve checks for nested creates and updates. (#2194, #2196)
  • +
  • validated_attrs argument renamed to validated_data in Serializer create()/update(). (#2197)
  • +
  • Remove deprecated code to reflect the dropped Django versions. (#2200)
  • +
  • Better serializer errors for nested writes. (#2202, #2215)
  • +
  • Fix pagination and custom permissions incompatibility. (#2205)
  • +
  • Raise error if fields on serializer is not a list of strings. (#2213)
  • +
  • Add missing translation markers for relational fields. (#2231)
  • +
  • Improve field lookup behavior for dicts/mappings. (#2244, #2243)
  • +
  • Optimized hyperlinked PK. (#2242)
  • +
+

3.0.0

+

Date: 1st December 2014

+

For full details see the 3.0 release announcement.

+
+

For older release notes, please see the version 2.x documentation.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/third-party-packages/index.html b/community/third-party-packages/index.html new file mode 100644 index 000000000..cb29b3459 --- /dev/null +++ b/community/third-party-packages/index.html @@ -0,0 +1,700 @@ + + + + + + + Third Party Packages - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + +

Third Party Packages

+
+

Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.

+

Jan Bosch.

+
+

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 favor the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.

+

We aim to make creating third party packages as easy as possible, whilst keeping a simple and well maintained core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.

+

If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the Mailing List.

+

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 cookiecutter 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 every time 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.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 Packages 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

+
    +
  • djangorestframework-digestauth - Provides Digest Access Authentication support.
  • +
  • django-oauth-toolkit - Provides OAuth 2.0 support.
  • +
  • djangorestframework-simplejwt - Provides JSON Web Token Authentication support.
  • +
  • hawkrest - Provides Hawk HTTP Authorization.
  • +
  • djangorestframework-httpsignature - Provides an easy to use HTTP Signature Authentication mechanism.
  • +
  • djoser - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
  • +
  • django-rest-auth - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
  • +
  • drf-oidc-auth - Implements OpenID Connect token authentication for DRF.
  • +
  • drfpasswordless - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
  • +
+

Permissions

+ +

Serializers

+
    +
  • django-rest-framework-mongoengine - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
  • +
  • djangorestframework-gis - Geographic add-ons
  • +
  • djangorestframework-hstore - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
  • +
  • djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
  • +
  • html-json-forms - Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.
  • +
  • django-rest-framework-serializer-extensions - + Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis.
  • +
  • djangorestframework-queryfields - Serializer mixin allowing clients to control which fields will be sent in the API response.
  • +
  • drf-flex-fields - Serializer providing dynamic field expansion and sparse field sets via URL parameters.
  • +
  • drf-action-serializer - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
  • +
  • djangorestframework-dataclasses - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
  • +
  • django-restql - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
  • +
+

Serializer fields

+
    +
  • drf-compound-fields - Provides "compound" serializer fields, such as lists of simple values.
  • +
  • django-extra-fields - Provides extra serializer fields.
  • +
  • django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.
  • +
+

Views

+
    +
  • django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
  • +
+

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

+
    +
  • djangorestframework-chain - Allows arbitrary chaining of both relations and lookup filters.
  • +
  • django-url-filter - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
  • +
  • drf-url-filter is a simple Django app to apply filters on drf ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
  • +
  • django-rest-framework-guardian - Provides integration with django-guardian, including the DjangoObjectPermissionsFilter previously found in DRF.
  • +
+

Misc

+ + + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/community/tutorials-and-resources/index.html b/community/tutorials-and-resources/index.html new file mode 100644 index 000000000..88d91fc12 --- /dev/null +++ b/community/tutorials-and-resources/index.html @@ -0,0 +1,571 @@ + + + + + + + Tutorials and Resources - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Tutorials and Resources

+

There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.

+

Books

+ + +

Tutorials

+ +

Videos

+

Talks

+ +

Tutorials

+ +

Articles

+ +

Documentations

+ +

Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us!

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/coreapi/7-schemas-and-client-libraries/index.html b/coreapi/7-schemas-and-client-libraries/index.html new file mode 100644 index 000000000..a3049427a --- /dev/null +++ b/coreapi/7-schemas-and-client-libraries/index.html @@ -0,0 +1,685 @@ + + + + + + + Tutorial 7: Schemas & client libraries - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + +

Tutorial 7: Schemas & client libraries

+

A schema is a machine-readable document that describes the available API +endpoints, their URLS, and what operations they support.

+

Schemas can be a useful tool for auto-generated documentation, and can also +be used to drive dynamic client libraries that can interact with the API.

+

Core API

+

In order to provide schema support REST framework uses Core API.

+

Core API is a document specification for describing APIs. It is used to provide +an internal representation format of the available endpoints and possible +interactions that an API exposes. It can either be used server-side, or +client-side.

+

When used server-side, Core API allows an API to support rendering to a wide +range of schema or hypermedia formats.

+

When used client-side, Core API allows for dynamically driven client libraries +that can interact with any API that exposes a supported schema or hypermedia +format.

+

Adding a schema

+

REST framework supports either explicitly defined schema views, or +automatically generated schemas. Since we're using viewsets and routers, +we can simply use the automatic schema generation.

+

You'll need to install the coreapi python package in order to include an +API schema, and pyyaml to render the schema into the commonly used +YAML-based OpenAPI format.

+
$ pip install coreapi pyyaml
+
+

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

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

If you visit the /schema/ endpoint in a browser you should now see corejson +representation become available as an option.

+

Schema format

+

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

+
$ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json
+HTTP/1.0 200 OK
+Allow: GET, HEAD, OPTIONS
+Content-Type: application/coreapi+json
+
+{
+    "_meta": {
+        "title": "Pastebin API"
+    },
+    "_type": "document",
+    ...
+
+

The default output style is to use the Core JSON encoding.

+

Other schema formats, such as Open API (formerly Swagger) are +also supported.

+

Using a command line client

+

Now that our API is exposing a schema endpoint, we can use a dynamic client +library to interact with the API. To demonstrate this, let's use the +Core API command line client.

+

The command line client is available as the coreapi-cli package:

+
$ pip install coreapi-cli
+
+

Now check that it is available on the command line...

+
$ coreapi
+Usage: coreapi [OPTIONS] COMMAND [ARGS]...
+
+  Command line client for interacting with CoreAPI services.
+
+  Visit https://www.coreapi.org/ for more information.
+
+Options:
+  --version  Display the package version number.
+  --help     Show this message and exit.
+
+Commands:
+...
+
+

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

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

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

+

Let's try listing the existing snippets, using the command line client:

+
$ coreapi action snippets list
+[
+    {
+        "url": "http://127.0.0.1:8000/snippets/1/",
+        "id": 1,
+        "highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
+        "owner": "lucy",
+        "title": "Example",
+        "code": "print('hello, world!')",
+        "linenos": true,
+        "language": "python",
+        "style": "friendly"
+    },
+    ...
+
+

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

+
$ coreapi action snippets highlight --param id=1
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+  <title>Example</title>
+  ...
+
+

Authenticating our client

+

If we want to be able to create, edit and delete snippets, we'll need to +authenticate as a valid user. In this case we'll just use basic auth.

+

Make sure to replace the <username> and <password> below with your +actual username and password.

+
$ coreapi credentials add 127.0.0.1 <username>:<password> --auth basic
+Added credentials
+127.0.0.1 "Basic <...>"
+
+

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

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

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

+
$ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
+{
+    "url": "http://127.0.0.1:8000/snippets/7/",
+    "id": 7,
+    "highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
+    "owner": "lucy",
+    "title": "Example",
+    "code": "print('hello, world')",
+    "linenos": false,
+    "language": "python",
+    "style": "friendly"
+}
+
+

And to delete a snippet:

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

As well as the command line client, developers can also interact with your +API using client libraries. The Python client library is the first of these +to be available, and a Javascript client library is planned to be released +soon.

+

For more details on customizing schema generation and using Core API +client libraries you'll need to refer to the full documentation.

+

Reviewing our work

+

With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.

+

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/coreapi/from-documenting-your-api/index.html b/coreapi/from-documenting-your-api/index.html new file mode 100644 index 000000000..29e7ae50d --- /dev/null +++ b/coreapi/from-documenting-your-api/index.html @@ -0,0 +1,637 @@ + + + + + + + From documenting your api - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Built-in API documentation

+

The built-in API documentation includes:

+
    +
  • Documentation of API endpoints.
  • +
  • Automatically generated code samples for each of the available API client libraries.
  • +
  • Support for API interaction.
  • +
+

Installation

+

The coreapi library is required as a dependency for the API docs. Make sure +to install the latest version. The Pygments and Markdown libraries +are optional but recommended.

+

To install the API documentation, you'll need to include it in your project's URLconf:

+
from rest_framework.documentation import include_docs_urls
+
+urlpatterns = [
+    ...
+    url(r'^docs/', include_docs_urls(title='My API title'))
+]
+
+

This will include two different views:

+
    +
  • /docs/ - The documentation page itself.
  • +
  • /docs/schema.js - A JavaScript resource that exposes the API schema.
  • +
+
+

Note: By default include_docs_urls configures the underlying SchemaView to generate public schemas. +This means that views will not be instantiated with a request instance. i.e. Inside the view self.request will be None.

+

To be compatible with this behaviour, methods (such as get_serializer or get_serializer_class etc.) which inspect self.request or, particularly, self.request.user may need to be adjusted to handle this case.

+

You may ensure views are given a request instance by calling include_docs_urls with public=False:

+
from rest_framework.documentation import include_docs_urls
+
+urlpatterns = [
+    ...
+    # Generate schema with valid `request` instance:
+    url(r'^docs/', include_docs_urls(title='My API title', public=False))
+]
+
+
+

Documenting your views

+

You can document your views by including docstrings that describe each of the available actions. +For example:

+
class UserList(generics.ListAPIView):
+    """
+    Return a list of all the existing users.
+    """
+
+

If a view supports multiple methods, you should split your documentation using method: style delimiters.

+
class UserList(generics.ListCreateAPIView):
+    """
+    get:
+    Return a list of all the existing users.
+
+    post:
+    Create a new user instance.
+    """
+
+

When using viewsets, you should use the relevant action names as delimiters.

+
class UserViewSet(viewsets.ModelViewSet):
+    """
+    retrieve:
+    Return the given user.
+
+    list:
+    Return a list of all the existing users.
+
+    create:
+    Create a new user instance.
+    """
+
+

Custom actions on viewsets can also be documented in a similar way using the method names +as delimiters or by attaching the documentation to action mapping methods.

+
class UserViewSet(viewsets.ModelViewset):
+    ...
+
+    @action(detail=False, methods=['get', 'post'])
+    def some_action(self, request, *args, **kwargs):
+        """
+        get:
+        A description of the get method on the custom action.
+
+        post:
+        A description of the post method on the custom action.
+        """
+
+    @some_action.mapping.put
+    def put_some_action():
+        """
+        A description of the put method on the custom action.
+        """
+
+

documentation API Reference

+

The rest_framework.documentation module provides three helper functions to help configure the interactive API documentation, include_docs_urls (usage shown above), get_docs_view and get_schemajs_view.

+

include_docs_urls employs get_docs_view and get_schemajs_view to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (get_docs_view and get_schemajs_view ultimately call rest_frameworks.schemas.get_schema_view(), see the Schemas docs for more options there.)

+

include_docs_urls

+
    +
  • title: Default None. May be used to provide a descriptive title for the schema definition.
  • +
  • description: Default None. May be used to provide a description for the schema definition.
  • +
  • schema_url: Default None. May be used to pass a canonical base URL for the schema.
  • +
  • public: Default True. Should the schema be considered public? If True schema is generated without a request instance being passed to views.
  • +
  • patterns: Default None. A list of URLs to inspect when generating the schema. If None project's URL conf will be used.
  • +
  • generator_class: Default rest_framework.schemas.SchemaGenerator. May be used to specify a SchemaGenerator subclass to be passed to the SchemaView.
  • +
  • authentication_classes: Default api_settings.DEFAULT_AUTHENTICATION_CLASSES. May be used to pass custom authentication classes to the SchemaView.
  • +
  • permission_classes: Default api_settings.DEFAULT_PERMISSION_CLASSES May be used to pass custom permission classes to the SchemaView.
  • +
  • renderer_classes: Default None. May be used to pass custom renderer classes to the SchemaView.
  • +
+

get_docs_view

+
    +
  • title: Default None. May be used to provide a descriptive title for the schema definition.
  • +
  • description: Default None. May be used to provide a description for the schema definition.
  • +
  • schema_url: Default None. May be used to pass a canonical base URL for the schema.
  • +
  • public: Default True. If True schema is generated without a request instance being passed to views.
  • +
  • patterns: Default None. A list of URLs to inspect when generating the schema. If None project's URL conf will be used.
  • +
  • generator_class: Default rest_framework.schemas.SchemaGenerator. May be used to specify a SchemaGenerator subclass to be passed to the SchemaView.
  • +
  • authentication_classes: Default api_settings.DEFAULT_AUTHENTICATION_CLASSES. May be used to pass custom authentication classes to the SchemaView.
  • +
  • permission_classes: Default api_settings.DEFAULT_PERMISSION_CLASSES. May be used to pass custom permission classes to the SchemaView.
  • +
  • renderer_classes: Default None. May be used to pass custom renderer classes to the SchemaView. If None the SchemaView will be configured with DocumentationRenderer and CoreJSONRenderer renderers, corresponding to the (default) html and corejson formats.
  • +
+

get_schemajs_view

+
    +
  • title: Default None. May be used to provide a descriptive title for the schema definition.
  • +
  • description: Default None. May be used to provide a description for the schema definition.
  • +
  • schema_url: Default None. May be used to pass a canonical base URL for the schema.
  • +
  • public: Default True. If True schema is generated without a request instance being passed to views.
  • +
  • patterns: Default None. A list of URLs to inspect when generating the schema. If None project's URL conf will be used.
  • +
  • generator_class: Default rest_framework.schemas.SchemaGenerator. May be used to specify a SchemaGenerator subclass to be passed to the SchemaView.
  • +
  • authentication_classes: Default api_settings.DEFAULT_AUTHENTICATION_CLASSES. May be used to pass custom authentication classes to the SchemaView.
  • +
  • permission_classes: Default api_settings.DEFAULT_PERMISSION_CLASSES May be used to pass custom permission classes to the SchemaView.
  • +
+

Customising code samples

+

The built-in API documentation includes automatically generated code samples for +each of the available API client libraries.

+

You may customise these samples by subclassing DocumentationRenderer, setting +languages to the list of languages you wish to support:

+
from rest_framework.renderers import DocumentationRenderer
+
+
+class CustomRenderer(DocumentationRenderer):
+    languages = ['ruby', 'go']
+
+

For each language you need to provide an intro template, detailing installation instructions and such, +plus a generic template for making API requests, that can be filled with individual request details. +See the templates for the bundled languages for examples.

+
+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/coreapi/index.html b/coreapi/index.html new file mode 100644 index 000000000..3a721084d --- /dev/null +++ b/coreapi/index.html @@ -0,0 +1,503 @@ + + + + + + + Legacy CoreAPI Schemas Docs - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+
+
+ + +
+
+ +
+ + + +

Legacy CoreAPI Schemas Docs

+

Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.

+

See the Version 3.10 Release Announcement for more details.

+
+

You can continue to use CoreAPI schemas by setting the appropriate default schema class:

+
# In settings.py
+REST_FRAMEWORK = {
+    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
+}
+
+ +

Under-the-hood, any subclass of coreapi.AutoSchema here will trigger use of the old CoreAPI schemas. +Otherwise you will automatically be opted-in to the new OpenAPI schemas.

+

All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.

+
+

For reference this folder contains the old CoreAPI related documentation:

+ + + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/coreapi/schemas/index.html b/coreapi/schemas/index.html new file mode 100644 index 000000000..44c25829a --- /dev/null +++ b/coreapi/schemas/index.html @@ -0,0 +1,1248 @@ + + + + + + + Schemas - Django REST framework + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
+ + +
+ + + + + s + + + + c + + + + h + + + + e + + + + m + + + + a + + + + s + + + + . + + + + p + + + + y + + + + +

Schemas

+
+

A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.

+

— Heroku, JSON Schema for the Heroku Platform API

+
+

API schemas are a useful tool that allow for a range of use cases, including +generating reference documentation, or driving dynamic client libraries that +can interact with your API.

+

Install Core API & PyYAML

+

You'll need to install the coreapi package in order to add schema support +for REST framework. You probably also want to install pyyaml, so that you +can render the schema into the commonly used YAML-based OpenAPI format.

+
pip install coreapi pyyaml
+
+

Quickstart

+

There are two different ways you can serve a schema description for your API.

+

Generating a schema with the generateschema management command

+

To generate a static API schema, use the generateschema management command.

+
$ python manage.py generateschema > schema.yml
+
+ +

Once you've generated a schema in this way you can annotate it with any +additional information that cannot be automatically inferred by the schema +generator.

+

You might want to check your API schema into version control and update it +with each new release, or serve the API schema from your site's static media.

+

Adding a view with get_schema_view

+

To add a dynamically generated schema view to your API, use get_schema_view.

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

See below for more details on customizing a +dynamically generated schema view.

+

Internal schema representation

+

REST framework uses Core API in order to model schema information in +a format-independent representation. This information can then be rendered +into various different schema formats, or used to generate API documentation.

+

When using Core API, a schema is represented as a Document which is the +top-level container object for information about the API. Available API +interactions are represented using Link objects. Each link includes a URL, +HTTP method, and may include a list of Field instances, which describe any +parameters that may be accepted by the API endpoint. The Link and Field +instances may also include descriptions, that allow an API schema to be +rendered into user documentation.

+

Here's an example of an API description that includes a single search +endpoint:

+
coreapi.Document(
+    title='Flight Search API',
+    url='https://api.example.org/',
+    content={
+        'search': coreapi.Link(
+            url='/search/',
+            action='get',
+            fields=[
+                coreapi.Field(
+                    name='from',
+                    required=True,
+                    location='query',
+                    description='City name or airport code.'
+                ),
+                coreapi.Field(
+                    name='to',
+                    required=True,
+                    location='query',
+                    description='City name or airport code.'
+                ),
+                coreapi.Field(
+                    name='date',
+                    required=True,
+                    location='query',
+                    description='Flight date in "YYYY-MM-DD" format.'
+                )
+            ],
+            description='Return flight availability and prices.'
+        )
+    }
+)
+
+

Schema output formats

+

In order to be presented in an HTTP response, the internal representation +has to be rendered into the actual bytes that are used in the response.

+

REST framework includes a few different renderers that you can use for +encoding the API schema.

+
    +
  • renderers.OpenAPIRenderer - Renders into YAML-based OpenAPI, the most widely used API schema format.
  • +
  • renderers.JSONOpenAPIRenderer - Renders into JSON-based OpenAPI.
  • +
  • renderers.CoreJSONRenderer - Renders into Core JSON, a format designed for +use with the coreapi client library.
  • +
+

Core JSON is designed as a canonical format for use with Core API. +REST framework includes a renderer class for handling this media type, which +is available as renderers.CoreJSONRenderer.

+

Schemas vs Hypermedia

+

It's worth pointing out here that Core API can also be used to model hypermedia +responses, which present an alternative interaction style to API schemas.

+

With an API schema, the entire available interface is presented up-front +as a single endpoint. Responses to individual API endpoints are then typically +presented as plain data, without any further interactions contained in each +response.

+

With Hypermedia, the client is instead presented with a document containing +both data and available interactions. Each interaction results in a new +document, detailing both the current state and the available interactions.

+

Further information and support on building Hypermedia APIs with REST framework +is planned for a future version.

+
+

Creating a schema

+

REST framework includes functionality for auto-generating a schema, +or allows you to specify one explicitly.

+

Manual Schema Specification

+

To manually specify a schema you create a Core API Document, similar to the +example above.

+
schema = coreapi.Document(
+    title='Flight Search API',
+    content={
+        ...
+    }
+)
+
+

Automatic Schema Generation

+

Automatic schema generation is provided by the SchemaGenerator class.

+

SchemaGenerator processes a list of routed URL patterns and compiles the +appropriately structured Core API Document.

+

Basic usage is just to provide the title for your schema and call +get_schema():

+
generator = schemas.SchemaGenerator(title='Flight Search API')
+schema = generator.get_schema()
+
+

Per-View Schema Customisation

+

By default, view introspection is performed by an AutoSchema instance +accessible via the schema attribute on APIView. This provides the +appropriate Core API Link object for the view, request method and path:

+
auto_schema = view.schema
+coreapi_link = auto_schema.get_link(...)
+
+

(In compiling the schema, SchemaGenerator calls view.schema.get_link() for +each view, allowed method and path.)

+
+

Note: For basic APIView subclasses, default introspection is essentially +limited to the URL kwarg path parameters. For GenericAPIView +subclasses, which includes all the provided class based views, AutoSchema will +attempt to introspect serializer, pagination and filter fields, as well as +provide richer path field descriptions. (The key hooks here are the relevant +GenericAPIView attributes and methods: get_serializer, pagination_class, +filter_backends and so on.)

+
+

To customise the Link generation you may:

+
    +
  • +

    Instantiate AutoSchema on your view with the manual_fields kwarg:

    +
    from rest_framework.views import APIView
    +from rest_framework.schemas import AutoSchema
    +
    +class CustomView(APIView):
    +    ...
    +    schema = AutoSchema(
    +        manual_fields=[
    +            coreapi.Field("extra_field", ...),
    +        ]
    +    )
    +
    +

    This allows extension for the most common case without subclassing.

    +
  • +
  • +

    Provide an AutoSchema subclass with more complex customisation:

    +
    from rest_framework.views import APIView
    +from rest_framework.schemas import AutoSchema
    +
    +class CustomSchema(AutoSchema):
    +    def get_link(...):
    +        # Implement custom introspection here (or in other sub-methods)
    +
    +class CustomView(APIView):
    +    ...
    +    schema = CustomSchema()
    +
    +

    This provides complete control over view introspection.

    +
  • +
  • +

    Instantiate ManualSchema on your view, providing the Core API Fields for + the view explicitly:

    +
    from rest_framework.views import APIView
    +from rest_framework.schemas import ManualSchema
    +
    +class CustomView(APIView):
    +    ...
    +    schema = ManualSchema(fields=[
    +        coreapi.Field(
    +            "first_field",
    +            required=True,
    +            location="path",
    +            schema=coreschema.String()
    +        ),
    +        coreapi.Field(
    +            "second_field",
    +            required=True,
    +            location="path",
    +            schema=coreschema.String()
    +        ),
    +    ])
    +
    +

    This allows manually specifying the schema for some views whilst maintaining +automatic generation elsewhere.

    +
  • +
+

You may disable schema generation for a view by setting schema to None:

+
    class CustomView(APIView):
+        ...
+        schema = None  # Will not appear in schema
+
+

This also applies to extra actions for ViewSets:

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

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

+
+

Adding a schema view

+

There are a few different ways to add a schema view to your API, depending on +exactly what you need.

+

The get_schema_view shortcut

+

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

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

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

+
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
+HTTP/1.0 200 OK
+Allow: GET, HEAD, OPTIONS
+Content-Type: application/vnd.coreapi+json
+
+{
+    "_meta": {
+        "title": "Server Monitoring API"
+    },
+    "_type": "document",
+    ...
+}
+
+

The arguments to get_schema_view() are:

+

title

+

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

+

url

+

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

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

urlconf

+

A string representing the import path to the URL conf that you want +to generate an API schema for. This defaults to the value of Django's +ROOT_URLCONF setting.

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

renderer_classes

+

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

+
from rest_framework.schemas import get_schema_view
+from rest_framework.renderers import JSONOpenAPIRenderer
+
+schema_view = get_schema_view(
+    title='Server Monitoring API',
+    url='https://www.example.org/api/',
+    renderer_classes=[JSONOpenAPIRenderer]
+)
+
+

patterns

+

List of url patterns to limit the schema introspection to. If you only want the myproject.api urls +to be exposed in the schema:

+
schema_url_patterns = [
+    url(r'^api/', include('myproject.api.urls')),
+]
+
+schema_view = get_schema_view(
+    title='Server Monitoring API',
+    url='https://www.example.org/api/',
+    patterns=schema_url_patterns,
+)
+
+

generator_class

+

May be used to specify a SchemaGenerator subclass to be passed to the +SchemaView.

+

authentication_classes

+

May be used to specify the list of authentication classes that will apply to the schema endpoint. +Defaults to settings.DEFAULT_AUTHENTICATION_CLASSES

+

permission_classes

+

May be used to specify the list of permission classes that will apply to the schema endpoint. +Defaults to settings.DEFAULT_PERMISSION_CLASSES

+

Using an explicit schema view

+

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

+

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

+

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

+

views.py:

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

urls.py:

+
urlpatterns = [
+    url('/', schema_view),
+    ...
+]
+
+

You can also serve different schemas to different users, depending on the +permissions they have available. This approach can be used to ensure that +unauthenticated requests are presented with a different schema to +authenticated requests, or to ensure that different parts of the API are +made visible to different users depending on their role.

+

In order to present a schema with endpoints filtered by user permissions, +you need to pass the request argument to the get_schema() method, like so:

+
@api_view()
+@renderer_classes([renderers.OpenAPIRenderer])
+def schema_view(request):
+    generator = schemas.SchemaGenerator(title='Bookings API')
+    return response.Response(generator.get_schema(request=request))
+
+

Explicit schema definition

+

An alternative to the auto-generated approach is to specify the API schema +explicitly, by declaring a Document object in your codebase. Doing so is a +little more work, but ensures that you have full control over the schema +representation.

+
import coreapi
+from rest_framework.decorators import api_view, renderer_classes
+from rest_framework import renderers, response
+
+schema = coreapi.Document(
+    title='Bookings API',
+    content={
+        ...
+    }
+)
+
+@api_view()
+@renderer_classes([renderers.OpenAPIRenderer])
+def schema_view(request):
+    return response.Response(schema)
+
+
+

Schemas as documentation

+

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

+

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

+

These descriptions will be based on:

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

Examples

+

An APIView, with an explicit method docstring.

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

A ViewSet, with an explicit action docstring.

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

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

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

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

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

API Reference

+

SchemaGenerator

+

A class that walks a list of routed URL patterns, requests the schema for each view, +and collates the resulting CoreAPI Document.

+

Typically you'll instantiate SchemaGenerator with a single argument, like so:

+
generator = SchemaGenerator(title='Stock Prices API')
+
+

Arguments:

+
    +
  • title required - The name of the API.
  • +
  • url - The root URL of the API schema. This option is not required unless the schema is included under path prefix.
  • +
  • patterns - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
  • +
  • urlconf - A URL conf module name to use when generating the schema. Defaults to settings.ROOT_URLCONF.
  • +
+

get_schema(self, request)

+

Returns a coreapi.Document instance that represents the API schema.

+
@api_view
+@renderer_classes([renderers.OpenAPIRenderer])
+def schema_view(request):
+    generator = schemas.SchemaGenerator(title='Bookings API')
+    return Response(generator.get_schema())
+
+

The request argument is optional, and may be used if you want to apply per-user +permissions to the resulting schema generation.

+

get_links(self, request)

+

Return a nested dictionary containing all the links that should be included in the API schema.

+

This is a good point to override if you want to modify the resulting structure of the generated schema, +as you can build a new dictionary with a different layout.

+

AutoSchema

+

A class that deals with introspection of individual views for schema generation.

+

AutoSchema is attached to APIView via the schema attribute.

+

The AutoSchema constructor takes a single keyword argument manual_fields.

+

manual_fields: a list of coreapi.Field instances that will be added to +the generated fields. Generated fields with a matching name will be overwritten.

+
class CustomView(APIView):
+    schema = AutoSchema(manual_fields=[
+        coreapi.Field(
+            "my_extra_field",
+            required=True,
+            location="path",
+            schema=coreschema.String()
+        ),
+    ])
+
+

For more advanced customisation subclass AutoSchema to customise schema generation.

+
class CustomViewSchema(AutoSchema):
+    """
+    Overrides `get_link()` to provide Custom Behavior X
+    """
+
+    def get_link(self, path, method, base_url):
+        link = super().get_link(path, method, base_url)
+        # Do something to customize link here...
+        return link
+
+class MyView(APIView):
+  schema = CustomViewSchema()
+
+

The following methods are available to override.

+

get_link(self, path, method, base_url)

+

Returns a coreapi.Link instance corresponding to the given view.

+

This is the main entry point. +You can override this if you need to provide custom behaviors for particular views.

+

get_description(self, path, method)

+

Returns a string to use as the link description. By default this is based on the +view docstring as described in the "Schemas as Documentation" section above.

+

get_encoding(self, path, method)

+

Returns a string to indicate the encoding for any request body, when interacting +with the given view. Eg. 'application/json'. May return a blank string for views +that do not expect a request body.

+

get_path_fields(self, path, method):

+

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

+

get_serializer_fields(self, path, method)

+

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

+

get_pagination_fields(self, path, method)

+

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

+

get_filter_fields(self, path, method)

+

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

+

get_manual_fields(self, path, method)

+

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

+

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

+
def get_manual_fields(self, path, method):
+    """Example adding per-method fields."""
+
+    extra_fields = []
+    if method=='GET':
+        extra_fields = # ... list of extra fields for GET ...
+    if method=='POST':
+        extra_fields = # ... list of extra fields for POST ...
+
+    manual_fields = super().get_manual_fields(path, method)
+    return manual_fields + extra_fields
+
+ +

update_fields(fields, update_with)

+

Utility staticmethod. Encapsulates logic to add or replace fields from a list +by Field.name. May be overridden to adjust replacement criteria.

+

ManualSchema

+

Allows manually providing a list of coreapi.Field instances for the schema, +plus an optional description.

+
class MyView(APIView):
+  schema = ManualSchema(fields=[
+        coreapi.Field(
+            "first_field",
+            required=True,
+            location="path",
+            schema=coreschema.String()
+        ),
+        coreapi.Field(
+            "second_field",
+            required=True,
+            location="path",
+            schema=coreschema.String()
+        ),
+    ]
+  )
+
+

The ManualSchema constructor takes two arguments:

+

fields: A list of coreapi.Field instances. Required.

+

description: A string description. Optional.

+

encoding: Default None. A string encoding, e.g application/json. Optional.

+
+

Core API

+

This documentation gives a brief overview of the components within the coreapi +package that are used to represent an API schema.

+

Note that these classes are imported from the coreapi package, rather than +from the rest_framework package.

+

Document

+

Represents a container for the API schema.

+

title

+

A name for the API.

+

url

+

A canonical URL for the API.

+

content

+

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

+

In order to provide more structure to the schema, the content dictionary +may be nested, typically to a second level. For example:

+
content={
+    "bookings": {
+        "list": Link(...),
+        "create": Link(...),
+        ...
+    },
+    "venues": {
+        "list": Link(...),
+        ...
+    },
+    ...
+}
+
+ +

Represents an individual API endpoint.

+

url

+

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

+

action

+

The HTTP method associated with the endpoint. Note that URLs that support +more than one HTTP method, should correspond to a single Link for each.

+

fields

+

A list of Field instances, describing the available parameters on the input.

+

description

+

A short description of the meaning and intended usage of the endpoint.

+

Field

+

Represents a single input parameter on a given API endpoint.

+

name

+

A descriptive name for the input.

+

required

+

A boolean, indicated if the client is required to included a value, or if +the parameter can be omitted.

+

location

+

Determines how the information is encoded into the request. Should be one of +the following strings:

+

"path"

+

Included in a templated URI. For example a url value of /products/{product_code}/ could be used together with a "path" field, to handle API inputs in a URL path such as /products/slim-fit-jeans/.

+

These fields will normally correspond with named arguments in the project URL conf.

+

"query"

+

Included as a URL query parameter. For example ?search=sale. Typically for GET requests.

+

These fields will normally correspond with pagination and filtering controls on a view.

+

"form"

+

Included in the request body, as a single item of a JSON object or HTML form. For example {"colour": "blue", ...}. Typically for POST, PUT and PATCH requests. Multiple "form" fields may be included on a single link.

+

These fields will normally correspond with serializer fields on a view.

+

"body"

+

Included as the complete request body. Typically for POST, PUT and PATCH requests. No more than one "body" field may exist on a link. May not be used together with "form" fields.

+

These fields will normally correspond with views that use ListSerializer to validate the request input, or with file upload views.

+

encoding

+

"application/json"

+

JSON encoded request content. Corresponds to views using JSONParser. +Valid only if either one or more location="form" fields, or a single +location="body" field is included on the Link.

+

"multipart/form-data"

+

Multipart encoded request content. Corresponds to views using MultiPartParser. +Valid only if one or more location="form" fields is included on the Link.

+

"application/x-www-form-urlencoded"

+

URL encoded request content. Corresponds to views using FormParser. Valid +only if one or more location="form" fields is included on the Link.

+

"application/octet-stream"

+

Binary upload request content. Corresponds to views using FileUploadParser. +Valid only if a location="body" field is included on the Link.

+

description

+

A short description of the meaning and intended usage of the input field.

+
+

Third party packages

+

drf-yasg - Yet Another Swagger Generator

+

drf-yasg generates OpenAPI documents suitable for code generation - nested schemas, +named models, response bodies, enum/pattern/min/max validators, form parameters, etc.

+ + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/css/base.css b/css/base.css new file mode 100644 index 000000000..a71c186f1 --- /dev/null +++ b/css/base.css @@ -0,0 +1,324 @@ +body { + padding-top: 70px; +} + +/* Replacement for `body { background-attachment: fixed; }`, which has + performance issues when scrolling on large displays. See #1394. */ +body::before { + content: ' '; + position: fixed; + width: 100%; + height: 100%; + top: 0; + left: 0; + background-color: #f8f8f8; + background: url(../img/grid.png) repeat-x; + will-change: transform; + z-index: -1; +} + +body > .container { + min-height: 400px; +} + +ul.nav .main { + font-weight: bold; +} + +.col-md-3 { + padding-left: 0; + z-index: 1; +} + +.col-md-9 { + padding-bottom: 100px; +} + +.source-links { + float: right; +} + +.col-md-9 img { + max-width: 100%; + display: inline-block; + padding: 4px; + line-height: 1.428571429; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + margin: 20px auto 30px auto; +} + +/* + * The code below adds some padding to the top of the current anchor target so + * that, when navigating to it, the header isn't hidden by the navbar at the + * top. + */ +:target::before { + content: ""; + display: block; + margin-top: -75px; + height: 75px; + pointer-events: none; +} + +h1 { + color: #444; + font-weight: 400; + font-size: 42px; +} + +h2, h3, h4, h5, h6 { + color: #444; + font-weight: 300; +} + +hr { + border-top: 1px solid #aaa; +} + +pre, .rst-content tt { + max-width: 100%; + background: #fff; + border: solid 1px #e1e4e5; + color: #333; + overflow-x: auto; +} + +code.code-large, .rst-content tt.code-large { + font-size: 90%; +} + +code { + padding: 2px 5px; + background: #fff; + border: solid 1px #e1e4e5; + color: #333; + white-space: pre-wrap; + word-wrap: break-word; +} + +pre code { + background: transparent; + border: none; + white-space: pre; + word-wrap: normal; + font-family: monospace,serif; + font-size: 12px; +} + +kbd { + padding: 2px 4px; + font-size: 90%; + color: #fff; + background-color: #333; + border-radius: 3px; + -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.25); + box-shadow: inset 0 -1px 0 rgba(0,0,0,.25); +} + +a code { + color: #2FA4E7; +} + +a:hover code, a:focus code { + color: #157AB5; +} + +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 { /* csslint allow: adjoining-classes */ + position: static; +} + +.bs-sidebar.well { /* csslint allow: adjoining-classes */ + padding: 0; + max-height: 90%; + overflow-y: auto; +} + +/* 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; + z-index: 1; +} +.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) { + /* Workaround a Safari bug when zooming to < 100% + https://github.com/mkdocs/mkdocs/issues/1050 */ + .col-md-9 { + box-sizing: border-box; /* csslint allow: box-sizing */ + padding-left: 25%; + width: 100%; + } + .bs-sidebar .nav > .active > ul { + display: block; + } + /* Widen the fixed sidebar */ + .bs-sidebar.affix, /* csslint allow: adjoining-classes */ + .bs-sidebar.affix-bottom { /* csslint allow: adjoining-classes */ + width: 213px; + } + .bs-sidebar.affix { /* csslint allow: adjoining-classes */ + position: fixed; /* Undo the static from mobile first approach */ + top: 80px; + } + .bs-sidebar.affix-bottom { /* csslint allow: adjoining-classes */ + position: absolute; /* Undo the static from mobile first approach */ + } + .bs-sidebar.affix-bottom .bs-sidenav, /* csslint allow: adjoining-classes */ + .bs-sidebar.affix .bs-sidenav { /* csslint allow: adjoining-classes */ + margin-top: 0; + margin-bottom: 0; + } +} +@media (min-width: 1200px) { + /* Widen the fixed sidebar again */ + .bs-sidebar.affix-bottom, /* csslint allow: adjoining-classes */ + .bs-sidebar.affix { /* csslint allow: adjoining-classes */ + width: 263px; + } +} + +.headerlink { + font-family: FontAwesome; + font-size: 14px; + display: none; + padding-left: .5em; +} + +h1:hover .headerlink, h2:hover .headerlink, h3:hover .headerlink, h4:hover .headerlink, h5:hover .headerlink, h6:hover .headerlink{ + display:inline-block; +} + + + +.admonition { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; + text-align: left; +} + +.admonition.note { /* csslint allow: adjoining-classes */ + color: #3a87ad; + background-color: #d9edf7; + border-color: #bce8f1; +} + +.admonition.warning { /* csslint allow: adjoining-classes */ + color: #c09853; + background-color: #fcf8e3; + border-color: #fbeed5; +} + +.admonition.danger { /* csslint allow: adjoining-classes */ + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; +} + +.admonition-title { + font-weight: bold; + text-align: left; +} + + +.dropdown-submenu { + position: relative; +} + +.dropdown-submenu>.dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px; + border-radius: 0 6px 6px 6px; +} + +.dropdown-submenu:hover>.dropdown-menu { + display: block; +} + +.dropdown-submenu>a:after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: #ccc; + margin-top: 5px; + margin-right: -10px; +} + +.dropdown-submenu:hover>a:after { + border-left-color: #fff; +} + +.dropdown-submenu.pull-left { /* csslint allow: adjoining-classes */ + float: none; +} + +.dropdown-submenu.pull-left>.dropdown-menu { /* csslint allow: adjoining-classes */ + left: -100%; + margin-left: 10px; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; +} 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 new file mode 100644 index 000000000..ec0b51947 --- /dev/null +++ b/css/bootstrap-responsive.css @@ -0,0 +1,1058 @@ +/*! + * Bootstrap Responsive v2.1.1 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + +.clearfix { + *zoom: 1; +} + +.clearfix:before, +.clearfix:after { + display: table; + line-height: 0; + content: ""; +} + +.clearfix:after { + clear: both; +} + +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} + +.input-block-level { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.hidden { + display: none; + visibility: hidden; +} + +.visible-phone { + display: none !important; +} + +.visible-tablet { + display: none !important; +} + +.hidden-desktop { + display: none !important; +} + +.visible-desktop { + display: inherit !important; +} + +@media (min-width: 768px) and (max-width: 979px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important ; + } + .visible-tablet { + display: inherit !important; + } + .hidden-tablet { + display: none !important; + } +} + +@media (max-width: 767px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important; + } + .visible-phone { + display: inherit !important; + } + .hidden-phone { + display: none !important; + } +} + +@media (min-width: 1200px) { + .row { + margin-left: -30px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 30px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 1170px; + } + .span12 { + width: 1170px; + } + .span11 { + width: 1070px; + } + .span10 { + width: 970px; + } + .span9 { + width: 870px; + } + .span8 { + width: 770px; + } + .span7 { + width: 670px; + } + .span6 { + width: 570px; + } + .span5 { + width: 470px; + } + .span4 { + width: 370px; + } + .span3 { + width: 270px; + } + .span2 { + width: 170px; + } + .span1 { + width: 70px; + } + .offset12 { + margin-left: 1230px; + } + .offset11 { + margin-left: 1130px; + } + .offset10 { + margin-left: 1030px; + } + .offset9 { + margin-left: 930px; + } + .offset8 { + margin-left: 830px; + } + .offset7 { + margin-left: 730px; + } + .offset6 { + margin-left: 630px; + } + .offset5 { + margin-left: 530px; + } + .offset4 { + margin-left: 430px; + } + .offset3 { + margin-left: 330px; + } + .offset2 { + margin-left: 230px; + } + .offset1 { + margin-left: 130px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.564102564102564%; + *margin-left: 2.5109110747408616%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.45299145299145%; + *width: 91.39979996362975%; + } + .row-fluid .span10 { + width: 82.90598290598291%; + *width: 82.8527914166212%; + } + .row-fluid .span9 { + width: 74.35897435897436%; + *width: 74.30578286961266%; + } + .row-fluid .span8 { + width: 65.81196581196582%; + *width: 65.75877432260411%; + } + .row-fluid .span7 { + width: 57.26495726495726%; + *width: 57.21176577559556%; + } + .row-fluid .span6 { + width: 48.717948717948715%; + *width: 48.664757228587014%; + } + .row-fluid .span5 { + width: 40.17094017094017%; + *width: 40.11774868157847%; + } + .row-fluid .span4 { + width: 31.623931623931625%; + *width: 31.570740134569924%; + } + .row-fluid .span3 { + width: 23.076923076923077%; + *width: 23.023731587561375%; + } + .row-fluid .span2 { + width: 14.52991452991453%; + *width: 14.476723040552828%; + } + .row-fluid .span1 { + width: 5.982905982905983%; + *width: 5.929714493544281%; + } + .row-fluid .offset12 { + margin-left: 105.12820512820512%; + *margin-left: 105.02182214948171%; + } + .row-fluid .offset12:first-child { + margin-left: 102.56410256410257%; + *margin-left: 102.45771958537915%; + } + .row-fluid .offset11 { + margin-left: 96.58119658119658%; + *margin-left: 96.47481360247316%; + } + .row-fluid .offset11:first-child { + margin-left: 94.01709401709402%; + *margin-left: 93.91071103837061%; + } + .row-fluid .offset10 { + margin-left: 88.03418803418803%; + *margin-left: 87.92780505546462%; + } + .row-fluid .offset10:first-child { + margin-left: 85.47008547008548%; + *margin-left: 85.36370249136206%; + } + .row-fluid .offset9 { + margin-left: 79.48717948717949%; + *margin-left: 79.38079650845607%; + } + .row-fluid .offset9:first-child { + margin-left: 76.92307692307693%; + *margin-left: 76.81669394435352%; + } + .row-fluid .offset8 { + margin-left: 70.94017094017094%; + *margin-left: 70.83378796144753%; + } + .row-fluid .offset8:first-child { + margin-left: 68.37606837606839%; + *margin-left: 68.26968539734497%; + } + .row-fluid .offset7 { + margin-left: 62.393162393162385%; + *margin-left: 62.28677941443899%; + } + .row-fluid .offset7:first-child { + margin-left: 59.82905982905982%; + *margin-left: 59.72267685033642%; + } + .row-fluid .offset6 { + margin-left: 53.84615384615384%; + *margin-left: 53.739770867430444%; + } + .row-fluid .offset6:first-child { + margin-left: 51.28205128205128%; + *margin-left: 51.175668303327875%; + } + .row-fluid .offset5 { + margin-left: 45.299145299145295%; + *margin-left: 45.1927623204219%; + } + .row-fluid .offset5:first-child { + margin-left: 42.73504273504273%; + *margin-left: 42.62865975631933%; + } + .row-fluid .offset4 { + margin-left: 36.75213675213675%; + *margin-left: 36.645753773413354%; + } + .row-fluid .offset4:first-child { + margin-left: 34.18803418803419%; + *margin-left: 34.081651209310785%; + } + .row-fluid .offset3 { + margin-left: 28.205128205128204%; + *margin-left: 28.0987452264048%; + } + .row-fluid .offset3:first-child { + margin-left: 25.641025641025642%; + *margin-left: 25.53464266230224%; + } + .row-fluid .offset2 { + margin-left: 19.65811965811966%; + *margin-left: 19.551736679396257%; + } + .row-fluid .offset2:first-child { + margin-left: 17.094017094017094%; + *margin-left: 16.98763411529369%; + } + .row-fluid .offset1 { + margin-left: 11.11111111111111%; + *margin-left: 11.004728132387708%; + } + .row-fluid .offset1:first-child { + margin-left: 8.547008547008547%; + *margin-left: 8.440625568285142%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 30px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 1156px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 1056px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 956px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 856px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 756px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 656px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 556px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 456px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 356px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 256px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 156px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 56px; + } + .thumbnails { + margin-left: -30px; + } + .thumbnails > li { + margin-left: 30px; + } + .row-fluid .thumbnails { + margin-left: 0; + } +} + +@media (min-width: 768px) and (max-width: 979px) { + .row { + margin-left: -20px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 724px; + } + .span12 { + width: 724px; + } + .span11 { + width: 662px; + } + .span10 { + width: 600px; + } + .span9 { + width: 538px; + } + .span8 { + width: 476px; + } + .span7 { + width: 414px; + } + .span6 { + width: 352px; + } + .span5 { + width: 290px; + } + .span4 { + width: 228px; + } + .span3 { + width: 166px; + } + .span2 { + width: 104px; + } + .span1 { + width: 42px; + } + .offset12 { + margin-left: 764px; + } + .offset11 { + margin-left: 702px; + } + .offset10 { + margin-left: 640px; + } + .offset9 { + margin-left: 578px; + } + .offset8 { + margin-left: 516px; + } + .offset7 { + margin-left: 454px; + } + .offset6 { + margin-left: 392px; + } + .offset5 { + margin-left: 330px; + } + .offset4 { + margin-left: 268px; + } + .offset3 { + margin-left: 206px; + } + .offset2 { + margin-left: 144px; + } + .offset1 { + margin-left: 82px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.7624309392265194%; + *margin-left: 2.709239449864817%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.43646408839778%; + *width: 91.38327259903608%; + } + .row-fluid .span10 { + width: 82.87292817679558%; + *width: 82.81973668743387%; + } + .row-fluid .span9 { + width: 74.30939226519337%; + *width: 74.25620077583166%; + } + .row-fluid .span8 { + width: 65.74585635359117%; + *width: 65.69266486422946%; + } + .row-fluid .span7 { + width: 57.18232044198895%; + *width: 57.12912895262725%; + } + .row-fluid .span6 { + width: 48.61878453038674%; + *width: 48.56559304102504%; + } + .row-fluid .span5 { + width: 40.05524861878453%; + *width: 40.00205712942283%; + } + .row-fluid .span4 { + width: 31.491712707182323%; + *width: 31.43852121782062%; + } + .row-fluid .span3 { + width: 22.92817679558011%; + *width: 22.87498530621841%; + } + .row-fluid .span2 { + width: 14.3646408839779%; + *width: 14.311449394616199%; + } + .row-fluid .span1 { + width: 5.801104972375691%; + *width: 5.747913483013988%; + } + .row-fluid .offset12 { + margin-left: 105.52486187845304%; + *margin-left: 105.41847889972962%; + } + .row-fluid .offset12:first-child { + margin-left: 102.76243093922652%; + *margin-left: 102.6560479605031%; + } + .row-fluid .offset11 { + margin-left: 96.96132596685082%; + *margin-left: 96.8549429881274%; + } + .row-fluid .offset11:first-child { + margin-left: 94.1988950276243%; + *margin-left: 94.09251204890089%; + } + .row-fluid .offset10 { + margin-left: 88.39779005524862%; + *margin-left: 88.2914070765252%; + } + .row-fluid .offset10:first-child { + margin-left: 85.6353591160221%; + *margin-left: 85.52897613729868%; + } + .row-fluid .offset9 { + margin-left: 79.8342541436464%; + *margin-left: 79.72787116492299%; + } + .row-fluid .offset9:first-child { + margin-left: 77.07182320441989%; + *margin-left: 76.96544022569647%; + } + .row-fluid .offset8 { + margin-left: 71.2707182320442%; + *margin-left: 71.16433525332079%; + } + .row-fluid .offset8:first-child { + margin-left: 68.50828729281768%; + *margin-left: 68.40190431409427%; + } + .row-fluid .offset7 { + margin-left: 62.70718232044199%; + *margin-left: 62.600799341718584%; + } + .row-fluid .offset7:first-child { + margin-left: 59.94475138121547%; + *margin-left: 59.838368402492065%; + } + .row-fluid .offset6 { + margin-left: 54.14364640883978%; + *margin-left: 54.037263430116376%; + } + .row-fluid .offset6:first-child { + margin-left: 51.38121546961326%; + *margin-left: 51.27483249088986%; + } + .row-fluid .offset5 { + margin-left: 45.58011049723757%; + *margin-left: 45.47372751851417%; + } + .row-fluid .offset5:first-child { + margin-left: 42.81767955801105%; + *margin-left: 42.71129657928765%; + } + .row-fluid .offset4 { + margin-left: 37.01657458563536%; + *margin-left: 36.91019160691196%; + } + .row-fluid .offset4:first-child { + margin-left: 34.25414364640884%; + *margin-left: 34.14776066768544%; + } + .row-fluid .offset3 { + margin-left: 28.45303867403315%; + *margin-left: 28.346655695309746%; + } + .row-fluid .offset3:first-child { + margin-left: 25.69060773480663%; + *margin-left: 25.584224756083227%; + } + .row-fluid .offset2 { + margin-left: 19.88950276243094%; + *margin-left: 19.783119783707537%; + } + .row-fluid .offset2:first-child { + margin-left: 17.12707182320442%; + *margin-left: 17.02068884448102%; + } + .row-fluid .offset1 { + margin-left: 11.32596685082873%; + *margin-left: 11.219583872105325%; + } + .row-fluid .offset1:first-child { + margin-left: 8.56353591160221%; + *margin-left: 8.457152932878806%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 710px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 648px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 586px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 524px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 462px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 400px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 338px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 276px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 214px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 152px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 90px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 28px; + } +} + +@media (max-width: 767px) { + body { + padding-right: 20px; + padding-left: 20px; + } + .navbar-fixed-top, + .navbar-fixed-bottom, + .navbar-static-top { + margin-right: -20px; + margin-left: -20px; + } + .container-fluid { + padding: 0; + } + .dl-horizontal dt { + float: none; + width: auto; + clear: none; + text-align: left; + } + .dl-horizontal dd { + margin-left: 0; + } + .container { + width: auto; + } + .row-fluid { + width: 100%; + } + .row, + .thumbnails { + margin-left: 0; + } + .thumbnails > li { + float: none; + margin-left: 0; + } + [class*="span"], + .row-fluid [class*="span"] { + display: block; + float: none; + width: 100%; + margin-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .span12, + .row-fluid .span12 { + width: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .input-large, + .input-xlarge, + .input-xxlarge, + input[class*="span"], + select[class*="span"], + textarea[class*="span"], + .uneditable-input { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .input-prepend input, + .input-append input, + .input-prepend input[class*="span"], + .input-append input[class*="span"] { + display: inline-block; + width: auto; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 0; + } + .modal { + position: fixed; + top: 20px; + right: 20px; + left: 20px; + width: auto; + margin: 0; + } + .modal.fade.in { + top: auto; + } +} + +@media (max-width: 480px) { + .nav-collapse { + -webkit-transform: translate3d(0, 0, 0); + } + .page-header h1 small { + display: block; + line-height: 20px; + } + input[type="checkbox"], + input[type="radio"] { + border: 1px solid #ccc; + } + .form-horizontal .control-label { + float: none; + width: auto; + padding-top: 0; + text-align: left; + } + .form-horizontal .controls { + margin-left: 0; + } + .form-horizontal .control-list { + padding-top: 0; + } + .form-horizontal .form-actions { + padding-right: 10px; + padding-left: 10px; + } + .modal { + top: 10px; + right: 10px; + left: 10px; + } + .modal-header .close { + padding: 10px; + margin: -10px; + } + .carousel-caption { + position: static; + } +} + +@media (max-width: 979px) { + body { + padding-top: 0; + } + .navbar-fixed-top, + .navbar-fixed-bottom { + position: static; + } + .navbar-fixed-top { + margin-bottom: 20px; + } + .navbar-fixed-bottom { + margin-top: 20px; + } + .navbar-fixed-top .navbar-inner, + .navbar-fixed-bottom .navbar-inner { + padding: 5px; + } + .navbar .container { + width: auto; + padding: 0; + } + .navbar .brand { + padding-right: 10px; + padding-left: 10px; + margin: 0 0 0 -5px; + } + .nav-collapse { + clear: both; + } + .nav-collapse .nav { + float: none; + margin: 0 0 10px; + } + .nav-collapse .nav > li { + float: none; + } + .nav-collapse .nav > li > a { + margin-bottom: 2px; + } + .nav-collapse .nav > .divider-vertical { + display: none; + } + .nav-collapse .nav .nav-header { + color: #777777; + text-shadow: none; + } + .nav-collapse .nav > li > a, + .nav-collapse .dropdown-menu a { + padding: 9px 15px; + font-weight: bold; + color: #777777; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + } + .nav-collapse .btn { + padding: 4px 10px 4px; + font-weight: normal; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + } + .nav-collapse .dropdown-menu li + li a { + margin-bottom: 2px; + } + .nav-collapse .nav > li > a:hover, + .nav-collapse .dropdown-menu a:hover { + background-color: #f2f2f2; + } + .navbar-inverse .nav-collapse .nav > li > a:hover, + .navbar-inverse .nav-collapse .dropdown-menu a:hover { + background-color: #111111; + } + .nav-collapse.in .btn-group { + padding: 0; + margin-top: 5px; + } + .nav-collapse .dropdown-menu { + position: static; + top: auto; + left: auto; + display: block; + float: none; + max-width: none; + padding: 0; + margin: 0 15px; + background-color: transparent; + border: none; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + } + .nav-collapse .dropdown-menu:before, + .nav-collapse .dropdown-menu:after { + display: none; + } + .nav-collapse .dropdown-menu .divider { + display: none; + } + .nav-collapse .nav > li > .dropdown-menu:before, + .nav-collapse .nav > li > .dropdown-menu:after { + display: none; + } + .nav-collapse .navbar-form, + .nav-collapse .navbar-search { + float: none; + padding: 10px 15px; + margin: 10px 0; + border-top: 1px solid #f2f2f2; + border-bottom: 1px solid #f2f2f2; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + -moz-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); + } + .navbar-inverse .nav-collapse .navbar-form, + .navbar-inverse .nav-collapse .navbar-search { + border-top-color: #111111; + border-bottom-color: #111111; + } + .navbar .nav-collapse .nav.pull-right { + float: none; + margin-left: 0; + } + .nav-collapse, + .nav-collapse.collapse { + height: 0; + overflow: hidden; + } + .navbar .btn-navbar { + display: block; + } + .navbar-static .navbar-inner { + padding-right: 10px; + padding-left: 10px; + } +} + +@media (min-width: 980px) { + .nav-collapse.collapse { + height: auto !important; + overflow: visible !important; + } +} \ No newline at end of file diff --git a/css/bootstrap.css b/css/bootstrap.css new file mode 100644 index 000000000..a48bbbecf --- /dev/null +++ b/css/bootstrap.css @@ -0,0 +1,5774 @@ +/*! + * Bootstrap v2.1.1 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section { + display: block; +} + +audio, +canvas, +video { + display: inline-block; + *display: inline; + *zoom: 1; +} + +audio:not([controls]) { + display: none; +} + +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} + +a:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +a:hover, +a:active { + outline: 0; +} + +sub, +sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +img { + width: auto\9; + height: auto; + max-width: 100%; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; +} + +#map_canvas img { + max-width: none; +} + +button, +input, +select, +textarea { + margin: 0; + font-size: 100%; + vertical-align: middle; +} + +button, +input { + *overflow: visible; + line-height: normal; +} + +button::-moz-focus-inner, +input::-moz-focus-inner { + padding: 0; + border: 0; +} + +button, +input[type="button"], +input[type="reset"], +input[type="submit"] { + cursor: pointer; + -webkit-appearance: button; +} + +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-decoration, +input[type="search"]::-webkit-search-cancel-button { + -webkit-appearance: none; +} + +textarea { + overflow: auto; + vertical-align: top; +} + +.clearfix { + *zoom: 1; +} + +.clearfix:before, +.clearfix:after { + display: table; + line-height: 0; + content: ""; +} + +.clearfix:after { + clear: both; +} + +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} + +.input-block-level { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +body { + margin: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 20px; + color: #333333; + background-color: #ffffff; +} + +a { + color: #0088cc; + text-decoration: none; +} + +a:hover { + color: #005580; + text-decoration: underline; +} + +.img-rounded { + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.img-polaroid { + padding: 4px; + background-color: #fff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); +} + +.img-circle { + -webkit-border-radius: 500px; + -moz-border-radius: 500px; + border-radius: 500px; +} + +.row { + margin-left: -20px; + *zoom: 1; +} + +.row:before, +.row:after { + display: table; + line-height: 0; + content: ""; +} + +.row:after { + clear: both; +} + +[class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; +} + +.container, +.navbar-static-top .container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} + +.span12 { + width: 940px; +} + +.span11 { + width: 860px; +} + +.span10 { + width: 780px; +} + +.span9 { + width: 700px; +} + +.span8 { + width: 620px; +} + +.span7 { + width: 540px; +} + +.span6 { + width: 460px; +} + +.span5 { + width: 380px; +} + +.span4 { + width: 300px; +} + +.span3 { + width: 220px; +} + +.span2 { + width: 140px; +} + +.span1 { + width: 60px; +} + +.offset12 { + margin-left: 980px; +} + +.offset11 { + margin-left: 900px; +} + +.offset10 { + margin-left: 820px; +} + +.offset9 { + margin-left: 740px; +} + +.offset8 { + margin-left: 660px; +} + +.offset7 { + margin-left: 580px; +} + +.offset6 { + margin-left: 500px; +} + +.offset5 { + margin-left: 420px; +} + +.offset4 { + margin-left: 340px; +} + +.offset3 { + margin-left: 260px; +} + +.offset2 { + margin-left: 180px; +} + +.offset1 { + margin-left: 100px; +} + +.row-fluid { + width: 100%; + *zoom: 1; +} + +.row-fluid:before, +.row-fluid:after { + display: table; + line-height: 0; + content: ""; +} + +.row-fluid:after { + clear: both; +} + +.row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.127659574468085%; + *margin-left: 2.074468085106383%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.row-fluid [class*="span"]:first-child { + margin-left: 0; +} + +.row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; +} + +.row-fluid .span11 { + width: 91.48936170212765%; + *width: 91.43617021276594%; +} + +.row-fluid .span10 { + width: 82.97872340425532%; + *width: 82.92553191489361%; +} + +.row-fluid .span9 { + width: 74.46808510638297%; + *width: 74.41489361702126%; +} + +.row-fluid .span8 { + width: 65.95744680851064%; + *width: 65.90425531914893%; +} + +.row-fluid .span7 { + width: 57.44680851063829%; + *width: 57.39361702127659%; +} + +.row-fluid .span6 { + width: 48.93617021276595%; + *width: 48.88297872340425%; +} + +.row-fluid .span5 { + width: 40.42553191489362%; + *width: 40.37234042553192%; +} + +.row-fluid .span4 { + width: 31.914893617021278%; + *width: 31.861702127659576%; +} + +.row-fluid .span3 { + width: 23.404255319148934%; + *width: 23.351063829787233%; +} + +.row-fluid .span2 { + width: 14.893617021276595%; + *width: 14.840425531914894%; +} + +.row-fluid .span1 { + width: 6.382978723404255%; + *width: 6.329787234042553%; +} + +.row-fluid .offset12 { + margin-left: 104.25531914893617%; + *margin-left: 104.14893617021275%; +} + +.row-fluid .offset12:first-child { + margin-left: 102.12765957446808%; + *margin-left: 102.02127659574467%; +} + +.row-fluid .offset11 { + margin-left: 95.74468085106382%; + *margin-left: 95.6382978723404%; +} + +.row-fluid .offset11:first-child { + margin-left: 93.61702127659574%; + *margin-left: 93.51063829787232%; +} + +.row-fluid .offset10 { + margin-left: 87.23404255319149%; + *margin-left: 87.12765957446807%; +} + +.row-fluid .offset10:first-child { + margin-left: 85.1063829787234%; + *margin-left: 84.99999999999999%; +} + +.row-fluid .offset9 { + margin-left: 78.72340425531914%; + *margin-left: 78.61702127659572%; +} + +.row-fluid .offset9:first-child { + margin-left: 76.59574468085106%; + *margin-left: 76.48936170212764%; +} + +.row-fluid .offset8 { + margin-left: 70.2127659574468%; + *margin-left: 70.10638297872339%; +} + +.row-fluid .offset8:first-child { + margin-left: 68.08510638297872%; + *margin-left: 67.9787234042553%; +} + +.row-fluid .offset7 { + margin-left: 61.70212765957446%; + *margin-left: 61.59574468085106%; +} + +.row-fluid .offset7:first-child { + margin-left: 59.574468085106375%; + *margin-left: 59.46808510638297%; +} + +.row-fluid .offset6 { + margin-left: 53.191489361702125%; + *margin-left: 53.085106382978715%; +} + +.row-fluid .offset6:first-child { + margin-left: 51.063829787234035%; + *margin-left: 50.95744680851063%; +} + +.row-fluid .offset5 { + margin-left: 44.68085106382979%; + *margin-left: 44.57446808510638%; +} + +.row-fluid .offset5:first-child { + margin-left: 42.5531914893617%; + *margin-left: 42.4468085106383%; +} + +.row-fluid .offset4 { + margin-left: 36.170212765957444%; + *margin-left: 36.06382978723405%; +} + +.row-fluid .offset4:first-child { + margin-left: 34.04255319148936%; + *margin-left: 33.93617021276596%; +} + +.row-fluid .offset3 { + margin-left: 27.659574468085104%; + *margin-left: 27.5531914893617%; +} + +.row-fluid .offset3:first-child { + margin-left: 25.53191489361702%; + *margin-left: 25.425531914893618%; +} + +.row-fluid .offset2 { + margin-left: 19.148936170212764%; + *margin-left: 19.04255319148936%; +} + +.row-fluid .offset2:first-child { + margin-left: 17.02127659574468%; + *margin-left: 16.914893617021278%; +} + +.row-fluid .offset1 { + margin-left: 10.638297872340425%; + *margin-left: 10.53191489361702%; +} + +.row-fluid .offset1:first-child { + margin-left: 8.51063829787234%; + *margin-left: 8.404255319148938%; +} + +[class*="span"].hide, +.row-fluid [class*="span"].hide { + display: none; +} + +[class*="span"].pull-right, +.row-fluid [class*="span"].pull-right { + float: right; +} + +.container { + margin-right: auto; + margin-left: auto; + *zoom: 1; +} + +.container:before, +.container:after { + display: table; + line-height: 0; + content: ""; +} + +.container:after { + clear: both; +} + +.container-fluid { + padding-right: 20px; + padding-left: 20px; + *zoom: 1; +} + +.container-fluid:before, +.container-fluid:after { + display: table; + line-height: 0; + content: ""; +} + +.container-fluid:after { + clear: both; +} + +p { + margin: 0 0 10px; +} + +.lead { + margin-bottom: 20px; + font-size: 21px; + font-weight: 200; + line-height: 30px; +} + +small { + font-size: 85%; +} + +strong { + font-weight: bold; +} + +em { + font-style: italic; +} + +cite { + font-style: normal; +} + +.muted { + color: #999999; +} + +.text-warning { + color: #c09853; +} + +.text-error { + color: #b94a48; +} + +.text-info { + color: #3a87ad; +} + +.text-success { + color: #468847; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 10px 0; + font-family: inherit; + font-weight: bold; + line-height: 1; + color: inherit; + text-rendering: optimizelegibility; +} + +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small { + font-weight: normal; + line-height: 1; + color: #999999; +} + +h1 { + font-size: 36px; + line-height: 40px; +} + +h2 { + font-size: 30px; + line-height: 40px; +} + +h3 { + font-size: 24px; + line-height: 40px; +} + +h4 { + font-size: 18px; + line-height: 20px; +} + +h5 { + font-size: 14px; + line-height: 20px; +} + +h6 { + font-size: 12px; + line-height: 20px; +} + +h1 small { + font-size: 24px; +} + +h2 small { + font-size: 18px; +} + +h3 small { + font-size: 14px; +} + +h4 small { + font-size: 14px; +} + +.page-header { + padding-bottom: 9px; + margin: 20px 0 30px; + border-bottom: 1px solid #eeeeee; +} + +ul, +ol { + padding: 0; + margin: 0 0 10px 25px; +} + +ul ul, +ul ol, +ol ol, +ol ul { + margin-bottom: 0; +} + +li { + line-height: 20px; +} + +ul.unstyled, +ol.unstyled { + margin-left: 0; + list-style: none; +} + +dl { + margin-bottom: 20px; +} + +dt, +dd { + line-height: 20px; +} + +dt { + font-weight: bold; +} + +dd { + margin-left: 10px; +} + +.dl-horizontal { + *zoom: 1; +} + +.dl-horizontal:before, +.dl-horizontal:after { + display: table; + line-height: 0; + content: ""; +} + +.dl-horizontal:after { + clear: both; +} + +.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; +} + +hr { + margin: 20px 0; + border: 0; + border-top: 1px solid #eeeeee; + border-bottom: 1px solid #ffffff; +} + +abbr[title] { + cursor: help; + border-bottom: 1px dotted #999999; +} + +abbr.initialism { + font-size: 90%; + text-transform: uppercase; +} + +blockquote { + padding: 0 0 0 15px; + margin: 0 0 20px; + border-left: 5px solid #eeeeee; +} + +blockquote p { + margin-bottom: 0; + font-size: 16px; + font-weight: 300; + line-height: 25px; +} + +blockquote small { + display: block; + line-height: 20px; + color: #999999; +} + +blockquote small:before { + content: '\2014 \00A0'; +} + +blockquote.pull-right { + float: right; + padding-right: 15px; + padding-left: 0; + border-right: 5px solid #eeeeee; + border-left: 0; +} + +blockquote.pull-right p, +blockquote.pull-right small { + text-align: right; +} + +blockquote.pull-right small:before { + content: ''; +} + +blockquote.pull-right small:after { + content: '\00A0 \2014'; +} + +q:before, +q:after, +blockquote:before, +blockquote:after { + content: ""; +} + +address { + display: block; + margin-bottom: 20px; + font-style: normal; + line-height: 20px; +} + +code, +pre { + padding: 0 3px 2px; + font-family: Monaco, Menlo, Consolas, "Courier New", monospace; + font-size: 12px; + color: #333333; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +code { + padding: 2px 4px; + color: #d14; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; +} + +pre { + display: block; + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + line-height: 20px; + word-break: break-all; + word-wrap: break-word; + white-space: pre; + white-space: pre-wrap; + background-color: #f5f5f5; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +pre.prettyprint { + margin-bottom: 20px; +} + +pre code { + padding: 0; + color: inherit; + background-color: transparent; + border: 0; +} + +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; +} + +form { + margin: 0 0 20px; +} + +fieldset { + padding: 0; + margin: 0; + border: 0; +} + +legend { + display: block; + width: 100%; + padding: 0; + margin-bottom: 20px; + font-size: 21px; + line-height: 40px; + color: #333333; + border: 0; + border-bottom: 1px solid #e5e5e5; +} + +legend small { + font-size: 15px; + color: #999999; +} + +label, +input, +button, +select, +textarea { + font-size: 14px; + font-weight: normal; + line-height: 20px; +} + +input, +button, +select, +textarea { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +} + +label { + display: block; + margin-bottom: 5px; +} + +select, +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + display: inline-block; + height: 20px; + padding: 4px 6px; + margin-bottom: 9px; + font-size: 14px; + line-height: 20px; + color: #555555; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +input, +textarea, +.uneditable-input { + width: 206px; +} + +textarea { + height: auto; +} + +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + background-color: #ffffff; + border: 1px solid #cccccc; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-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 linear 0.2s, box-shadow linear 0.2s; + -moz-transition: border linear 0.2s, box-shadow linear 0.2s; + -o-transition: border linear 0.2s, box-shadow linear 0.2s; + transition: border linear 0.2s, box-shadow linear 0.2s; +} + +textarea:focus, +input[type="text"]:focus, +input[type="password"]:focus, +input[type="datetime"]:focus, +input[type="datetime-local"]:focus, +input[type="date"]:focus, +input[type="month"]:focus, +input[type="time"]:focus, +input[type="week"]:focus, +input[type="number"]:focus, +input[type="email"]:focus, +input[type="url"]:focus, +input[type="search"]:focus, +input[type="tel"]:focus, +input[type="color"]:focus, +.uneditable-input:focus { + border-color: rgba(82, 168, 236, 0.8); + outline: 0; + outline: thin dotted \9; + /* IE6-9 */ + + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); +} + +input[type="radio"], +input[type="checkbox"] { + margin: 4px 0 0; + margin-top: 1px \9; + *margin-top: 0; + line-height: normal; + cursor: pointer; +} + +input[type="file"], +input[type="image"], +input[type="submit"], +input[type="reset"], +input[type="button"], +input[type="radio"], +input[type="checkbox"] { + width: auto; +} + +select, +input[type="file"] { + height: 30px; + /* In IE7, the height of the select element cannot be changed by height, only font-size */ + + *margin-top: 4px; + /* For IE7, add top margin to align select with labels */ + + line-height: 30px; +} + +select { + width: 220px; + background-color: #ffffff; + border: 1px solid #cccccc; +} + +select[multiple], +select[size] { + height: auto; +} + +select:focus, +input[type="file"]:focus, +input[type="radio"]:focus, +input[type="checkbox"]:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +.uneditable-input, +.uneditable-textarea { + color: #999999; + cursor: not-allowed; + background-color: #fcfcfc; + border-color: #cccccc; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); +} + +.uneditable-input { + overflow: hidden; + white-space: nowrap; +} + +.uneditable-textarea { + width: auto; + height: auto; +} + +input:-moz-placeholder, +textarea:-moz-placeholder { + color: #999999; +} + +input:-ms-input-placeholder, +textarea:-ms-input-placeholder { + color: #999999; +} + +input::-webkit-input-placeholder, +textarea::-webkit-input-placeholder { + color: #999999; +} + +.radio, +.checkbox { + min-height: 18px; + padding-left: 18px; +} + +.radio input[type="radio"], +.checkbox input[type="checkbox"] { + float: left; + margin-left: -18px; +} + +.controls > .radio:first-child, +.controls > .checkbox:first-child { + padding-top: 5px; +} + +.radio.inline, +.checkbox.inline { + display: inline-block; + padding-top: 5px; + margin-bottom: 0; + vertical-align: middle; +} + +.radio.inline + .radio.inline, +.checkbox.inline + .checkbox.inline { + margin-left: 10px; +} + +.input-mini { + width: 60px; +} + +.input-small { + width: 90px; +} + +.input-medium { + width: 150px; +} + +.input-large { + width: 210px; +} + +.input-xlarge { + width: 270px; +} + +.input-xxlarge { + width: 530px; +} + +input[class*="span"], +select[class*="span"], +textarea[class*="span"], +.uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"] { + float: none; + margin-left: 0; +} + +.input-append input[class*="span"], +.input-append .uneditable-input[class*="span"], +.input-prepend input[class*="span"], +.input-prepend .uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"], +.row-fluid .input-prepend [class*="span"], +.row-fluid .input-append [class*="span"] { + display: inline-block; +} + +input, +textarea, +.uneditable-input { + margin-left: 0; +} + +.controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; +} + +input.span12, +textarea.span12, +.uneditable-input.span12 { + width: 926px; +} + +input.span11, +textarea.span11, +.uneditable-input.span11 { + width: 846px; +} + +input.span10, +textarea.span10, +.uneditable-input.span10 { + width: 766px; +} + +input.span9, +textarea.span9, +.uneditable-input.span9 { + width: 686px; +} + +input.span8, +textarea.span8, +.uneditable-input.span8 { + width: 606px; +} + +input.span7, +textarea.span7, +.uneditable-input.span7 { + width: 526px; +} + +input.span6, +textarea.span6, +.uneditable-input.span6 { + width: 446px; +} + +input.span5, +textarea.span5, +.uneditable-input.span5 { + width: 366px; +} + +input.span4, +textarea.span4, +.uneditable-input.span4 { + width: 286px; +} + +input.span3, +textarea.span3, +.uneditable-input.span3 { + width: 206px; +} + +input.span2, +textarea.span2, +.uneditable-input.span2 { + width: 126px; +} + +input.span1, +textarea.span1, +.uneditable-input.span1 { + width: 46px; +} + +.controls-row { + *zoom: 1; +} + +.controls-row:before, +.controls-row:after { + display: table; + line-height: 0; + content: ""; +} + +.controls-row:after { + clear: both; +} + +.controls-row [class*="span"] { + float: left; +} + +input[disabled], +select[disabled], +textarea[disabled], +input[readonly], +select[readonly], +textarea[readonly] { + cursor: not-allowed; + background-color: #eeeeee; +} + +input[type="radio"][disabled], +input[type="checkbox"][disabled], +input[type="radio"][readonly], +input[type="checkbox"][readonly] { + background-color: transparent; +} + +.control-group.warning > label, +.control-group.warning .help-block, +.control-group.warning .help-inline { + color: #c09853; +} + +.control-group.warning .checkbox, +.control-group.warning .radio, +.control-group.warning input, +.control-group.warning select, +.control-group.warning textarea { + color: #c09853; +} + +.control-group.warning input, +.control-group.warning select, +.control-group.warning textarea { + border-color: #c09853; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} + +.control-group.warning input:focus, +.control-group.warning select:focus, +.control-group.warning textarea:focus { + border-color: #a47e3c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + -moz-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; +} + +.control-group.warning .input-prepend .add-on, +.control-group.warning .input-append .add-on { + color: #c09853; + background-color: #fcf8e3; + border-color: #c09853; +} + +.control-group.error > label, +.control-group.error .help-block, +.control-group.error .help-inline { + color: #b94a48; +} + +.control-group.error .checkbox, +.control-group.error .radio, +.control-group.error input, +.control-group.error select, +.control-group.error textarea { + color: #b94a48; +} + +.control-group.error input, +.control-group.error select, +.control-group.error textarea { + border-color: #b94a48; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} + +.control-group.error input:focus, +.control-group.error select:focus, +.control-group.error textarea:focus { + border-color: #953b39; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + -moz-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; +} + +.control-group.error .input-prepend .add-on, +.control-group.error .input-append .add-on { + color: #b94a48; + background-color: #f2dede; + border-color: #b94a48; +} + +.control-group.success > label, +.control-group.success .help-block, +.control-group.success .help-inline { + color: #468847; +} + +.control-group.success .checkbox, +.control-group.success .radio, +.control-group.success input, +.control-group.success select, +.control-group.success textarea { + color: #468847; +} + +.control-group.success input, +.control-group.success select, +.control-group.success textarea { + border-color: #468847; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} + +.control-group.success input:focus, +.control-group.success select:focus, +.control-group.success textarea:focus { + border-color: #356635; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + -moz-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; +} + +.control-group.success .input-prepend .add-on, +.control-group.success .input-append .add-on { + color: #468847; + background-color: #dff0d8; + border-color: #468847; +} + +.control-group.info > label, +.control-group.info .help-block, +.control-group.info .help-inline { + color: #3a87ad; +} + +.control-group.info .checkbox, +.control-group.info .radio, +.control-group.info input, +.control-group.info select, +.control-group.info textarea { + color: #3a87ad; +} + +.control-group.info input, +.control-group.info select, +.control-group.info textarea { + border-color: #3a87ad; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} + +.control-group.info input:focus, +.control-group.info select:focus, +.control-group.info textarea:focus { + border-color: #2d6987; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; +} + +.control-group.info .input-prepend .add-on, +.control-group.info .input-append .add-on { + color: #3a87ad; + background-color: #d9edf7; + border-color: #3a87ad; +} + +input:focus:required:invalid, +textarea:focus:required:invalid, +select:focus:required:invalid { + color: #b94a48; + border-color: #ee5f5b; +} + +input:focus:required:invalid:focus, +textarea:focus:required:invalid:focus, +select:focus:required:invalid:focus { + border-color: #e9322d; + -webkit-box-shadow: 0 0 6px #f8b9b7; + -moz-box-shadow: 0 0 6px #f8b9b7; + box-shadow: 0 0 6px #f8b9b7; +} + +.form-actions { + padding: 19px 20px 20px; + margin-top: 20px; + margin-bottom: 20px; + background-color: #f5f5f5; + border-top: 1px solid #e5e5e5; + *zoom: 1; +} + +.form-actions:before, +.form-actions:after { + display: table; + line-height: 0; + content: ""; +} + +.form-actions:after { + clear: both; +} + +.help-block, +.help-inline { + color: #595959; +} + +.help-block { + display: block; + margin-bottom: 10px; +} + +.help-inline { + display: inline-block; + *display: inline; + padding-left: 5px; + vertical-align: middle; + *zoom: 1; +} + +.input-append, +.input-prepend { + margin-bottom: 5px; + font-size: 0; + white-space: nowrap; +} + +.input-append input, +.input-prepend input, +.input-append select, +.input-prepend select, +.input-append .uneditable-input, +.input-prepend .uneditable-input { + position: relative; + margin-bottom: 0; + *margin-left: 0; + font-size: 14px; + vertical-align: top; + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.input-append input:focus, +.input-prepend input:focus, +.input-append select:focus, +.input-prepend select:focus, +.input-append .uneditable-input:focus, +.input-prepend .uneditable-input:focus { + z-index: 2; +} + +.input-append .add-on, +.input-prepend .add-on { + display: inline-block; + width: auto; + height: 20px; + min-width: 16px; + padding: 4px 5px; + font-size: 14px; + font-weight: normal; + line-height: 20px; + text-align: center; + text-shadow: 0 1px 0 #ffffff; + background-color: #eeeeee; + border: 1px solid #ccc; +} + +.input-append .add-on, +.input-prepend .add-on, +.input-append .btn, +.input-prepend .btn { + vertical-align: top; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.input-append .active, +.input-prepend .active { + background-color: #a9dba9; + border-color: #46a546; +} + +.input-prepend .add-on, +.input-prepend .btn { + margin-right: -1px; +} + +.input-prepend .add-on:first-child, +.input-prepend .btn:first-child { + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-append input, +.input-append select, +.input-append .uneditable-input { + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-append .add-on, +.input-append .btn { + margin-left: -1px; +} + +.input-append .add-on:last-child, +.input-append .btn:last-child { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.input-prepend.input-append input, +.input-prepend.input-append select, +.input-prepend.input-append .uneditable-input { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.input-prepend.input-append .add-on:first-child, +.input-prepend.input-append .btn:first-child { + margin-right: -1px; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-prepend.input-append .add-on:last-child, +.input-prepend.input-append .btn:last-child { + margin-left: -1px; + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +input.search-query { + padding-right: 14px; + padding-right: 4px \9; + padding-left: 14px; + padding-left: 4px \9; + /* IE7-8 doesn't have border-radius, so don't indent the padding */ + + margin-bottom: 0; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} + +/* Allow for input prepend/append in search forms */ + +.form-search .input-append .search-query, +.form-search .input-prepend .search-query { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.form-search .input-append .search-query { + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; +} + +.form-search .input-append .btn { + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; +} + +.form-search .input-prepend .search-query { + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; +} + +.form-search .input-prepend .btn { + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; +} + +.form-search input, +.form-inline input, +.form-horizontal input, +.form-search textarea, +.form-inline textarea, +.form-horizontal textarea, +.form-search select, +.form-inline select, +.form-horizontal select, +.form-search .help-inline, +.form-inline .help-inline, +.form-horizontal .help-inline, +.form-search .uneditable-input, +.form-inline .uneditable-input, +.form-horizontal .uneditable-input, +.form-search .input-prepend, +.form-inline .input-prepend, +.form-horizontal .input-prepend, +.form-search .input-append, +.form-inline .input-append, +.form-horizontal .input-append { + display: inline-block; + *display: inline; + margin-bottom: 0; + vertical-align: middle; + *zoom: 1; +} + +.form-search .hide, +.form-inline .hide, +.form-horizontal .hide { + display: none; +} + +.form-search label, +.form-inline label, +.form-search .btn-group, +.form-inline .btn-group { + display: inline-block; +} + +.form-search .input-append, +.form-inline .input-append, +.form-search .input-prepend, +.form-inline .input-prepend { + margin-bottom: 0; +} + +.form-search .radio, +.form-search .checkbox, +.form-inline .radio, +.form-inline .checkbox { + padding-left: 0; + margin-bottom: 0; + vertical-align: middle; +} + +.form-search .radio input[type="radio"], +.form-search .checkbox input[type="checkbox"], +.form-inline .radio input[type="radio"], +.form-inline .checkbox input[type="checkbox"] { + float: left; + margin-right: 3px; + margin-left: 0; +} + +.control-group { + margin-bottom: 10px; +} + +legend + .control-group { + margin-top: 20px; + -webkit-margin-top-collapse: separate; +} + +.form-horizontal .control-group { + margin-bottom: 20px; + *zoom: 1; +} + +.form-horizontal .control-group:before, +.form-horizontal .control-group:after { + display: table; + line-height: 0; + content: ""; +} + +.form-horizontal .control-group:after { + clear: both; +} + +.form-horizontal .control-label { + float: left; + width: 160px; + padding-top: 5px; + text-align: right; +} + +.form-horizontal .controls { + *display: inline-block; + *padding-left: 20px; + margin-left: 180px; + *margin-left: 0; +} + +.form-horizontal .controls:first-child { + *padding-left: 180px; +} + +.form-horizontal .help-block { + margin-bottom: 0; +} + +.form-horizontal input + .help-block, +.form-horizontal select + .help-block, +.form-horizontal textarea + .help-block { + margin-top: 10px; +} + +.form-horizontal .form-actions { + padding-left: 180px; +} + +table { + max-width: 100%; + background-color: transparent; + border-collapse: collapse; + border-spacing: 0; +} + +.table { + width: 100%; + margin-bottom: 20px; +} + +.table th, +.table td { + padding: 8px; + line-height: 20px; + text-align: left; + vertical-align: top; + border-top: 1px solid #dddddd; +} + +.table th { + font-weight: bold; +} + +.table thead th { + vertical-align: bottom; +} + +.table caption + thead tr:first-child th, +.table caption + thead tr:first-child td, +.table colgroup + thead tr:first-child th, +.table colgroup + thead tr:first-child td, +.table thead:first-child tr:first-child th, +.table thead:first-child tr:first-child td { + border-top: 0; +} + +.table tbody + tbody { + border-top: 2px solid #dddddd; +} + +.table-condensed th, +.table-condensed td { + padding: 4px 5px; +} + +.table-bordered { + border: 1px solid #dddddd; + border-collapse: separate; + *border-collapse: collapse; + border-left: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.table-bordered th, +.table-bordered td { + border-left: 1px solid #dddddd; +} + +.table-bordered caption + thead tr:first-child th, +.table-bordered caption + tbody tr:first-child th, +.table-bordered caption + tbody tr:first-child td, +.table-bordered colgroup + thead tr:first-child th, +.table-bordered colgroup + tbody tr:first-child th, +.table-bordered colgroup + tbody tr:first-child td, +.table-bordered thead:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child td { + border-top: 0; +} + +.table-bordered thead:first-child tr:first-child th:first-child, +.table-bordered tbody:first-child tr:first-child td:first-child { + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; +} + +.table-bordered thead:first-child tr:first-child th:last-child, +.table-bordered tbody:first-child tr:first-child td:last-child { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; +} + +.table-bordered thead:last-child tr:last-child th:first-child, +.table-bordered tbody:last-child tr:last-child td:first-child, +.table-bordered tfoot:last-child tr:last-child td:first-child { + -webkit-border-radius: 0 0 0 4px; + -moz-border-radius: 0 0 0 4px; + border-radius: 0 0 0 4px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; +} + +.table-bordered thead:last-child tr:last-child th:last-child, +.table-bordered tbody:last-child tr:last-child td:last-child, +.table-bordered tfoot:last-child tr:last-child td:last-child { + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; +} + +.table-bordered caption + thead tr:first-child th:first-child, +.table-bordered caption + tbody tr:first-child td:first-child, +.table-bordered colgroup + thead tr:first-child th:first-child, +.table-bordered colgroup + tbody tr:first-child td:first-child { + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; +} + +.table-bordered caption + thead tr:first-child th:last-child, +.table-bordered caption + tbody tr:first-child td:last-child, +.table-bordered colgroup + thead tr:first-child th:last-child, +.table-bordered colgroup + tbody tr:first-child td:last-child { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-topleft: 4px; +} + +.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 [class*=span], +.row-fluid table [class*=span] { + display: table-cell; + float: none; + margin-left: 0; +} + +.table .span1 { + float: none; + width: 44px; + margin-left: 0; +} + +.table .span2 { + float: none; + width: 124px; + margin-left: 0; +} + +.table .span3 { + float: none; + width: 204px; + margin-left: 0; +} + +.table .span4 { + float: none; + width: 284px; + margin-left: 0; +} + +.table .span5 { + float: none; + width: 364px; + margin-left: 0; +} + +.table .span6 { + float: none; + width: 444px; + margin-left: 0; +} + +.table .span7 { + float: none; + width: 524px; + margin-left: 0; +} + +.table .span8 { + float: none; + width: 604px; + margin-left: 0; +} + +.table .span9 { + float: none; + width: 684px; + margin-left: 0; +} + +.table .span10 { + float: none; + width: 764px; + margin-left: 0; +} + +.table .span11 { + float: none; + width: 844px; + margin-left: 0; +} + +.table .span12 { + float: none; + width: 924px; + margin-left: 0; +} + +.table .span13 { + float: none; + width: 1004px; + margin-left: 0; +} + +.table .span14 { + float: none; + width: 1084px; + margin-left: 0; +} + +.table .span15 { + float: none; + width: 1164px; + margin-left: 0; +} + +.table .span16 { + float: none; + width: 1244px; + margin-left: 0; +} + +.table .span17 { + float: none; + width: 1324px; + margin-left: 0; +} + +.table .span18 { + float: none; + width: 1404px; + margin-left: 0; +} + +.table .span19 { + float: none; + width: 1484px; + margin-left: 0; +} + +.table .span20 { + float: none; + width: 1564px; + margin-left: 0; +} + +.table .span21 { + float: none; + width: 1644px; + margin-left: 0; +} + +.table .span22 { + float: none; + width: 1724px; + margin-left: 0; +} + +.table .span23 { + float: none; + width: 1804px; + margin-left: 0; +} + +.table .span24 { + float: none; + width: 1884px; + margin-left: 0; +} + +.table tbody tr.success td { + background-color: #dff0d8; +} + +.table tbody tr.error td { + background-color: #f2dede; +} + +.table tbody tr.warning td { + background-color: #fcf8e3; +} + +.table tbody tr.info td { + background-color: #d9edf7; +} + +.table-hover tbody tr.success:hover td { + background-color: #d0e9c6; +} + +.table-hover tbody tr.error:hover td { + background-color: #ebcccc; +} + +.table-hover tbody tr.warning:hover td { + background-color: #faf2cc; +} + +.table-hover tbody tr.info:hover td { + background-color: #c4e3f3; +} + +[class^="icon-"], +[class*=" icon-"] { + display: inline-block; + width: 14px; + height: 14px; + margin-top: 1px; + *margin-right: .3em; + line-height: 14px; + vertical-align: text-top; + background-image: url("../img/glyphicons-halflings.png"); + background-position: 14px 14px; + background-repeat: no-repeat; +} + +/* White icons with optional class, or on hover/active states of certain elements */ + +.icon-white, +.nav-tabs > .active > a > [class^="icon-"], +.nav-tabs > .active > a > [class*=" icon-"], +.nav-pills > .active > a > [class^="icon-"], +.nav-pills > .active > a > [class*=" icon-"], +.nav-list > .active > a > [class^="icon-"], +.nav-list > .active > a > [class*=" icon-"], +.navbar-inverse .nav > .active > a > [class^="icon-"], +.navbar-inverse .nav > .active > a > [class*=" icon-"], +.dropdown-menu > li > a:hover > [class^="icon-"], +.dropdown-menu > li > a:hover > [class*=" icon-"], +.dropdown-menu > .active > a > [class^="icon-"], +.dropdown-menu > .active > a > [class*=" icon-"] { + background-image: url("../img/glyphicons-halflings-white.png"); +} + +.icon-glass { + background-position: 0 0; +} + +.icon-music { + background-position: -24px 0; +} + +.icon-search { + background-position: -48px 0; +} + +.icon-envelope { + background-position: -72px 0; +} + +.icon-heart { + background-position: -96px 0; +} + +.icon-star { + background-position: -120px 0; +} + +.icon-star-empty { + background-position: -144px 0; +} + +.icon-user { + background-position: -168px 0; +} + +.icon-film { + background-position: -192px 0; +} + +.icon-th-large { + background-position: -216px 0; +} + +.icon-th { + background-position: -240px 0; +} + +.icon-th-list { + background-position: -264px 0; +} + +.icon-ok { + background-position: -288px 0; +} + +.icon-remove { + background-position: -312px 0; +} + +.icon-zoom-in { + background-position: -336px 0; +} + +.icon-zoom-out { + background-position: -360px 0; +} + +.icon-off { + background-position: -384px 0; +} + +.icon-signal { + background-position: -408px 0; +} + +.icon-cog { + background-position: -432px 0; +} + +.icon-trash { + background-position: -456px 0; +} + +.icon-home { + background-position: 0 -24px; +} + +.icon-file { + background-position: -24px -24px; +} + +.icon-time { + background-position: -48px -24px; +} + +.icon-road { + background-position: -72px -24px; +} + +.icon-download-alt { + background-position: -96px -24px; +} + +.icon-download { + background-position: -120px -24px; +} + +.icon-upload { + background-position: -144px -24px; +} + +.icon-inbox { + background-position: -168px -24px; +} + +.icon-play-circle { + background-position: -192px -24px; +} + +.icon-repeat { + background-position: -216px -24px; +} + +.icon-refresh { + background-position: -240px -24px; +} + +.icon-list-alt { + background-position: -264px -24px; +} + +.icon-lock { + background-position: -287px -24px; +} + +.icon-flag { + background-position: -312px -24px; +} + +.icon-headphones { + background-position: -336px -24px; +} + +.icon-volume-off { + background-position: -360px -24px; +} + +.icon-volume-down { + background-position: -384px -24px; +} + +.icon-volume-up { + background-position: -408px -24px; +} + +.icon-qrcode { + background-position: -432px -24px; +} + +.icon-barcode { + background-position: -456px -24px; +} + +.icon-tag { + background-position: 0 -48px; +} + +.icon-tags { + background-position: -25px -48px; +} + +.icon-book { + background-position: -48px -48px; +} + +.icon-bookmark { + background-position: -72px -48px; +} + +.icon-print { + background-position: -96px -48px; +} + +.icon-camera { + background-position: -120px -48px; +} + +.icon-font { + background-position: -144px -48px; +} + +.icon-bold { + background-position: -167px -48px; +} + +.icon-italic { + background-position: -192px -48px; +} + +.icon-text-height { + background-position: -216px -48px; +} + +.icon-text-width { + background-position: -240px -48px; +} + +.icon-align-left { + background-position: -264px -48px; +} + +.icon-align-center { + background-position: -288px -48px; +} + +.icon-align-right { + background-position: -312px -48px; +} + +.icon-align-justify { + background-position: -336px -48px; +} + +.icon-list { + background-position: -360px -48px; +} + +.icon-indent-left { + background-position: -384px -48px; +} + +.icon-indent-right { + background-position: -408px -48px; +} + +.icon-facetime-video { + background-position: -432px -48px; +} + +.icon-picture { + background-position: -456px -48px; +} + +.icon-pencil { + background-position: 0 -72px; +} + +.icon-map-marker { + background-position: -24px -72px; +} + +.icon-adjust { + background-position: -48px -72px; +} + +.icon-tint { + background-position: -72px -72px; +} + +.icon-edit { + background-position: -96px -72px; +} + +.icon-share { + background-position: -120px -72px; +} + +.icon-check { + background-position: -144px -72px; +} + +.icon-move { + background-position: -168px -72px; +} + +.icon-step-backward { + background-position: -192px -72px; +} + +.icon-fast-backward { + background-position: -216px -72px; +} + +.icon-backward { + background-position: -240px -72px; +} + +.icon-play { + background-position: -264px -72px; +} + +.icon-pause { + background-position: -288px -72px; +} + +.icon-stop { + background-position: -312px -72px; +} + +.icon-forward { + background-position: -336px -72px; +} + +.icon-fast-forward { + background-position: -360px -72px; +} + +.icon-step-forward { + background-position: -384px -72px; +} + +.icon-eject { + background-position: -408px -72px; +} + +.icon-chevron-left { + background-position: -432px -72px; +} + +.icon-chevron-right { + background-position: -456px -72px; +} + +.icon-plus-sign { + background-position: 0 -96px; +} + +.icon-minus-sign { + background-position: -24px -96px; +} + +.icon-remove-sign { + background-position: -48px -96px; +} + +.icon-ok-sign { + background-position: -72px -96px; +} + +.icon-question-sign { + background-position: -96px -96px; +} + +.icon-info-sign { + background-position: -120px -96px; +} + +.icon-screenshot { + background-position: -144px -96px; +} + +.icon-remove-circle { + background-position: -168px -96px; +} + +.icon-ok-circle { + background-position: -192px -96px; +} + +.icon-ban-circle { + background-position: -216px -96px; +} + +.icon-arrow-left { + background-position: -240px -96px; +} + +.icon-arrow-right { + background-position: -264px -96px; +} + +.icon-arrow-up { + background-position: -289px -96px; +} + +.icon-arrow-down { + background-position: -312px -96px; +} + +.icon-share-alt { + background-position: -336px -96px; +} + +.icon-resize-full { + background-position: -360px -96px; +} + +.icon-resize-small { + background-position: -384px -96px; +} + +.icon-plus { + background-position: -408px -96px; +} + +.icon-minus { + background-position: -433px -96px; +} + +.icon-asterisk { + background-position: -456px -96px; +} + +.icon-exclamation-sign { + background-position: 0 -120px; +} + +.icon-gift { + background-position: -24px -120px; +} + +.icon-leaf { + background-position: -48px -120px; +} + +.icon-fire { + background-position: -72px -120px; +} + +.icon-eye-open { + background-position: -96px -120px; +} + +.icon-eye-close { + background-position: -120px -120px; +} + +.icon-warning-sign { + background-position: -144px -120px; +} + +.icon-plane { + background-position: -168px -120px; +} + +.icon-calendar { + background-position: -192px -120px; +} + +.icon-random { + width: 16px; + background-position: -216px -120px; +} + +.icon-comment { + background-position: -240px -120px; +} + +.icon-magnet { + background-position: -264px -120px; +} + +.icon-chevron-up { + background-position: -288px -120px; +} + +.icon-chevron-down { + background-position: -313px -119px; +} + +.icon-retweet { + background-position: -336px -120px; +} + +.icon-shopping-cart { + background-position: -360px -120px; +} + +.icon-folder-close { + background-position: -384px -120px; +} + +.icon-folder-open { + width: 16px; + background-position: -408px -120px; +} + +.icon-resize-vertical { + background-position: -432px -119px; +} + +.icon-resize-horizontal { + background-position: -456px -118px; +} + +.icon-hdd { + background-position: 0 -144px; +} + +.icon-bullhorn { + background-position: -24px -144px; +} + +.icon-bell { + background-position: -48px -144px; +} + +.icon-certificate { + background-position: -72px -144px; +} + +.icon-thumbs-up { + background-position: -96px -144px; +} + +.icon-thumbs-down { + background-position: -120px -144px; +} + +.icon-hand-right { + background-position: -144px -144px; +} + +.icon-hand-left { + background-position: -168px -144px; +} + +.icon-hand-up { + background-position: -192px -144px; +} + +.icon-hand-down { + background-position: -216px -144px; +} + +.icon-circle-arrow-right { + background-position: -240px -144px; +} + +.icon-circle-arrow-left { + background-position: -264px -144px; +} + +.icon-circle-arrow-up { + background-position: -288px -144px; +} + +.icon-circle-arrow-down { + background-position: -312px -144px; +} + +.icon-globe { + background-position: -336px -144px; +} + +.icon-wrench { + background-position: -360px -144px; +} + +.icon-tasks { + background-position: -384px -144px; +} + +.icon-filter { + background-position: -408px -144px; +} + +.icon-briefcase { + background-position: -432px -144px; +} + +.icon-fullscreen { + background-position: -456px -144px; +} + +.dropup, +.dropdown { + position: relative; +} + +.dropdown-toggle { + *margin-bottom: -3px; +} + +.dropdown-toggle:active, +.open .dropdown-toggle { + outline: 0; +} + +.caret { + display: inline-block; + width: 0; + height: 0; + vertical-align: top; + border-top: 4px solid #000000; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; +} + +.dropdown .caret { + margin-top: 8px; + margin-left: 2px; +} + +.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; + list-style: none; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + *border-right-width: 2px; + *border-bottom-width: 2px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; +} + +.dropdown-menu.pull-right { + right: 0; + left: auto; +} + +.dropdown-menu .divider { + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} + +.dropdown-menu a { + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 20px; + color: #333333; + white-space: nowrap; +} + +.dropdown-menu li > a:hover, +.dropdown-menu li > a:focus, +.dropdown-submenu:hover > a { + color: #ffffff; + text-decoration: none; + background-color: #0088cc; + background-color: #0081c2; + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); +} + +.dropdown-menu .active > a, +.dropdown-menu .active > a:hover { + color: #ffffff; + text-decoration: none; + background-color: #0088cc; + background-color: #0081c2; + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-repeat: repeat-x; + outline: 0; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); +} + +.dropdown-menu .disabled > a, +.dropdown-menu .disabled > a:hover { + color: #999999; +} + +.dropdown-menu .disabled > a:hover { + text-decoration: none; + cursor: default; + background-color: transparent; +} + +.open { + *z-index: 1000; +} + +.open > .dropdown-menu { + display: block; +} + +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} + +.dropup .caret, +.navbar-fixed-bottom .dropdown .caret { + border-top: 0; + border-bottom: 4px solid #000000; + content: ""; +} + +.dropup .dropdown-menu, +.navbar-fixed-bottom .dropdown .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 1px; +} + +.dropdown-submenu { + position: relative; +} + +.dropdown-submenu > .dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px 6px; + border-radius: 0 6px 6px 6px; +} + +.dropdown-submenu:hover > .dropdown-menu { + display: block; +} + +.dropdown-submenu > a:after { + display: block; + float: right; + width: 0; + height: 0; + margin-top: 5px; + margin-right: -10px; + border-color: transparent; + border-left-color: #cccccc; + border-style: solid; + border-width: 5px 0 5px 5px; + content: " "; +} + +.dropdown-submenu:hover > a:after { + border-left-color: #ffffff; +} + +.dropdown .dropdown-menu .nav-header { + padding-right: 20px; + padding-left: 20px; +} + +.typeahead { + margin-top: 2px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.well { + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #e3e3e3; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + -moz-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-large { + padding: 24px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.well-small { + padding: 9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +.fade { + opacity: 0; + -webkit-transition: opacity 0.15s linear; + -moz-transition: opacity 0.15s linear; + -o-transition: opacity 0.15s linear; + transition: opacity 0.15s linear; +} + +.fade.in { + opacity: 1; +} + +.collapse { + position: relative; + height: 0; + overflow: hidden; + -webkit-transition: height 0.35s ease; + -moz-transition: height 0.35s ease; + -o-transition: height 0.35s ease; + transition: height 0.35s ease; +} + +.collapse.in { + height: auto; +} + +.close { + float: right; + font-size: 20px; + font-weight: bold; + line-height: 20px; + color: #000000; + text-shadow: 0 1px 0 #ffffff; + opacity: 0.2; + filter: alpha(opacity=20); +} + +.close:hover { + color: #000000; + text-decoration: none; + cursor: pointer; + opacity: 0.4; + filter: alpha(opacity=40); +} + +button.close { + padding: 0; + cursor: pointer; + background: transparent; + border: 0; + -webkit-appearance: none; +} + +.btn { + display: inline-block; + *display: inline; + padding: 4px 14px; + margin-bottom: 0; + *margin-left: .3em; + font-size: 14px; + line-height: 20px; + *line-height: 20px; + color: #333333; + text-align: center; + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); + vertical-align: middle; + cursor: pointer; + background-color: #f5f5f5; + *background-color: #e6e6e6; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); + background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); + background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); + background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); + background-repeat: repeat-x; + border: 1px solid #bbbbbb; + *border: 0; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + border-color: #e6e6e6 #e6e6e6 #bfbfbf; + border-bottom-color: #a2a2a2; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn:hover, +.btn:active, +.btn.active, +.btn.disabled, +.btn[disabled] { + color: #333333; + background-color: #e6e6e6; + *background-color: #d9d9d9; +} + +.btn:active, +.btn.active { + background-color: #cccccc \9; +} + +.btn:first-child { + *margin-left: 0; +} + +.btn:hover { + color: #333333; + text-decoration: none; + background-color: #e6e6e6; + *background-color: #d9d9d9; + /* Buttons in IE7 don't get borders, so darken on hover */ + + background-position: 0 -15px; + -webkit-transition: background-position 0.1s linear; + -moz-transition: background-position 0.1s linear; + -o-transition: background-position 0.1s linear; + transition: background-position 0.1s linear; +} + +.btn:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +.btn.active, +.btn:active { + background-color: #e6e6e6; + background-color: #d9d9d9 \9; + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn.disabled, +.btn[disabled] { + cursor: default; + background-color: #e6e6e6; + background-image: none; + opacity: 0.65; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} + +.btn-large { + padding: 9px 14px; + font-size: 16px; + line-height: normal; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +.btn-large [class^="icon-"] { + margin-top: 2px; +} + +.btn-small { + padding: 3px 9px; + font-size: 12px; + line-height: 18px; +} + +.btn-small [class^="icon-"] { + margin-top: 0; +} + +.btn-mini { + padding: 2px 6px; + font-size: 11px; + line-height: 17px; +} + +.btn-block { + display: block; + width: 100%; + padding-right: 0; + padding-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.btn-block + .btn-block { + margin-top: 5px; +} + +input[type="submit"].btn-block, +input[type="reset"].btn-block, +input[type="button"].btn-block { + width: 100%; +} + +.btn-primary.active, +.btn-warning.active, +.btn-danger.active, +.btn-success.active, +.btn-info.active, +.btn-inverse.active { + color: rgba(255, 255, 255, 0.75); +} + +.btn { + border-color: #c5c5c5; + border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); +} + +.btn-primary { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #006dcc; + *background-color: #0044cc; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); + background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); + background-image: -o-linear-gradient(top, #0088cc, #0044cc); + background-image: linear-gradient(to bottom, #0088cc, #0044cc); + background-image: -moz-linear-gradient(top, #0088cc, #0044cc); + background-repeat: repeat-x; + border-color: #0044cc #0044cc #002a80; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-primary:hover, +.btn-primary:active, +.btn-primary.active, +.btn-primary.disabled, +.btn-primary[disabled] { + color: #ffffff; + background-color: #0044cc; + *background-color: #003bb3; +} + +.btn-primary:active, +.btn-primary.active { + background-color: #003399 \9; +} + +.btn-warning { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #faa732; + *background-color: #f89406; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-repeat: repeat-x; + border-color: #f89406 #f89406 #ad6704; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-warning:hover, +.btn-warning:active, +.btn-warning.active, +.btn-warning.disabled, +.btn-warning[disabled] { + color: #ffffff; + background-color: #f89406; + *background-color: #df8505; +} + +.btn-warning:active, +.btn-warning.active { + background-color: #c67605 \9; +} + +.btn-danger { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #da4f49; + *background-color: #bd362f; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); + background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); + background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); + background-repeat: repeat-x; + border-color: #bd362f #bd362f #802420; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-danger:hover, +.btn-danger:active, +.btn-danger.active, +.btn-danger.disabled, +.btn-danger[disabled] { + color: #ffffff; + background-color: #bd362f; + *background-color: #a9302a; +} + +.btn-danger:active, +.btn-danger.active { + background-color: #942a25 \9; +} + +.btn-success { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #5bb75b; + *background-color: #51a351; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); + background-image: -webkit-linear-gradient(top, #62c462, #51a351); + background-image: -o-linear-gradient(top, #62c462, #51a351); + background-image: linear-gradient(to bottom, #62c462, #51a351); + background-image: -moz-linear-gradient(top, #62c462, #51a351); + background-repeat: repeat-x; + border-color: #51a351 #51a351 #387038; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-success:hover, +.btn-success:active, +.btn-success.active, +.btn-success.disabled, +.btn-success[disabled] { + color: #ffffff; + background-color: #51a351; + *background-color: #499249; +} + +.btn-success:active, +.btn-success.active { + background-color: #408140 \9; +} + +.btn-info { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #49afcd; + *background-color: #2f96b4; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-repeat: repeat-x; + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-info:hover, +.btn-info:active, +.btn-info.active, +.btn-info.disabled, +.btn-info[disabled] { + color: #ffffff; + background-color: #2f96b4; + *background-color: #2a85a0; +} + +.btn-info:active, +.btn-info.active { + background-color: #24748c \9; +} + +.btn-inverse { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #363636; + *background-color: #222222; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); + background-image: -webkit-linear-gradient(top, #444444, #222222); + background-image: -o-linear-gradient(top, #444444, #222222); + background-image: linear-gradient(to bottom, #444444, #222222); + background-image: -moz-linear-gradient(top, #444444, #222222); + background-repeat: repeat-x; + border-color: #222222 #222222 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-inverse:hover, +.btn-inverse:active, +.btn-inverse.active, +.btn-inverse.disabled, +.btn-inverse[disabled] { + color: #ffffff; + background-color: #222222; + *background-color: #151515; +} + +.btn-inverse:active, +.btn-inverse.active { + background-color: #080808 \9; +} + +button.btn, +input[type="submit"].btn { + *padding-top: 3px; + *padding-bottom: 3px; +} + +button.btn::-moz-focus-inner, +input[type="submit"].btn::-moz-focus-inner { + padding: 0; + border: 0; +} + +button.btn.btn-large, +input[type="submit"].btn.btn-large { + *padding-top: 7px; + *padding-bottom: 7px; +} + +button.btn.btn-small, +input[type="submit"].btn.btn-small { + *padding-top: 3px; + *padding-bottom: 3px; +} + +button.btn.btn-mini, +input[type="submit"].btn.btn-mini { + *padding-top: 1px; + *padding-bottom: 1px; +} + +.btn-link, +.btn-link:active, +.btn-link[disabled] { + background-color: transparent; + background-image: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} + +.btn-link { + color: #0088cc; + cursor: pointer; + border-color: transparent; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.btn-link:hover { + color: #005580; + text-decoration: underline; + background-color: transparent; +} + +.btn-link[disabled]:hover { + color: #333333; + text-decoration: none; +} + +.btn-group { + position: relative; + *margin-left: .3em; + font-size: 0; + white-space: nowrap; + vertical-align: middle; +} + +.btn-group:first-child { + *margin-left: 0; +} + +.btn-group + .btn-group { + margin-left: 5px; +} + +.btn-toolbar { + margin-top: 10px; + margin-bottom: 10px; + font-size: 0; +} + +.btn-toolbar .btn-group { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; +} + +.btn-toolbar .btn + .btn, +.btn-toolbar .btn-group + .btn, +.btn-toolbar .btn + .btn-group { + margin-left: 5px; +} + +.btn-group > .btn { + position: relative; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.btn-group > .btn + .btn { + margin-left: -1px; +} + +.btn-group > .btn, +.btn-group > .dropdown-menu { + font-size: 14px; +} + +.btn-group > .btn-mini { + font-size: 11px; +} + +.btn-group > .btn-small { + font-size: 12px; +} + +.btn-group > .btn-large { + font-size: 16px; +} + +.btn-group > .btn:first-child { + margin-left: 0; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + -moz-border-radius-topleft: 4px; +} + +.btn-group > .btn:last-child, +.btn-group > .dropdown-toggle { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; +} + +.btn-group > .btn.large:first-child { + margin-left: 0; + -webkit-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + -moz-border-radius-topleft: 6px; +} + +.btn-group > .btn.large:last-child, +.btn-group > .large.dropdown-toggle { + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + -moz-border-radius-topright: 6px; + -moz-border-radius-bottomright: 6px; +} + +.btn-group > .btn:hover, +.btn-group > .btn:focus, +.btn-group > .btn:active, +.btn-group > .btn.active { + z-index: 2; +} + +.btn-group .dropdown-toggle:active, +.btn-group.open .dropdown-toggle { + outline: 0; +} + +.btn-group > .btn + .dropdown-toggle { + *padding-top: 5px; + padding-right: 8px; + *padding-bottom: 5px; + padding-left: 8px; + -webkit-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn-group > .btn-mini + .dropdown-toggle { + *padding-top: 2px; + padding-right: 5px; + *padding-bottom: 2px; + padding-left: 5px; +} + +.btn-group > .btn-small + .dropdown-toggle { + *padding-top: 5px; + *padding-bottom: 4px; +} + +.btn-group > .btn-large + .dropdown-toggle { + *padding-top: 7px; + padding-right: 12px; + *padding-bottom: 7px; + padding-left: 12px; +} + +.btn-group.open .dropdown-toggle { + background-image: none; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn-group.open .btn.dropdown-toggle { + background-color: #e6e6e6; +} + +.btn-group.open .btn-primary.dropdown-toggle { + background-color: #0044cc; +} + +.btn-group.open .btn-warning.dropdown-toggle { + background-color: #f89406; +} + +.btn-group.open .btn-danger.dropdown-toggle { + background-color: #bd362f; +} + +.btn-group.open .btn-success.dropdown-toggle { + background-color: #51a351; +} + +.btn-group.open .btn-info.dropdown-toggle { + background-color: #2f96b4; +} + +.btn-group.open .btn-inverse.dropdown-toggle { + background-color: #222222; +} + +.btn .caret { + margin-top: 8px; + margin-left: 0; +} + +.btn-mini .caret, +.btn-small .caret, +.btn-large .caret { + margin-top: 6px; +} + +.btn-large .caret { + border-top-width: 5px; + border-right-width: 5px; + border-left-width: 5px; +} + +.dropup .btn-large .caret { + border-top: 0; + border-bottom: 5px solid #000000; +} + +.btn-primary .caret, +.btn-warning .caret, +.btn-danger .caret, +.btn-info .caret, +.btn-success .caret, +.btn-inverse .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} + +.btn-group-vertical { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; +} + +.btn-group-vertical .btn { + display: block; + float: none; + width: 100%; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.btn-group-vertical .btn + .btn { + margin-top: -1px; + margin-left: 0; +} + +.btn-group-vertical .btn:first-child { + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} + +.btn-group-vertical .btn:last-child { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} + +.btn-group-vertical .btn-large:first-child { + -webkit-border-radius: 6px 6px 0 0; + -moz-border-radius: 6px 6px 0 0; + border-radius: 6px 6px 0 0; +} + +.btn-group-vertical .btn-large:last-child { + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; +} + +.alert { + padding: 8px 35px 8px 14px; + margin-bottom: 20px; + color: #c09853; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + background-color: #fcf8e3; + border: 1px solid #fbeed5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.alert h4 { + margin: 0; +} + +.alert .close { + position: relative; + top: -2px; + right: -21px; + line-height: 20px; +} + +.alert-success { + color: #468847; + background-color: #dff0d8; + border-color: #d6e9c6; +} + +.alert-danger, +.alert-error { + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; +} + +.alert-info { + color: #3a87ad; + background-color: #d9edf7; + border-color: #bce8f1; +} + +.alert-block { + padding-top: 14px; + padding-bottom: 14px; +} + +.alert-block > p, +.alert-block > ul { + margin-bottom: 0; +} + +.alert-block p + p { + margin-top: 5px; +} + +.nav { + margin-bottom: 20px; + margin-left: 0; + list-style: none; +} + +.nav > li > a { + display: block; +} + +.nav > li > a:hover { + text-decoration: none; + background-color: #eeeeee; +} + +.nav > .pull-right { + float: right; +} + +.nav-header { + display: block; + padding: 3px 15px; + font-size: 11px; + font-weight: bold; + line-height: 20px; + color: #999999; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-transform: uppercase; +} + +.nav li + .nav-header { + margin-top: 9px; +} + +.nav-list { + padding-right: 15px; + padding-left: 15px; + margin-bottom: 0; +} + +.nav-list > li > a, +.nav-list .nav-header { + margin-right: -15px; + margin-left: -15px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); +} + +.nav-list > li > a { + padding: 3px 15px; +} + +.nav-list > .active > a, +.nav-list > .active > a:hover { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); + background-color: #0088cc; +} + +.nav-list [class^="icon-"] { + margin-right: 2px; +} + +.nav-list .divider { + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} + +.nav-tabs, +.nav-pills { + *zoom: 1; +} + +.nav-tabs:before, +.nav-pills:before, +.nav-tabs:after, +.nav-pills:after { + display: table; + line-height: 0; + content: ""; +} + +.nav-tabs:after, +.nav-pills:after { + clear: both; +} + +.nav-tabs > li, +.nav-pills > li { + float: left; +} + +.nav-tabs > li > a, +.nav-pills > li > a { + padding-right: 12px; + padding-left: 12px; + margin-right: 2px; + line-height: 14px; +} + +.nav-tabs { + border-bottom: 1px solid #ddd; +} + +.nav-tabs > li { + margin-bottom: -1px; +} + +.nav-tabs > li > a { + padding-top: 8px; + padding-bottom: 8px; + line-height: 20px; + border: 1px solid transparent; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} + +.nav-tabs > li > a:hover { + border-color: #eeeeee #eeeeee #dddddd; +} + +.nav-tabs > .active > a, +.nav-tabs > .active > a:hover { + color: #555555; + cursor: default; + background-color: #ffffff; + border: 1px solid #ddd; + border-bottom-color: transparent; +} + +.nav-pills > li > a { + padding-top: 8px; + padding-bottom: 8px; + margin-top: 2px; + margin-bottom: 2px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +.nav-pills > .active > a, +.nav-pills > .active > a:hover { + color: #ffffff; + background-color: #0088cc; +} + +.nav-stacked > li { + float: none; +} + +.nav-stacked > li > a { + margin-right: 0; +} + +.nav-tabs.nav-stacked { + border-bottom: 0; +} + +.nav-tabs.nav-stacked > li > a { + border: 1px solid #ddd; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.nav-tabs.nav-stacked > li:first-child > a { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-topleft: 4px; +} + +.nav-tabs.nav-stacked > li:last-child > a { + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -moz-border-radius-bottomright: 4px; + -moz-border-radius-bottomleft: 4px; +} + +.nav-tabs.nav-stacked > li > a:hover { + z-index: 2; + border-color: #ddd; +} + +.nav-pills.nav-stacked > li > a { + margin-bottom: 3px; +} + +.nav-pills.nav-stacked > li:last-child > a { + margin-bottom: 1px; +} + +.nav-tabs .dropdown-menu { + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; +} + +.nav-pills .dropdown-menu { + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.nav .dropdown-toggle .caret { + margin-top: 6px; + border-top-color: #0088cc; + border-bottom-color: #0088cc; +} + +.nav .dropdown-toggle:hover .caret { + border-top-color: #005580; + border-bottom-color: #005580; +} + +/* move down carets for tabs */ + +.nav-tabs .dropdown-toggle .caret { + margin-top: 8px; +} + +.nav .active .dropdown-toggle .caret { + border-top-color: #fff; + border-bottom-color: #fff; +} + +.nav-tabs .active .dropdown-toggle .caret { + border-top-color: #555555; + border-bottom-color: #555555; +} + +.nav > .dropdown.active > a:hover { + cursor: pointer; +} + +.nav-tabs .open .dropdown-toggle, +.nav-pills .open .dropdown-toggle, +.nav > li.dropdown.open.active > a:hover { + color: #ffffff; + background-color: #999999; + border-color: #999999; +} + +.nav li.dropdown.open .caret, +.nav li.dropdown.open.active .caret, +.nav li.dropdown.open a:hover .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; + opacity: 1; + filter: alpha(opacity=100); +} + +.tabs-stacked .open > a:hover { + border-color: #999999; +} + +.tabbable { + *zoom: 1; +} + +.tabbable:before, +.tabbable:after { + display: table; + line-height: 0; + content: ""; +} + +.tabbable:after { + clear: both; +} + +.tab-content { + overflow: auto; +} + +.tabs-below > .nav-tabs, +.tabs-right > .nav-tabs, +.tabs-left > .nav-tabs { + border-bottom: 0; +} + +.tab-content > .tab-pane, +.pill-content > .pill-pane { + display: none; +} + +.tab-content > .active, +.pill-content > .active { + display: block; +} + +.tabs-below > .nav-tabs { + border-top: 1px solid #ddd; +} + +.tabs-below > .nav-tabs > li { + margin-top: -1px; + margin-bottom: 0; +} + +.tabs-below > .nav-tabs > li > a { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} + +.tabs-below > .nav-tabs > li > a:hover { + border-top-color: #ddd; + border-bottom-color: transparent; +} + +.tabs-below > .nav-tabs > .active > a, +.tabs-below > .nav-tabs > .active > a:hover { + border-color: transparent #ddd #ddd #ddd; +} + +.tabs-left > .nav-tabs > li, +.tabs-right > .nav-tabs > li { + float: none; +} + +.tabs-left > .nav-tabs > li > a, +.tabs-right > .nav-tabs > li > a { + min-width: 74px; + margin-right: 0; + margin-bottom: 3px; +} + +.tabs-left > .nav-tabs { + float: left; + margin-right: 19px; + border-right: 1px solid #ddd; +} + +.tabs-left > .nav-tabs > li > a { + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} + +.tabs-left > .nav-tabs > li > a:hover { + border-color: #eeeeee #dddddd #eeeeee #eeeeee; +} + +.tabs-left > .nav-tabs .active > a, +.tabs-left > .nav-tabs .active > a:hover { + border-color: #ddd transparent #ddd #ddd; + *border-right-color: #ffffff; +} + +.tabs-right > .nav-tabs { + float: right; + margin-left: 19px; + border-left: 1px solid #ddd; +} + +.tabs-right > .nav-tabs > li > a { + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} + +.tabs-right > .nav-tabs > li > a:hover { + border-color: #eeeeee #eeeeee #eeeeee #dddddd; +} + +.tabs-right > .nav-tabs .active > a, +.tabs-right > .nav-tabs .active > a:hover { + border-color: #ddd #ddd #ddd transparent; + *border-left-color: #ffffff; +} + +.nav > .disabled > a { + color: #999999; +} + +.nav > .disabled > a:hover { + text-decoration: none; + cursor: default; + background-color: transparent; +} + +.navbar { + *position: relative; + *z-index: 2; + margin-bottom: 20px; + overflow: visible; + color: #777777; +} + +.navbar-inner { + min-height: 40px; + padding-right: 20px; + padding-left: 20px; + background-color: #fafafa; + background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); + background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); + background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); + background-repeat: repeat-x; + border: 1px solid #d4d4d4; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); + *zoom: 1; + -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); +} + +.navbar-inner:before, +.navbar-inner:after { + display: table; + line-height: 0; + content: ""; +} + +.navbar-inner:after { + clear: both; +} + +.navbar .container { + width: auto; +} + +.nav-collapse.collapse { + height: auto; +} + +.navbar .brand { + display: block; + float: left; + padding: 10px 20px 10px; + margin-left: -20px; + font-size: 20px; + font-weight: 200; + color: #777777; + text-shadow: 0 1px 0 #ffffff; +} + +.navbar .brand:hover { + text-decoration: none; +} + +.navbar-text { + margin-bottom: 0; + line-height: 40px; +} + +.navbar-link { + color: #777777; +} + +.navbar-link:hover { + color: #333333; +} + +.navbar .divider-vertical { + height: 40px; + margin: 0 9px; + border-right: 1px solid #ffffff; + border-left: 1px solid #f2f2f2; +} + +.navbar .btn, +.navbar .btn-group { + margin-top: 5px; +} + +.navbar .btn-group .btn, +.navbar .input-prepend .btn, +.navbar .input-append .btn { + margin-top: 0; +} + +.navbar-form { + margin-bottom: 0; + *zoom: 1; +} + +.navbar-form:before, +.navbar-form:after { + display: table; + line-height: 0; + content: ""; +} + +.navbar-form:after { + clear: both; +} + +.navbar-form input, +.navbar-form select, +.navbar-form .radio, +.navbar-form .checkbox { + margin-top: 5px; +} + +.navbar-form input, +.navbar-form select, +.navbar-form .btn { + display: inline-block; + margin-bottom: 0; +} + +.navbar-form input[type="image"], +.navbar-form input[type="checkbox"], +.navbar-form input[type="radio"] { + margin-top: 3px; +} + +.navbar-form .input-append, +.navbar-form .input-prepend { + margin-top: 6px; + white-space: nowrap; +} + +.navbar-form .input-append input, +.navbar-form .input-prepend input { + margin-top: 0; +} + +.navbar-search { + position: relative; + float: left; + margin-top: 5px; + margin-bottom: 0; +} + +.navbar-search .search-query { + padding: 4px 14px; + margin-bottom: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: 1; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} + +.navbar-static-top { + position: static; + width: 100%; + margin-bottom: 0; +} + +.navbar-static-top .navbar-inner { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.navbar-fixed-top, +.navbar-fixed-bottom { + position: fixed; + right: 0; + left: 0; + z-index: 1030; + margin-bottom: 0; +} + +.navbar-fixed-top .navbar-inner, +.navbar-static-top .navbar-inner { + border-width: 0 0 1px; +} + +.navbar-fixed-bottom .navbar-inner { + border-width: 1px 0 0; +} + +.navbar-fixed-top .navbar-inner, +.navbar-fixed-bottom .navbar-inner { + padding-right: 0; + padding-left: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.navbar-static-top .container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} + +.navbar-fixed-top { + top: 0; +} + +.navbar-fixed-top .navbar-inner, +.navbar-static-top .navbar-inner { + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1); +} + +.navbar-fixed-bottom { + bottom: 0; +} + +.navbar-fixed-bottom .navbar-inner { + -webkit-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1); +} + +.navbar .nav { + position: relative; + left: 0; + display: block; + float: left; + margin: 0 10px 0 0; +} + +.navbar .nav.pull-right { + float: right; + margin-right: 0; +} + +.navbar .nav > li { + float: left; +} + +.navbar .nav > li > a { + float: none; + padding: 10px 15px 10px; + color: #777777; + text-decoration: none; + text-shadow: 0 1px 0 #ffffff; +} + +.navbar .nav .dropdown-toggle .caret { + margin-top: 8px; +} + +.navbar .nav > li > a:focus, +.navbar .nav > li > a:hover { + color: #333333; + text-decoration: none; + background-color: transparent; +} + +.navbar .nav > .active > a, +.navbar .nav > .active > a:hover, +.navbar .nav > .active > a:focus { + color: #555555; + text-decoration: none; + background-color: #e5e5e5; + -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); +} + +.navbar .btn-navbar { + display: none; + float: right; + padding: 7px 10px; + margin-right: 5px; + margin-left: 5px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #ededed; + *background-color: #e5e5e5; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); + background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); + background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); + background-repeat: repeat-x; + border-color: #e5e5e5 #e5e5e5 #bfbfbf; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); +} + +.navbar .btn-navbar:hover, +.navbar .btn-navbar:active, +.navbar .btn-navbar.active, +.navbar .btn-navbar.disabled, +.navbar .btn-navbar[disabled] { + color: #ffffff; + background-color: #e5e5e5; + *background-color: #d9d9d9; +} + +.navbar .btn-navbar:active, +.navbar .btn-navbar.active { + background-color: #cccccc \9; +} + +.navbar .btn-navbar .icon-bar { + display: block; + width: 18px; + height: 2px; + background-color: #f5f5f5; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); +} + +.btn-navbar .icon-bar + .icon-bar { + margin-top: 3px; +} + +.navbar .nav > li > .dropdown-menu:before { + position: absolute; + top: -7px; + left: 9px; + display: inline-block; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-left: 7px solid transparent; + border-bottom-color: rgba(0, 0, 0, 0.2); + content: ''; +} + +.navbar .nav > li > .dropdown-menu:after { + position: absolute; + top: -6px; + left: 10px; + display: inline-block; + border-right: 6px solid transparent; + border-bottom: 6px solid #ffffff; + border-left: 6px solid transparent; + content: ''; +} + +.navbar-fixed-bottom .nav > li > .dropdown-menu:before { + top: auto; + bottom: -7px; + border-top: 7px solid #ccc; + border-bottom: 0; + border-top-color: rgba(0, 0, 0, 0.2); +} + +.navbar-fixed-bottom .nav > li > .dropdown-menu:after { + top: auto; + bottom: -6px; + border-top: 6px solid #ffffff; + border-bottom: 0; +} + +.navbar .nav li.dropdown.open > .dropdown-toggle, +.navbar .nav li.dropdown.active > .dropdown-toggle, +.navbar .nav li.dropdown.open.active > .dropdown-toggle { + color: #555555; + background-color: #e5e5e5; +} + +.navbar .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: #777777; + border-bottom-color: #777777; +} + +.navbar .nav li.dropdown.open > .dropdown-toggle .caret, +.navbar .nav li.dropdown.active > .dropdown-toggle .caret, +.navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: #555555; + border-bottom-color: #555555; +} + +.navbar .pull-right > li > .dropdown-menu, +.navbar .nav > li > .dropdown-menu.pull-right { + right: 0; + left: auto; +} + +.navbar .pull-right > li > .dropdown-menu:before, +.navbar .nav > li > .dropdown-menu.pull-right:before { + right: 12px; + left: auto; +} + +.navbar .pull-right > li > .dropdown-menu:after, +.navbar .nav > li > .dropdown-menu.pull-right:after { + right: 13px; + left: auto; +} + +.navbar .pull-right > li > .dropdown-menu .dropdown-menu, +.navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { + right: 100%; + left: auto; + margin-right: -1px; + margin-left: 0; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; +} + +.navbar-inverse { + color: #999999; +} + +.navbar-inverse .navbar-inner { + background-color: #1b1b1b; + background-image: -moz-linear-gradient(top, #222222, #111111); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); + background-image: -webkit-linear-gradient(top, #222222, #111111); + background-image: -o-linear-gradient(top, #222222, #111111); + background-image: linear-gradient(to bottom, #222222, #111111); + background-repeat: repeat-x; + border-color: #252525; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); +} + +.navbar-inverse .brand, +.navbar-inverse .nav > li > a { + color: #999999; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); +} + +.navbar-inverse .brand:hover, +.navbar-inverse .nav > li > a:hover { + color: #ffffff; +} + +.navbar-inverse .nav > li > a:focus, +.navbar-inverse .nav > li > a:hover { + color: #ffffff; + background-color: transparent; +} + +.navbar-inverse .nav .active > a, +.navbar-inverse .nav .active > a:hover, +.navbar-inverse .nav .active > a:focus { + color: #ffffff; + background-color: #111111; +} + +.navbar-inverse .navbar-link { + color: #999999; +} + +.navbar-inverse .navbar-link:hover { + color: #ffffff; +} + +.navbar-inverse .divider-vertical { + border-right-color: #222222; + border-left-color: #111111; +} + +.navbar-inverse .nav li.dropdown.open > .dropdown-toggle, +.navbar-inverse .nav li.dropdown.active > .dropdown-toggle, +.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { + color: #ffffff; + background-color: #111111; +} + +.navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: #999999; + border-bottom-color: #999999; +} + +.navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, +.navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, +.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} + +.navbar-inverse .navbar-search .search-query { + color: #ffffff; + background-color: #515151; + border-color: #111111; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -webkit-transition: none; + -moz-transition: none; + -o-transition: none; + transition: none; +} + +.navbar-inverse .navbar-search .search-query:-moz-placeholder { + color: #cccccc; +} + +.navbar-inverse .navbar-search .search-query:-ms-input-placeholder { + color: #cccccc; +} + +.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { + color: #cccccc; +} + +.navbar-inverse .navbar-search .search-query:focus, +.navbar-inverse .navbar-search .search-query.focused { + padding: 5px 15px; + color: #333333; + text-shadow: 0 1px 0 #ffffff; + background-color: #ffffff; + border: 0; + outline: 0; + -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); +} + +.navbar-inverse .btn-navbar { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e0e0e; + *background-color: #040404; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); + background-image: -webkit-linear-gradient(top, #151515, #040404); + background-image: -o-linear-gradient(top, #151515, #040404); + background-image: linear-gradient(to bottom, #151515, #040404); + background-image: -moz-linear-gradient(top, #151515, #040404); + background-repeat: repeat-x; + border-color: #040404 #040404 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.navbar-inverse .btn-navbar:hover, +.navbar-inverse .btn-navbar:active, +.navbar-inverse .btn-navbar.active, +.navbar-inverse .btn-navbar.disabled, +.navbar-inverse .btn-navbar[disabled] { + color: #ffffff; + background-color: #040404; + *background-color: #000000; +} + +.navbar-inverse .btn-navbar:active, +.navbar-inverse .btn-navbar.active { + background-color: #000000 \9; +} + +.breadcrumb { + padding: 8px 15px; + margin: 0 0 20px; + list-style: none; + background-color: #f5f5f5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.breadcrumb li { + display: inline-block; + *display: inline; + text-shadow: 0 1px 0 #ffffff; + *zoom: 1; +} + +.breadcrumb .divider { + padding: 0 5px; + color: #ccc; +} + +.breadcrumb .active { + color: #999999; +} + +.pagination { + height: 40px; + margin: 20px 0; +} + +.pagination ul { + display: inline-block; + *display: inline; + margin-bottom: 0; + margin-left: 0; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + *zoom: 1; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.pagination ul > li { + display: inline; +} + +.pagination ul > li > a, +.pagination ul > li > span { + float: left; + padding: 0 14px; + line-height: 38px; + text-decoration: none; + background-color: #ffffff; + border: 1px solid #dddddd; + border-left-width: 0; +} + +.pagination ul > li > a:hover, +.pagination ul > .active > a, +.pagination ul > .active > span { + background-color: #f5f5f5; +} + +.pagination ul > .active > a, +.pagination ul > .active > span { + color: #999999; + cursor: default; +} + +.pagination ul > .disabled > span, +.pagination ul > .disabled > a, +.pagination ul > .disabled > a:hover { + color: #999999; + cursor: default; + background-color: transparent; +} + +.pagination ul > li:first-child > a, +.pagination ul > li:first-child > span { + border-left-width: 1px; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.pagination ul > li:last-child > a, +.pagination ul > li:last-child > span { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.pagination-centered { + text-align: center; +} + +.pagination-right { + text-align: right; +} + +.pager { + margin: 20px 0; + text-align: center; + list-style: none; + *zoom: 1; +} + +.pager:before, +.pager:after { + display: table; + line-height: 0; + content: ""; +} + +.pager:after { + clear: both; +} + +.pager li { + display: inline; +} + +.pager a, +.pager span { + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} + +.pager a:hover { + text-decoration: none; + background-color: #f5f5f5; +} + +.pager .next a, +.pager .next span { + float: right; +} + +.pager .previous a { + float: left; +} + +.pager .disabled a, +.pager .disabled a:hover, +.pager .disabled span { + color: #999999; + cursor: default; + background-color: #fff; +} + +.modal-open .modal .dropdown-menu { + z-index: 2050; +} + +.modal-open .modal .dropdown.open { + *z-index: 2050; +} + +.modal-open .modal .popover { + z-index: 2060; +} + +.modal-open .modal .tooltip { + z-index: 2080; +} + +.modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000000; +} + +.modal-backdrop.fade { + opacity: 0; +} + +.modal-backdrop, +.modal-backdrop.fade.in { + opacity: 0.8; + filter: alpha(opacity=80); +} + +.modal { + position: fixed; + top: 50%; + left: 50%; + z-index: 1050; + width: 560px; + margin: -250px 0 0 -280px; + overflow: auto; + background-color: #ffffff; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + *border: 1px solid #999; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} + +.modal.fade { + top: -25%; + -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; + -moz-transition: opacity 0.3s linear, top 0.3s ease-out; + -o-transition: opacity 0.3s linear, top 0.3s ease-out; + transition: opacity 0.3s linear, top 0.3s ease-out; +} + +.modal.fade.in { + top: 50%; +} + +.modal-header { + padding: 9px 15px; + border-bottom: 1px solid #eee; +} + +.modal-header .close { + margin-top: 2px; +} + +.modal-header h3 { + margin: 0; + line-height: 30px; +} + +.modal-body { + max-height: 400px; + padding: 15px; + overflow-y: auto; +} + +.modal-form { + margin-bottom: 0; +} + +.modal-footer { + padding: 14px 15px 15px; + margin-bottom: 0; + text-align: right; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; +} + +.modal-footer:before, +.modal-footer:after { + display: table; + line-height: 0; + 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; +} + +.tooltip { + position: absolute; + z-index: 1030; + display: block; + padding: 5px; + font-size: 11px; + opacity: 0; + filter: alpha(opacity=0); + visibility: visible; +} + +.tooltip.in { + opacity: 0.8; + filter: alpha(opacity=80); +} + +.tooltip.top { + margin-top: -3px; +} + +.tooltip.right { + margin-left: 3px; +} + +.tooltip.bottom { + margin-top: 3px; +} + +.tooltip.left { + margin-left: -3px; +} + +.tooltip-inner { + max-width: 200px; + padding: 3px 8px; + color: #ffffff; + text-align: center; + text-decoration: none; + background-color: #000000; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + 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: #000000; + border-width: 5px 5px 0; +} + +.tooltip.right .tooltip-arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-right-color: #000000; + border-width: 5px 5px 5px 0; +} + +.tooltip.left .tooltip-arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-left-color: #000000; + border-width: 5px 0 5px 5px; +} + +.tooltip.bottom .tooltip-arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-bottom-color: #000000; + border-width: 0 5px 5px; +} + +.popover { + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + width: 236px; + padding: 1px; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; +} + +.popover.top { + margin-bottom: 10px; +} + +.popover.right { + margin-left: 10px; +} + +.popover.bottom { + margin-top: 10px; +} + +.popover.left { + margin-right: 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; + -webkit-border-radius: 5px 5px 0 0; + -moz-border-radius: 5px 5px 0 0; + border-radius: 5px 5px 0 0; +} + +.popover-content { + padding: 9px 14px; +} + +.popover-content p, +.popover-content ul, +.popover-content ol { + margin-bottom: 0; +} + +.popover .arrow, +.popover .arrow:after { + position: absolute; + display: inline-block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} + +.popover .arrow:after { + z-index: -1; + content: ""; +} + +.popover.top .arrow { + bottom: -10px; + left: 50%; + margin-left: -10px; + border-top-color: #ffffff; + border-width: 10px 10px 0; +} + +.popover.top .arrow:after { + bottom: -1px; + left: -11px; + border-top-color: rgba(0, 0, 0, 0.25); + border-width: 11px 11px 0; +} + +.popover.right .arrow { + top: 50%; + left: -10px; + margin-top: -10px; + border-right-color: #ffffff; + border-width: 10px 10px 10px 0; +} + +.popover.right .arrow:after { + bottom: -11px; + left: -1px; + border-right-color: rgba(0, 0, 0, 0.25); + border-width: 11px 11px 11px 0; +} + +.popover.bottom .arrow { + top: -10px; + left: 50%; + margin-left: -10px; + border-bottom-color: #ffffff; + border-width: 0 10px 10px; +} + +.popover.bottom .arrow:after { + top: -1px; + left: -11px; + border-bottom-color: rgba(0, 0, 0, 0.25); + border-width: 0 11px 11px; +} + +.popover.left .arrow { + top: 50%; + right: -10px; + margin-top: -10px; + border-left-color: #ffffff; + border-width: 10px 0 10px 10px; +} + +.popover.left .arrow:after { + right: -1px; + bottom: -11px; + border-left-color: rgba(0, 0, 0, 0.25); + border-width: 11px 0 11px 11px; +} + +.thumbnails { + margin-left: -20px; + list-style: none; + *zoom: 1; +} + +.thumbnails:before, +.thumbnails:after { + display: table; + line-height: 0; + content: ""; +} + +.thumbnails:after { + clear: both; +} + +.row-fluid .thumbnails { + margin-left: 0; +} + +.thumbnails > li { + float: left; + margin-bottom: 20px; + margin-left: 20px; +} + +.thumbnail { + display: block; + padding: 4px; + line-height: 20px; + border: 1px solid #ddd; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -webkit-transition: all 0.2s ease-in-out; + -moz-transition: all 0.2s ease-in-out; + -o-transition: all 0.2s ease-in-out; + transition: all 0.2s ease-in-out; +} + +a.thumbnail:hover { + border-color: #0088cc; + -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); +} + +.thumbnail > img { + display: block; + max-width: 100%; + margin-right: auto; + margin-left: auto; +} + +.thumbnail .caption { + padding: 9px; + color: #555555; +} + +.label, +.badge { + font-size: 11.844px; + font-weight: bold; + line-height: 14px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + white-space: nowrap; + vertical-align: baseline; + background-color: #999999; +} + +.label { + padding: 1px 4px 2px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +.badge { + padding: 1px 9px 2px; + -webkit-border-radius: 9px; + -moz-border-radius: 9px; + border-radius: 9px; +} + +a.label:hover, +a.badge:hover { + color: #ffffff; + text-decoration: none; + cursor: pointer; +} + +.label-important, +.badge-important { + background-color: #b94a48; +} + +.label-important[href], +.badge-important[href] { + background-color: #953b39; +} + +.label-warning, +.badge-warning { + background-color: #f89406; +} + +.label-warning[href], +.badge-warning[href] { + background-color: #c67605; +} + +.label-success, +.badge-success { + background-color: #468847; +} + +.label-success[href], +.badge-success[href] { + background-color: #356635; +} + +.label-info, +.badge-info { + background-color: #3a87ad; +} + +.label-info[href], +.badge-info[href] { + background-color: #2d6987; +} + +.label-inverse, +.badge-inverse { + background-color: #333333; +} + +.label-inverse[href], +.badge-inverse[href] { + background-color: #1a1a1a; +} + +.btn .label, +.btn .badge { + position: relative; + top: -1px; +} + +.btn-mini .label, +.btn-mini .badge { + top: 0; +} + +@-webkit-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-moz-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-ms-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-o-keyframes progress-bar-stripes { + from { + background-position: 0 0; + } + to { + background-position: 40px 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: #f7f7f7; + background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); + background-repeat: repeat-x; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -moz-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; + color: #ffffff; + text-align: center; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e90d2; + background-image: -moz-linear-gradient(top, #149bdf, #0480be); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, #0480be); + background-image: -o-linear-gradient(top, #149bdf, #0480be); + background-image: linear-gradient(to bottom, #149bdf, #0480be); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-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-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-transition: width 0.6s ease; + -moz-transition: width 0.6s ease; + -o-transition: width 0.6s ease; + transition: width 0.6s ease; +} + +.progress .bar + .bar { + -webkit-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); +} + +.progress-striped .bar { + background-color: #149bdf; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + 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: -moz-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: -o-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); + -webkit-background-size: 40px 40px; + -moz-background-size: 40px 40px; + -o-background-size: 40px 40px; + background-size: 40px 40px; +} + +.progress.active .bar { + -webkit-animation: progress-bar-stripes 2s linear infinite; + -moz-animation: progress-bar-stripes 2s linear infinite; + -ms-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; +} + +.progress-danger .bar, +.progress .bar-danger { + background-color: #dd514c; + background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); + background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); +} + +.progress-danger.progress-striped .bar, +.progress-striped .bar-danger { + background-color: #ee5f5b; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + 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: -moz-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: -o-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-success .bar, +.progress .bar-success { + background-color: #5eb95e; + background-image: -moz-linear-gradient(top, #62c462, #57a957); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); + background-image: -webkit-linear-gradient(top, #62c462, #57a957); + background-image: -o-linear-gradient(top, #62c462, #57a957); + background-image: linear-gradient(to bottom, #62c462, #57a957); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); +} + +.progress-success.progress-striped .bar, +.progress-striped .bar-success { + background-color: #62c462; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + 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: -moz-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: -o-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-info .bar, +.progress .bar-info { + background-color: #4bb1cf; + background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); + background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); + background-image: -o-linear-gradient(top, #5bc0de, #339bb9); + background-image: linear-gradient(to bottom, #5bc0de, #339bb9); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); +} + +.progress-info.progress-striped .bar, +.progress-striped .bar-info { + background-color: #5bc0de; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + 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: -moz-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: -o-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-warning .bar, +.progress .bar-warning { + background-color: #faa732; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); +} + +.progress-warning.progress-striped .bar, +.progress-striped .bar-warning { + background-color: #fbb450; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + 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: -moz-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: -o-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); +} + +.accordion { + margin-bottom: 20px; +} + +.accordion-group { + margin-bottom: 2px; + border: 1px solid #e5e5e5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.accordion-heading { + border-bottom: 0; +} + +.accordion-heading .accordion-toggle { + display: block; + padding: 8px 15px; +} + +.accordion-toggle { + cursor: pointer; +} + +.accordion-inner { + padding: 9px 15px; + border-top: 1px solid #e5e5e5; +} + +.carousel { + position: relative; + margin-bottom: 20px; + line-height: 1; +} + +.carousel-inner { + position: relative; + width: 100%; + overflow: hidden; +} + +.carousel .item { + position: relative; + display: none; + -webkit-transition: 0.6s ease-in-out left; + -moz-transition: 0.6s ease-in-out left; + -o-transition: 0.6s ease-in-out left; + transition: 0.6s ease-in-out left; +} + +.carousel .item > img { + display: block; + line-height: 1; +} + +.carousel .active, +.carousel .next, +.carousel .prev { + display: block; +} + +.carousel .active { + left: 0; +} + +.carousel .next, +.carousel .prev { + position: absolute; + top: 0; + width: 100%; +} + +.carousel .next { + left: 100%; +} + +.carousel .prev { + left: -100%; +} + +.carousel .next.left, +.carousel .prev.right { + left: 0; +} + +.carousel .active.left { + left: -100%; +} + +.carousel .active.right { + left: 100%; +} + +.carousel-control { + position: absolute; + top: 40%; + left: 15px; + width: 40px; + height: 40px; + margin-top: -20px; + font-size: 60px; + font-weight: 100; + line-height: 30px; + color: #ffffff; + text-align: center; + background: #222222; + border: 3px solid #ffffff; + -webkit-border-radius: 23px; + -moz-border-radius: 23px; + border-radius: 23px; + opacity: 0.5; + filter: alpha(opacity=50); +} + +.carousel-control.right { + right: 15px; + left: auto; +} + +.carousel-control:hover { + color: #ffffff; + text-decoration: none; + opacity: 0.9; + filter: alpha(opacity=90); +} + +.carousel-caption { + position: absolute; + right: 0; + bottom: 0; + left: 0; + padding: 15px; + background: #333333; + background: rgba(0, 0, 0, 0.75); +} + +.carousel-caption h4, +.carousel-caption p { + line-height: 20px; + color: #ffffff; +} + +.carousel-caption h4 { + margin: 0 0 5px; +} + +.carousel-caption p { + margin-bottom: 0; +} + +.hero-unit { + padding: 60px; + margin-bottom: 30px; + background-color: #eeeeee; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.hero-unit h1 { + margin-bottom: 0; + font-size: 60px; + line-height: 1; + letter-spacing: -1px; + color: inherit; +} + +.hero-unit p { + font-size: 18px; + font-weight: 200; + line-height: 30px; + color: inherit; +} + +.pull-right { + float: right; +} + +.pull-left { + float: left; +} + +.hide { + display: none; +} + +.show { + display: block; +} + +.invisible { + visibility: hidden; +} + +.affix { + position: fixed; +} \ No newline at end of file diff --git a/css/default.css b/css/default.css new file mode 100644 index 000000000..bb17a3a11 --- /dev/null +++ b/css/default.css @@ -0,0 +1,434 @@ +/* Set the body padding-top when above 980px to push the content down from + below the navbar, which is fixed at >980px screen widths. */ +pre { + font-size: 12px; +} + +.dropdown .dropdown-menu { + display: none; + overflow-y: scroll; +} + +.dropdown.open .dropdown-menu { + display: block; +} + +@media (max-width: 480px) { + .repo-link { + display: none; + } +} + +/* Header link to GitHub */ +.repo-link { + float: right; + margin-right: 10px; + margin-top: 9px; +} + +body.index-page #main-content p.badges { + padding-bottom: 1px; +} + +/* GitHub 'Star' badge */ +body.index-page #main-content iframe.github-star-button { + float: right; + margin-top: -12px; + margin-right: -15px; +} + +/* Travis CI and PyPI badge */ +body.index-page #main-content img.status-badge { + float: right; + margin-right: 8px; + margin-top: -11px; + margin-bottom: 0px; +} + +/* Github source file badges */ +a.github { + float: right; + margin-top: -12px; + margin-right: 12px; +} + +a.github:hover { + text-decoration: none; +} + +/* */ +body hr { + border-top: 1px dotted #A30000; +} + +/* Force TOC text to not overrun */ +#table-of-contents { + overflow: hidden; + margin: 0 0 20px 0; +} + +/* Code blocks should scroll horizontally */ +pre { + overflow: auto; + word-wrap: normal; + white-space: pre; +} + +/* Preserve the spacing of the navbar across different screen sizes. */ +.navbar-inner { + /*padding: 5px 0;*/ +} + +@media (max-width: 979px) { + .navbar .brand { + margin-left: 0; + padding-left: 0; + } + .navbar-inner .container-fluid { + padding-left: 15px; + } +} + +.nav-list li.main { + font-weight: bold; +} + +.nav-list a { + overflow: hidden; +} + +.nav-list > li > a { + padding: 2px 15px 3px; +} + +/* Set the table of contents to static so it flows back into the content when + viewed on tablets and smaller. */ +@media (max-width: 767px) { + #table-of-contents { + position: static; + } +} + +/* When the page is in two-column layout, give the main content some room + to breath on the left. */ +@media (min-width: 768px) { + #main-content { + padding-left: 1em; + } +} + +/* Cutesy quote styling */ +blockquote { + font-family: Georgia, serif; + font-size: 18px; + font-style: italic; + margin: 0.25em 0; + padding: 0.25em 40px; + line-height: 1.45; + position: relative; + color: #383838; + border-left: none; +} + +blockquote:before { + display: block; + content: "\201C"; + font-size: 80px; + position: absolute; + left: -10px; + top: -20px; + color: #7a7a7a; +} + +blockquote p:last-child { + color: #999999; + font-size: 14px; + display: block; + margin-top: 5px; +} + + +/*=== dabapps bootstrap styles ====*/ + +html{ + width:100%; + background: none; +} + +body, .navbar .navbar-inner .container-fluid{ + max-width: 1150px; + margin: 0 auto; +} + +/* Replacement for `body { background-attachment: fixed; }`, which + has performance issues when scrolling on large displays. */ +body::before { + content: ' '; + position: fixed; + width: 100%; + height: 100%; + top: 0; + left: 0; + background-color: #f8f8f8; + background: url(../img/grid.png) repeat-x; + will-change: transform; + z-index: -1; +} + + +#main-content h1:first-of-type { + margin-top: 0 +} + +#main-content h1, #main-content h2 { + font-weight: 300; + margin-top: 20px +} + +#main-content h3, #main-content h4, #main-content h5 { + font-weight: 300; + margin-top: 15px +} + +#main-content img { + display: block; + margin: 40px auto; +} +/* custom navigation styles */ + +.navbar .navbar-inner{ + background: #2C2C2C; + color: white; + border: none; + border-top: 5px solid #A30000; +} + +.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{ + color: white; +} + +.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover { + background:#212121; + color:white; +} + +.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{ + 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; +} + +/* custom general page styles */ +.hero-unit h2, .hero-unit h1{ + color: #A30000; +} + +body a{ + color: #A30000; +} + +body a:hover{ + color: #c20000; +} + +/* subnavigation styles */ + +@media (min-width: 767px) { + .sidebar-nav-fixed { + position:fixed; + width:19%; + max-width: 240px; + } + + .navbar { + position: fixed; + } + .navbar .navbar-inner .container-fluid{ + max-width: 1110px; + } +} + +h1 code, h2 code, h3 code, h4 code, h5 code { + color: #333; +} + +/* sticky footer and footer */ +html, body { + height: 100%; +} +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -60px; +} + +.body-content{ + padding-top: 70px; + padding-bottom: 70px; +} + +@media (max-width: 979px) { + .navbar-fixed-top .navbar-inner { + padding: 0px; + } +} + +@media (max-width: 767px) { + .body-content{ + padding-top: 0px; + } +} + +@media (min-width: 768px) { + footer.span12 { + width: 95%; + } +} + +footer, .push { + height: 60px; /* .push must be the same height as .footer */ +} + + +footer p { + text-align: center; + color: gray; + border-top: 1px solid #DDD; + padding-top: 10px; +} + +footer a { + color: gray; + font-weight: bold; +} + +footer a:hover { + color: gray; +} + +.btn-inverse { + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important; + background-image: -webkit-linear-gradient(top, #606060, #404040) !important; +} + +.modal-open .modal,.btn:focus{outline:none;} + +@media (max-width: 650px) { + .repo-link.btn-inverse {display: none;} +} + +td, th { + padding: 0.25em; + background-color: #f7f7f9; + border-color: #e1e1e8; +} + +table { + border-color: white; + margin-bottom: 0.6em; +} + +.side-nav { + overflow-y: scroll; +} + + +ul.sponsor.diamond li a { + float: left; + width: 600px; + height: 20px; + text-align: center; + margin: 10px 70px; + padding: 300px 0 0 0; + background-position: 0 50%; + background-size: 600px auto; + background-repeat: no-repeat; + font-size: 200%; +} + +@media (max-width: 1000px) { + ul.sponsor.diamond li a { + float: left; + width: 300px; + height: 20px; + text-align: center; + margin: 10px 40px; + padding: 300px 0 0 0; + background-position: 0 50%; + background-size: 280px auto; + background-repeat: no-repeat; + font-size: 150%; + } +} + +ul.sponsor.platinum li a { + float: left; + width: 300px; + height: 20px; + text-align: center; + margin: 10px 40px; + padding: 300px 0 0 0; + background-position: 0 50%; + background-size: 280px auto; + background-repeat: no-repeat; + font-size: 150%; +} + +ul.sponsor.gold li a { + float: left; + width: 130px; + height: 20px; + text-align: center; + margin: 10px 30px; + padding: 150px 0 0 0; + background-position: 0 50%; + background-size: 130px auto; + background-repeat: no-repeat; + font-size: 120%; +} + +ul.sponsor.silver li a { + float: left; + width: 130px; + height: 20px; + text-align: center; + margin: 10px 30px; + padding: 150px 0 0 0; + background-position: 0 50%; + background-size: 130px auto; + background-repeat: no-repeat; + font-size: 120%; +} + +ul.sponsor { + list-style: none; + display: block; +} + +#mkdocs_search_modal article p{ + word-wrap: break-word; +} + +.toclink { + color: #333; +} + +.book-cover img { + margin: 0 !important; + display: inline-block !important; +} diff --git a/css/font-awesome.min.css b/css/font-awesome.min.css new file mode 100644 index 000000000..540440ce8 --- /dev/null +++ b/css/font-awesome.min.css @@ -0,0 +1,4 @@ +/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.7.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.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.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.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:#fff}.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-remove:before,.fa-close:before,.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-photo:before,.fa-image:before,.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,.fa-bar-chart: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-f:before,.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-feed:before,.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-navicon:before,.fa-reorder:before,.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-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc: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-mail-reply-all:before,.fa-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,.fa-gratipay: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"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}.fa-buysellads:before{content:"\f20d"}.fa-connectdevelop:before{content:"\f20e"}.fa-dashcube:before{content:"\f210"}.fa-forumbee:before{content:"\f211"}.fa-leanpub:before{content:"\f212"}.fa-sellsy:before{content:"\f213"}.fa-shirtsinbulk:before{content:"\f214"}.fa-simplybuilt:before{content:"\f215"}.fa-skyatlas:before{content:"\f216"}.fa-cart-plus:before{content:"\f217"}.fa-cart-arrow-down:before{content:"\f218"}.fa-diamond:before{content:"\f219"}.fa-ship:before{content:"\f21a"}.fa-user-secret:before{content:"\f21b"}.fa-motorcycle:before{content:"\f21c"}.fa-street-view:before{content:"\f21d"}.fa-heartbeat:before{content:"\f21e"}.fa-venus:before{content:"\f221"}.fa-mars:before{content:"\f222"}.fa-mercury:before{content:"\f223"}.fa-intersex:before,.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-venus-double:before{content:"\f226"}.fa-mars-double:before{content:"\f227"}.fa-venus-mars:before{content:"\f228"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-neuter:before{content:"\f22c"}.fa-genderless:before{content:"\f22d"}.fa-facebook-official:before{content:"\f230"}.fa-pinterest-p:before{content:"\f231"}.fa-whatsapp:before{content:"\f232"}.fa-server:before{content:"\f233"}.fa-user-plus:before{content:"\f234"}.fa-user-times:before{content:"\f235"}.fa-hotel:before,.fa-bed:before{content:"\f236"}.fa-viacoin:before{content:"\f237"}.fa-train:before{content:"\f238"}.fa-subway:before{content:"\f239"}.fa-medium:before{content:"\f23a"}.fa-yc:before,.fa-y-combinator:before{content:"\f23b"}.fa-optin-monster:before{content:"\f23c"}.fa-opencart:before{content:"\f23d"}.fa-expeditedssl:before{content:"\f23e"}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:"\f240"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-battery-2:before,.fa-battery-half:before{content:"\f242"}.fa-battery-1:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-mouse-pointer:before{content:"\f245"}.fa-i-cursor:before{content:"\f246"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-sticky-note:before{content:"\f249"}.fa-sticky-note-o:before{content:"\f24a"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-diners-club:before{content:"\f24c"}.fa-clone:before{content:"\f24d"}.fa-balance-scale:before{content:"\f24e"}.fa-hourglass-o:before{content:"\f250"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass:before{content:"\f254"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:"\f255"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:"\f256"}.fa-hand-scissors-o:before{content:"\f257"}.fa-hand-lizard-o:before{content:"\f258"}.fa-hand-spock-o:before{content:"\f259"}.fa-hand-pointer-o:before{content:"\f25a"}.fa-hand-peace-o:before{content:"\f25b"}.fa-trademark:before{content:"\f25c"}.fa-registered:before{content:"\f25d"}.fa-creative-commons:before{content:"\f25e"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-tripadvisor:before{content:"\f262"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-get-pocket:before{content:"\f265"}.fa-wikipedia-w:before{content:"\f266"}.fa-safari:before{content:"\f267"}.fa-chrome:before{content:"\f268"}.fa-firefox:before{content:"\f269"}.fa-opera:before{content:"\f26a"}.fa-internet-explorer:before{content:"\f26b"}.fa-tv:before,.fa-television:before{content:"\f26c"}.fa-contao:before{content:"\f26d"}.fa-500px:before{content:"\f26e"}.fa-amazon:before{content:"\f270"}.fa-calendar-plus-o:before{content:"\f271"}.fa-calendar-minus-o:before{content:"\f272"}.fa-calendar-times-o:before{content:"\f273"}.fa-calendar-check-o:before{content:"\f274"}.fa-industry:before{content:"\f275"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-map-o:before{content:"\f278"}.fa-map:before{content:"\f279"}.fa-commenting:before{content:"\f27a"}.fa-commenting-o:before{content:"\f27b"}.fa-houzz:before{content:"\f27c"}.fa-vimeo:before{content:"\f27d"}.fa-black-tie:before{content:"\f27e"}.fa-fonticons:before{content:"\f280"}.fa-reddit-alien:before{content:"\f281"}.fa-edge:before{content:"\f282"}.fa-credit-card-alt:before{content:"\f283"}.fa-codiepie:before{content:"\f284"}.fa-modx:before{content:"\f285"}.fa-fort-awesome:before{content:"\f286"}.fa-usb:before{content:"\f287"}.fa-product-hunt:before{content:"\f288"}.fa-mixcloud:before{content:"\f289"}.fa-scribd:before{content:"\f28a"}.fa-pause-circle:before{content:"\f28b"}.fa-pause-circle-o:before{content:"\f28c"}.fa-stop-circle:before{content:"\f28d"}.fa-stop-circle-o:before{content:"\f28e"}.fa-shopping-bag:before{content:"\f290"}.fa-shopping-basket:before{content:"\f291"}.fa-hashtag:before{content:"\f292"}.fa-bluetooth:before{content:"\f293"}.fa-bluetooth-b:before{content:"\f294"}.fa-percent:before{content:"\f295"}.fa-gitlab:before{content:"\f296"}.fa-wpbeginner:before{content:"\f297"}.fa-wpforms:before{content:"\f298"}.fa-envira:before{content:"\f299"}.fa-universal-access:before{content:"\f29a"}.fa-wheelchair-alt:before{content:"\f29b"}.fa-question-circle-o:before{content:"\f29c"}.fa-blind:before{content:"\f29d"}.fa-audio-description:before{content:"\f29e"}.fa-volume-control-phone:before{content:"\f2a0"}.fa-braille:before{content:"\f2a1"}.fa-assistive-listening-systems:before{content:"\f2a2"}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:"\f2a4"}.fa-glide:before{content:"\f2a5"}.fa-glide-g:before{content:"\f2a6"}.fa-signing:before,.fa-sign-language:before{content:"\f2a7"}.fa-low-vision:before{content:"\f2a8"}.fa-viadeo:before{content:"\f2a9"}.fa-viadeo-square:before{content:"\f2aa"}.fa-snapchat:before{content:"\f2ab"}.fa-snapchat-ghost:before{content:"\f2ac"}.fa-snapchat-square:before{content:"\f2ad"}.fa-pied-piper:before{content:"\f2ae"}.fa-first-order:before{content:"\f2b0"}.fa-yoast:before{content:"\f2b1"}.fa-themeisle:before{content:"\f2b2"}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:"\f2b3"}.fa-fa:before,.fa-font-awesome:before{content:"\f2b4"}.fa-handshake-o:before{content:"\f2b5"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-o:before{content:"\f2b7"}.fa-linode:before{content:"\f2b8"}.fa-address-book:before{content:"\f2b9"}.fa-address-book-o:before{content:"\f2ba"}.fa-vcard:before,.fa-address-card:before{content:"\f2bb"}.fa-vcard-o:before,.fa-address-card-o:before{content:"\f2bc"}.fa-user-circle:before{content:"\f2bd"}.fa-user-circle-o:before{content:"\f2be"}.fa-user-o:before{content:"\f2c0"}.fa-id-badge:before{content:"\f2c1"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-drivers-license-o:before,.fa-id-card-o:before{content:"\f2c3"}.fa-quora:before{content:"\f2c4"}.fa-free-code-camp:before{content:"\f2c5"}.fa-telegram:before{content:"\f2c6"}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-shower:before{content:"\f2cc"}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:"\f2cd"}.fa-podcast:before{content:"\f2ce"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-times-rectangle:before,.fa-window-close:before{content:"\f2d3"}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:"\f2d4"}.fa-bandcamp:before{content:"\f2d5"}.fa-grav:before{content:"\f2d6"}.fa-etsy:before{content:"\f2d7"}.fa-imdb:before{content:"\f2d8"}.fa-ravelry:before{content:"\f2d9"}.fa-eercast:before{content:"\f2da"}.fa-microchip:before{content:"\f2db"}.fa-snowflake-o:before{content:"\f2dc"}.fa-superpowers:before{content:"\f2dd"}.fa-wpexplorer:before{content:"\f2de"}.fa-meetup:before{content:"\f2e0"}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto} diff --git a/css/prettify.css b/css/prettify.css new file mode 100644 index 000000000..d437aff62 --- /dev/null +++ b/css/prettify.css @@ -0,0 +1,30 @@ +.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; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; +} +.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; +} \ No newline at end of file diff --git a/fonts/fontawesome-webfont.eot b/fonts/fontawesome-webfont.eot new file mode 100644 index 000000000..e9f60ca95 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..855c845e5 --- /dev/null +++ b/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/fonts/fontawesome-webfont.ttf b/fonts/fontawesome-webfont.ttf new file mode 100644 index 000000000..35acda2fa 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..400014a4b Binary files /dev/null and b/fonts/fontawesome-webfont.woff differ diff --git a/fonts/fontawesome-webfont.woff2 b/fonts/fontawesome-webfont.woff2 new file mode 100644 index 000000000..4d13fc604 Binary files /dev/null and b/fonts/fontawesome-webfont.woff2 differ diff --git a/fonts/glyphicons-halflings-regular.eot b/fonts/glyphicons-halflings-regular.eot new file mode 100644 index 000000000..b93a4953f Binary files /dev/null and b/fonts/glyphicons-halflings-regular.eot differ diff --git a/fonts/glyphicons-halflings-regular.svg b/fonts/glyphicons-halflings-regular.svg new file mode 100644 index 000000000..94fb5490a --- /dev/null +++ b/fonts/glyphicons-halflings-regular.svg @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fonts/glyphicons-halflings-regular.ttf b/fonts/glyphicons-halflings-regular.ttf new file mode 100644 index 000000000..1413fc609 Binary files /dev/null and b/fonts/glyphicons-halflings-regular.ttf differ diff --git a/fonts/glyphicons-halflings-regular.woff b/fonts/glyphicons-halflings-regular.woff new file mode 100644 index 000000000..9e612858f Binary files /dev/null and b/fonts/glyphicons-halflings-regular.woff differ diff --git a/fonts/glyphicons-halflings-regular.woff2 b/fonts/glyphicons-halflings-regular.woff2 new file mode 100644 index 000000000..64539b54c Binary files /dev/null and b/fonts/glyphicons-halflings-regular.woff2 differ diff --git a/img/admin.png b/img/admin.png new file mode 100644 index 000000000..f12df099d Binary files /dev/null and b/img/admin.png differ diff --git a/img/api-docs.gif b/img/api-docs.gif new file mode 100644 index 000000000..6da560b7e Binary files /dev/null and b/img/api-docs.gif differ diff --git a/img/api-docs.png b/img/api-docs.png new file mode 100644 index 000000000..939075a89 Binary files /dev/null and b/img/api-docs.png differ diff --git a/img/bayer.png b/img/bayer.png new file mode 100644 index 000000000..e8ef56f5f Binary files /dev/null and b/img/bayer.png differ diff --git a/img/blacklivesmatter.png b/img/blacklivesmatter.png new file mode 100644 index 000000000..cb88b04f9 Binary files /dev/null and b/img/blacklivesmatter.png differ diff --git a/img/books/bda-cover.png b/img/books/bda-cover.png new file mode 100644 index 000000000..741fd24db Binary files /dev/null and b/img/books/bda-cover.png differ diff --git a/img/books/hwa-cover.png b/img/books/hwa-cover.png new file mode 100644 index 000000000..93d7a3088 Binary files /dev/null and b/img/books/hwa-cover.png differ diff --git a/img/books/rad-cover.png b/img/books/rad-cover.png new file mode 100644 index 000000000..75b19df64 Binary files /dev/null and b/img/books/rad-cover.png differ diff --git a/img/books/tsd-cover.png b/img/books/tsd-cover.png new file mode 100644 index 000000000..5034edfad Binary files /dev/null and b/img/books/tsd-cover.png differ diff --git a/img/cerulean.png b/img/cerulean.png new file mode 100644 index 000000000..e647d5e81 Binary files /dev/null and b/img/cerulean.png differ diff --git a/img/corejson-format.png b/img/corejson-format.png new file mode 100644 index 000000000..36c197a0d Binary files /dev/null and b/img/corejson-format.png differ diff --git a/img/cursor-pagination.png b/img/cursor-pagination.png new file mode 100644 index 000000000..1c9c99b68 Binary files /dev/null and b/img/cursor-pagination.png differ diff --git a/img/drf-yasg.png b/img/drf-yasg.png new file mode 100644 index 000000000..ed770a386 Binary files /dev/null and b/img/drf-yasg.png differ diff --git a/img/favicon.ico b/img/favicon.ico new file mode 100644 index 000000000..917892ad5 Binary files /dev/null and b/img/favicon.ico differ diff --git a/img/filter-controls.png b/img/filter-controls.png new file mode 100644 index 000000000..4a41cf04f Binary files /dev/null and b/img/filter-controls.png differ diff --git a/img/glyphicons-halflings-white.png b/img/glyphicons-halflings-white.png new file mode 100644 index 000000000..3bf6484a2 Binary files /dev/null and b/img/glyphicons-halflings-white.png differ diff --git a/img/glyphicons-halflings.png b/img/glyphicons-halflings.png new file mode 100644 index 000000000..a99699932 Binary files /dev/null and b/img/glyphicons-halflings.png differ diff --git a/img/grid.png b/img/grid.png new file mode 100644 index 000000000..878c3ed5c Binary files /dev/null and b/img/grid.png differ diff --git a/img/horizontal.png b/img/horizontal.png new file mode 100644 index 000000000..3852070ae Binary files /dev/null and b/img/horizontal.png differ diff --git a/img/inline.png b/img/inline.png new file mode 100644 index 000000000..a910de19e Binary files /dev/null and b/img/inline.png differ diff --git a/img/labels-and-milestones.png b/img/labels-and-milestones.png new file mode 100644 index 000000000..e7c829adc Binary files /dev/null and b/img/labels-and-milestones.png differ diff --git a/img/link-header-pagination.png b/img/link-header-pagination.png new file mode 100644 index 000000000..d3c556a4d Binary files /dev/null and b/img/link-header-pagination.png differ diff --git a/img/logo.png b/img/logo.png new file mode 100644 index 000000000..73de34f4b Binary files /dev/null and b/img/logo.png differ diff --git a/img/ordering-filter.png b/img/ordering-filter.png new file mode 100644 index 000000000..25bc4ec7a Binary files /dev/null and b/img/ordering-filter.png differ diff --git a/img/pages-pagination.png b/img/pages-pagination.png new file mode 100644 index 000000000..4ce1a09a8 Binary files /dev/null and b/img/pages-pagination.png differ diff --git a/img/premium/cadre-readme.png b/img/premium/cadre-readme.png new file mode 100644 index 000000000..8144c7bd0 Binary files /dev/null and b/img/premium/cadre-readme.png differ diff --git a/img/premium/esg-readme.png b/img/premium/esg-readme.png new file mode 100644 index 000000000..50aec5f1f Binary files /dev/null and b/img/premium/esg-readme.png differ diff --git a/img/premium/kloudless-readme.png b/img/premium/kloudless-readme.png new file mode 100644 index 000000000..2ee1c4874 Binary files /dev/null and b/img/premium/kloudless-readme.png differ diff --git a/img/premium/lightson-readme.png b/img/premium/lightson-readme.png new file mode 100644 index 000000000..0de66562b Binary files /dev/null and b/img/premium/lightson-readme.png differ diff --git a/img/premium/release-history.png b/img/premium/release-history.png new file mode 100644 index 000000000..8bc9b20f6 Binary files /dev/null and b/img/premium/release-history.png differ diff --git a/img/premium/retool-readme.png b/img/premium/retool-readme.png new file mode 100644 index 000000000..b5dc3aee7 Binary files /dev/null and b/img/premium/retool-readme.png differ diff --git a/img/premium/rollbar-readme.png b/img/premium/rollbar-readme.png new file mode 100644 index 000000000..c1d6e98d5 Binary files /dev/null and b/img/premium/rollbar-readme.png differ diff --git a/img/premium/sentry-readme.png b/img/premium/sentry-readme.png new file mode 100644 index 000000000..e4b5b8f34 Binary files /dev/null and b/img/premium/sentry-readme.png differ diff --git a/img/premium/stream-readme.png b/img/premium/stream-readme.png new file mode 100644 index 000000000..0ca650eaa Binary files /dev/null and b/img/premium/stream-readme.png differ diff --git a/img/quickstart.png b/img/quickstart.png new file mode 100644 index 000000000..5006d60fe Binary files /dev/null and b/img/quickstart.png differ diff --git a/img/raml.png b/img/raml.png new file mode 100644 index 000000000..87790dc48 Binary files /dev/null and b/img/raml.png differ diff --git a/img/rover.png b/img/rover.png new file mode 100644 index 000000000..93aaca701 Binary files /dev/null and b/img/rover.png differ diff --git a/img/search-filter.png b/img/search-filter.png new file mode 100644 index 000000000..d36f2b968 Binary files /dev/null and b/img/search-filter.png differ diff --git a/img/self-describing.png b/img/self-describing.png new file mode 100644 index 000000000..ecbe4fe40 Binary files /dev/null and b/img/self-describing.png differ diff --git a/img/slate.png b/img/slate.png new file mode 100644 index 000000000..31644eafe Binary files /dev/null and b/img/slate.png differ diff --git a/img/sponsors/0-eventbrite.png b/img/sponsors/0-eventbrite.png new file mode 100644 index 000000000..6c7392936 Binary files /dev/null and b/img/sponsors/0-eventbrite.png differ diff --git a/img/sponsors/1-cyan.png b/img/sponsors/1-cyan.png new file mode 100644 index 000000000..d6b55b4c5 Binary files /dev/null and b/img/sponsors/1-cyan.png differ diff --git a/img/sponsors/1-divio.png b/img/sponsors/1-divio.png new file mode 100644 index 000000000..8ced88f82 Binary files /dev/null and b/img/sponsors/1-divio.png differ diff --git a/img/sponsors/1-kuwaitnet.png b/img/sponsors/1-kuwaitnet.png new file mode 100644 index 000000000..bb779ea77 Binary files /dev/null and b/img/sponsors/1-kuwaitnet.png differ diff --git a/img/sponsors/1-lulu.png b/img/sponsors/1-lulu.png new file mode 100644 index 000000000..8a28bfa9f Binary files /dev/null and b/img/sponsors/1-lulu.png differ diff --git a/img/sponsors/1-potato.png b/img/sponsors/1-potato.png new file mode 100644 index 000000000..ad38abdd2 Binary files /dev/null and b/img/sponsors/1-potato.png differ diff --git a/img/sponsors/1-purplebit.png b/img/sponsors/1-purplebit.png new file mode 100644 index 000000000..0df63bf60 Binary files /dev/null and b/img/sponsors/1-purplebit.png differ diff --git a/img/sponsors/1-runscope.png b/img/sponsors/1-runscope.png new file mode 100644 index 000000000..d80a4b85b Binary files /dev/null and b/img/sponsors/1-runscope.png differ diff --git a/img/sponsors/1-simple-energy.png b/img/sponsors/1-simple-energy.png new file mode 100644 index 000000000..f59f7374c Binary files /dev/null and b/img/sponsors/1-simple-energy.png differ diff --git a/img/sponsors/1-vokal_interactive.png b/img/sponsors/1-vokal_interactive.png new file mode 100644 index 000000000..431482dca Binary files /dev/null and b/img/sponsors/1-vokal_interactive.png differ diff --git a/img/sponsors/1-wiredrive.png b/img/sponsors/1-wiredrive.png new file mode 100644 index 000000000..c9befefe4 Binary files /dev/null and b/img/sponsors/1-wiredrive.png differ diff --git a/img/sponsors/2-byte.png b/img/sponsors/2-byte.png new file mode 100644 index 000000000..2c3777b50 Binary files /dev/null and b/img/sponsors/2-byte.png differ diff --git a/img/sponsors/2-compile.png b/img/sponsors/2-compile.png new file mode 100644 index 000000000..858aa09d4 Binary files /dev/null and b/img/sponsors/2-compile.png differ diff --git a/img/sponsors/2-crate.png b/img/sponsors/2-crate.png new file mode 100644 index 000000000..6ef6b5da5 Binary files /dev/null and b/img/sponsors/2-crate.png differ diff --git a/img/sponsors/2-cryptico.png b/img/sponsors/2-cryptico.png new file mode 100644 index 000000000..2d86afe81 Binary files /dev/null and b/img/sponsors/2-cryptico.png differ diff --git a/img/sponsors/2-django.png b/img/sponsors/2-django.png new file mode 100644 index 000000000..c89e19cb3 Binary files /dev/null and b/img/sponsors/2-django.png differ diff --git a/img/sponsors/2-heroku.png b/img/sponsors/2-heroku.png new file mode 100644 index 000000000..224476596 Binary files /dev/null and b/img/sponsors/2-heroku.png differ diff --git a/img/sponsors/2-hipflask.png b/img/sponsors/2-hipflask.png new file mode 100644 index 000000000..c74735c34 Binary files /dev/null and b/img/sponsors/2-hipflask.png differ diff --git a/img/sponsors/2-hipo.png b/img/sponsors/2-hipo.png new file mode 100644 index 000000000..2b854c6d4 Binary files /dev/null and b/img/sponsors/2-hipo.png differ diff --git a/img/sponsors/2-koordinates.png b/img/sponsors/2-koordinates.png new file mode 100644 index 000000000..f38601b34 Binary files /dev/null and b/img/sponsors/2-koordinates.png differ diff --git a/img/sponsors/2-laterpay.png b/img/sponsors/2-laterpay.png new file mode 100644 index 000000000..75eb97d3f Binary files /dev/null and b/img/sponsors/2-laterpay.png differ diff --git a/img/sponsors/2-lightning_kite.png b/img/sponsors/2-lightning_kite.png new file mode 100644 index 000000000..ffdced04e Binary files /dev/null and b/img/sponsors/2-lightning_kite.png differ diff --git a/img/sponsors/2-mirus_research.png b/img/sponsors/2-mirus_research.png new file mode 100644 index 000000000..b15440708 Binary files /dev/null and b/img/sponsors/2-mirus_research.png differ diff --git a/img/sponsors/2-nexthub.png b/img/sponsors/2-nexthub.png new file mode 100644 index 000000000..9bf76e0bf Binary files /dev/null and b/img/sponsors/2-nexthub.png differ diff --git a/img/sponsors/2-opbeat.png b/img/sponsors/2-opbeat.png new file mode 100644 index 000000000..c71a52417 Binary files /dev/null and b/img/sponsors/2-opbeat.png differ diff --git a/img/sponsors/2-prorenata.png b/img/sponsors/2-prorenata.png new file mode 100644 index 000000000..f5e8bb762 Binary files /dev/null and b/img/sponsors/2-prorenata.png differ diff --git a/img/sponsors/2-pulsecode.png b/img/sponsors/2-pulsecode.png new file mode 100644 index 000000000..49f9532cf Binary files /dev/null and b/img/sponsors/2-pulsecode.png differ diff --git a/img/sponsors/2-rapasso.png b/img/sponsors/2-rapasso.png new file mode 100644 index 000000000..618e294be Binary files /dev/null and b/img/sponsors/2-rapasso.png differ diff --git a/img/sponsors/2-rheinwerk_verlag.png b/img/sponsors/2-rheinwerk_verlag.png new file mode 100644 index 000000000..ad454e177 Binary files /dev/null and b/img/sponsors/2-rheinwerk_verlag.png differ diff --git a/img/sponsors/2-schuberg_philis.png b/img/sponsors/2-schuberg_philis.png new file mode 100644 index 000000000..fd9282eeb Binary files /dev/null and b/img/sponsors/2-schuberg_philis.png differ diff --git a/img/sponsors/2-security_compass.png b/img/sponsors/2-security_compass.png new file mode 100644 index 000000000..abd63dbe3 Binary files /dev/null and b/img/sponsors/2-security_compass.png differ diff --git a/img/sponsors/2-sga.png b/img/sponsors/2-sga.png new file mode 100644 index 000000000..2b2a3b3bb Binary files /dev/null and b/img/sponsors/2-sga.png differ diff --git a/img/sponsors/2-singing-horse.png b/img/sponsors/2-singing-horse.png new file mode 100644 index 000000000..84142ae6c Binary files /dev/null and b/img/sponsors/2-singing-horse.png differ diff --git a/img/sponsors/2-sirono.png b/img/sponsors/2-sirono.png new file mode 100644 index 000000000..0a243001a Binary files /dev/null and b/img/sponsors/2-sirono.png differ diff --git a/img/sponsors/2-vinta.png b/img/sponsors/2-vinta.png new file mode 100644 index 000000000..4f4d75bc1 Binary files /dev/null and b/img/sponsors/2-vinta.png differ diff --git a/img/sponsors/2-wusawork.png b/img/sponsors/2-wusawork.png new file mode 100644 index 000000000..5834729b9 Binary files /dev/null and b/img/sponsors/2-wusawork.png differ diff --git a/img/sponsors/3-aba.png b/img/sponsors/3-aba.png new file mode 100644 index 000000000..cefa3dd60 Binary files /dev/null and b/img/sponsors/3-aba.png differ diff --git a/img/sponsors/3-aditium.png b/img/sponsors/3-aditium.png new file mode 100644 index 000000000..0952b08c8 Binary files /dev/null and b/img/sponsors/3-aditium.png differ diff --git a/img/sponsors/3-alwaysdata.png b/img/sponsors/3-alwaysdata.png new file mode 100644 index 000000000..4095774b7 Binary files /dev/null and b/img/sponsors/3-alwaysdata.png differ diff --git a/img/sponsors/3-ax_semantics.png b/img/sponsors/3-ax_semantics.png new file mode 100644 index 000000000..c072e028a Binary files /dev/null and b/img/sponsors/3-ax_semantics.png differ diff --git a/img/sponsors/3-beefarm.png b/img/sponsors/3-beefarm.png new file mode 100644 index 000000000..3348df42a Binary files /dev/null and b/img/sponsors/3-beefarm.png differ diff --git a/img/sponsors/3-blimp.png b/img/sponsors/3-blimp.png new file mode 100644 index 000000000..494bf7924 Binary files /dev/null and b/img/sponsors/3-blimp.png differ diff --git a/img/sponsors/3-brightloop.png b/img/sponsors/3-brightloop.png new file mode 100644 index 000000000..8d5e85a66 Binary files /dev/null and b/img/sponsors/3-brightloop.png differ diff --git a/img/sponsors/3-cantemo.gif b/img/sponsors/3-cantemo.gif new file mode 100644 index 000000000..17b1e8d05 Binary files /dev/null and b/img/sponsors/3-cantemo.gif differ diff --git a/img/sponsors/3-crosswordtracker.png b/img/sponsors/3-crosswordtracker.png new file mode 100644 index 000000000..f72362ea9 Binary files /dev/null and b/img/sponsors/3-crosswordtracker.png differ diff --git a/img/sponsors/3-fluxility.png b/img/sponsors/3-fluxility.png new file mode 100644 index 000000000..eacd7da97 Binary files /dev/null and b/img/sponsors/3-fluxility.png differ diff --git a/img/sponsors/3-garfo.png b/img/sponsors/3-garfo.png new file mode 100644 index 000000000..a9bdea0a0 Binary files /dev/null and b/img/sponsors/3-garfo.png differ diff --git a/img/sponsors/3-gizmag.png b/img/sponsors/3-gizmag.png new file mode 100644 index 000000000..a8d41bd02 Binary files /dev/null and b/img/sponsors/3-gizmag.png differ diff --git a/img/sponsors/3-holvi.png b/img/sponsors/3-holvi.png new file mode 100644 index 000000000..255e391e0 Binary files /dev/null and b/img/sponsors/3-holvi.png differ diff --git a/img/sponsors/3-imt_computer_services.png b/img/sponsors/3-imt_computer_services.png new file mode 100644 index 000000000..00643c978 Binary files /dev/null and b/img/sponsors/3-imt_computer_services.png differ diff --git a/img/sponsors/3-infinite_code.png b/img/sponsors/3-infinite_code.png new file mode 100644 index 000000000..7a8fdcf16 Binary files /dev/null and b/img/sponsors/3-infinite_code.png differ diff --git a/img/sponsors/3-ipushpull.png b/img/sponsors/3-ipushpull.png new file mode 100644 index 000000000..e70b8bad2 Binary files /dev/null and b/img/sponsors/3-ipushpull.png differ diff --git a/img/sponsors/3-isl.png b/img/sponsors/3-isl.png new file mode 100644 index 000000000..0bf0cf7c9 Binary files /dev/null and b/img/sponsors/3-isl.png differ diff --git a/img/sponsors/3-life_the_game.png b/img/sponsors/3-life_the_game.png new file mode 100644 index 000000000..9292685e7 Binary files /dev/null and b/img/sponsors/3-life_the_game.png differ diff --git a/img/sponsors/3-makespace.png b/img/sponsors/3-makespace.png new file mode 100644 index 000000000..80b793619 Binary files /dev/null and b/img/sponsors/3-makespace.png differ diff --git a/img/sponsors/3-nephila.png b/img/sponsors/3-nephila.png new file mode 100644 index 000000000..a905fa938 Binary files /dev/null and b/img/sponsors/3-nephila.png differ diff --git a/img/sponsors/3-openeye.png b/img/sponsors/3-openeye.png new file mode 100644 index 000000000..573140ed6 Binary files /dev/null and b/img/sponsors/3-openeye.png differ diff --git a/img/sponsors/3-pathwright.png b/img/sponsors/3-pathwright.png new file mode 100644 index 000000000..71be3b28b Binary files /dev/null and b/img/sponsors/3-pathwright.png differ diff --git a/img/sponsors/3-phurba.png b/img/sponsors/3-phurba.png new file mode 100644 index 000000000..657d872c9 Binary files /dev/null and b/img/sponsors/3-phurba.png differ diff --git a/img/sponsors/3-pkgfarm.png b/img/sponsors/3-pkgfarm.png new file mode 100644 index 000000000..9224cc2ee Binary files /dev/null and b/img/sponsors/3-pkgfarm.png differ diff --git a/img/sponsors/3-providenz.png b/img/sponsors/3-providenz.png new file mode 100644 index 000000000..55d9c992a Binary files /dev/null and b/img/sponsors/3-providenz.png differ diff --git a/img/sponsors/3-safari.png b/img/sponsors/3-safari.png new file mode 100644 index 000000000..c03e40e84 Binary files /dev/null and b/img/sponsors/3-safari.png differ diff --git a/img/sponsors/3-shippo.png b/img/sponsors/3-shippo.png new file mode 100644 index 000000000..4f5ae133a Binary files /dev/null and b/img/sponsors/3-shippo.png differ diff --git a/img/sponsors/3-teonite.png b/img/sponsors/3-teonite.png new file mode 100644 index 000000000..0c0984783 Binary files /dev/null and b/img/sponsors/3-teonite.png differ diff --git a/img/sponsors/3-thermondo-gmbh.png b/img/sponsors/3-thermondo-gmbh.png new file mode 100644 index 000000000..fe8691c8d Binary files /dev/null and b/img/sponsors/3-thermondo-gmbh.png differ diff --git a/img/sponsors/3-tivix.png b/img/sponsors/3-tivix.png new file mode 100644 index 000000000..bc2616a62 Binary files /dev/null and b/img/sponsors/3-tivix.png differ diff --git a/img/sponsors/3-trackmaven.png b/img/sponsors/3-trackmaven.png new file mode 100644 index 000000000..3880e3707 Binary files /dev/null and b/img/sponsors/3-trackmaven.png differ diff --git a/img/sponsors/3-transcode.png b/img/sponsors/3-transcode.png new file mode 100644 index 000000000..1faad69d9 Binary files /dev/null and b/img/sponsors/3-transcode.png differ diff --git a/img/sponsors/3-triggered_messaging.png b/img/sponsors/3-triggered_messaging.png new file mode 100644 index 000000000..4f8e50635 Binary files /dev/null and b/img/sponsors/3-triggered_messaging.png differ diff --git a/img/sponsors/3-vzzual.png b/img/sponsors/3-vzzual.png new file mode 100644 index 000000000..98edce028 Binary files /dev/null and b/img/sponsors/3-vzzual.png differ diff --git a/img/sponsors/3-wildfish.png b/img/sponsors/3-wildfish.png new file mode 100644 index 000000000..fa13ea703 Binary files /dev/null and b/img/sponsors/3-wildfish.png differ diff --git a/img/travis-status.png b/img/travis-status.png new file mode 100644 index 000000000..fec98cf9b Binary files /dev/null and b/img/travis-status.png differ diff --git a/img/vertical.png b/img/vertical.png new file mode 100644 index 000000000..a85e5c6c5 Binary files /dev/null and b/img/vertical.png differ diff --git a/index.html b/index.html index c2d6c8238..b11934bdd 100644 --- a/index.html +++ b/index.html @@ -1,167 +1,738 @@ - + - - - - George Floyd - + + + + Home - Django REST framework + + + + + - + + -html, -body { - height: 100%; - background-color: #333; -} +
+ +
+
+ + -.nav-masthead .nav-link { - padding: .25rem 0; - font-weight: 700; - color: rgba(255, 255, 255, .5); - background-color: transparent; - border-bottom: .25rem solid transparent; -} +
+
+
+ + +
+
+ +
+ + + + + +

+ + + + + + + + + +

+ +
+

+

Django REST Framework

+ +Black Lives Matter +

BLACK LIVES MATTER

+

+ +
+

+Black Lives Matter · The Equal Justice Initiative · We The Protestors +

+
+

Django REST framework is a powerful and flexible toolkit for building Web APIs.

+

Some reasons you might want to use REST framework:

+ +
+

Funding

+

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

+

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

+ + +
+ +

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, Lights On Software, and Retool.

+
+

Requirements

+

REST framework requires the following:

+
    +
  • Python (3.5, 3.6, 3.7, 3.8)
  • +
  • Django (1.11, 2.0, 2.1, 2.2, 3.0)
  • +
+

We highly recommend and only officially support the latest patch release of +each Python and Django series.

+

The following packages are optional:

+
    +
  • coreapi (1.32.0+) - Schema generation support.
  • +
  • Markdown (3.0.0+) - Markdown support for the browsable API.
  • +
  • Pygments (2.4.0+) - Add syntax highlighting to Markdown processing.
  • +
  • django-filter (1.0.1+) - Filtering support.
  • +
  • django-guardian (1.1.1+) - Object level permissions support.
  • +
+

Installation

+

Install using pip, including any optional packages you want...

+
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 https://github.com/encode/django-rest-framework
+
+

Add 'rest_framework' to your INSTALLED_APPS setting.

+
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 = [
+    ...
+    url(r'^api-auth/', include('rest_framework.urls'))
+]
+
+

Note that the URL path can be whatever you want.

+

Example

+

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 = {
+    # Use Django's standard `django.contrib.auth` permissions,
+    # or allow read-only access for unauthenticated users.
+    'DEFAULT_PERMISSION_CLASSES': [
+        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
+    ]
 }
+
+

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.contrib.auth.models import User
+from rest_framework import routers, serializers, viewsets
 
+# Serializers define the API representation.
+class UserSerializer(serializers.HyperlinkedModelSerializer):
+    class Meta:
+        model = User
+        fields = ['url', 'username', 'email', 'is_staff']
 
-/*
- * Footer
- */
-.mastfoot {
-  color: rgba(255, 255, 255, .5);
-}
-      .bd-placeholder-img {
-        font-size: 1.125rem;
-        text-anchor: middle;
-        -webkit-user-select: none;
-        -moz-user-select: none;
-        -ms-user-select: none;
-        user-select: none;
-      }
+# ViewSets define the view behavior.
+class UserViewSet(viewsets.ModelViewSet):
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
 
-      @media (min-width: 768px) {
-        .bd-placeholder-img-lg {
-          font-size: 3.5rem;
-        }
-      }
-    
-    
-    
-  
-  
-    
-
- -
+# Routers provide an easy way of automatically determining the URL conf. +router = routers.DefaultRouter() +router.register(r'users', UserViewSet) -
-

George Floyd

-

Natosha McDade, Yassin Mohamed, Finan H. Berhe, Sean Reed, Steven Demarco Taylor, Breonna Taylor, Ariane McCree, Terrance Franklin, Miles Hall, Darius Tarver, William Green, Samuel David Mallard, Kwame Jones, De’von Bailey, Christopher Whitfield, Anthony Hill, De’Von Bailey, Eric Logan, Jamarion Robinson, Gregory Hill Jr, JaQuavion Slaton, Ryan Twyman, Brandon Webber, Jimmy Atchison, Willie McCoy, Emantic Fitzgerald Bradford J, D’ettrick Griffin, Jemel Roberson, DeAndre Ballard, Botham Shem Jean, Robert Lawrence White, Anthony Lamar Smith, Ramarley Graham, Manuel Loggins Jr, Trayvon Martin, Wendell Allen, Kendrec McDade, Larry Jackson Jr, Jonathan Ferrell, Jordan Baker, Victor White III, Dontre Hamilton, Eric Garner, John Crawford III, Michael Brown, Ezell Ford, Dante Parker, Kajieme Powell, Laquan McDonald, Akai Gurley, Tamir Rice, Rumain Brisbon, Jerame Reid, Charly Keunang, Tony Robinson, Walter Scott, Freddie Gray, Brendon Glenn, Samuel DuBose, Christian Taylor, Jamar Clark, Mario Woods, Quintonio LeGrier, Gregory Gunn, Akiel Denkins, Alton Sterling, Philando Castile, Terrence Sterling, Terence Crutcher, Keith Lamont Scott, Alfred Olango, Jordan Edwards, Stephon Clark, Danny Ray Thomas, DeJuan Guillory, Patrick Harmon, Jonathan Hart, Maurice Granton, Julius Johnson, Jamee Johnson, Michael Dean...

- -
+# Wire up our API using automatic URL routing. +# Additionally, we include login URLs for the browsable API. +urlpatterns = [ + url(r'^', include(router.urls)), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) +] +
+

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.

+

Development

+

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

+

Support

+

For support please see the REST framework discussion group, try the #restframework channel on irc.freenode.net, search the IRC archives, or raise a question on Stack Overflow, making sure to include the 'django-rest-framework' tag.

+

For priority support please sign up for a professional or premium sponsorship plan.

+

For updates on REST framework development, you may also want to follow the author on Twitter.

+

+

+

Security

+

If you believe you’ve found something in Django REST framework which has security implications, please do not raise the issue in a public forum.

+

Send a description of the issue via email to rest-framework-security@googlegroups.com. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.

+

License

+

Copyright © 2011-present, Encode OSS Ltd. +All rights reserved.

+

Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met:

+
    +
  • +

    Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer.

    +
  • +
  • +

    Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution.

    +
  • +
  • +

    Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission.

    +
  • +
+

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +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.

+ -
+
+
+
+
+
+ + - + + + + + + + + + + + + + + + - + + \ No newline at end of file diff --git a/js/base.js b/js/base.js new file mode 100644 index 000000000..4755f4343 --- /dev/null +++ b/js/base.js @@ -0,0 +1,216 @@ +function getSearchTerm() +{ + var sPageURL = window.location.search.substring(1); + var sURLVariables = sPageURL.split('&'); + for (var i = 0; i < sURLVariables.length; i++) + { + var sParameterName = sURLVariables[i].split('='); + if (sParameterName[0] == 'q') + { + return sParameterName[1]; + } + } +} + +$(document).ready(function() { + + var search_term = getSearchTerm(), + $search_modal = $('#mkdocs_search_modal'), + $keyboard_modal = $('#mkdocs_keyboard_modal'); + + if(search_term){ + $search_modal.modal(); + } + + // make sure search input gets autofocus everytime modal opens. + $search_modal.on('shown.bs.modal', function () { + $search_modal.find('#mkdocs-search-query').focus(); + }); + + // Close search modal when result is selected + // The links get added later so listen to parent + $('#mkdocs-search-results').click(function(e) { + if ($(e.target).is('a')) { + $search_modal.modal('hide'); + } + }); + + // Populate keyboard modal with proper Keys + $keyboard_modal.find('.help.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.help]; + $keyboard_modal.find('.prev.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.previous]; + $keyboard_modal.find('.next.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.next]; + $keyboard_modal.find('.search.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.search]; + + // Keyboard navigation + document.addEventListener("keydown", function(e) { + if ($(e.target).is(':input')) return true; + var key = e.which || e.keyCode || window.event && window.event.keyCode; + var page; + switch (key) { + case shortcuts.next: + page = $('[role="navigation"] a:contains(Next):first').prop('href'); + break; + case shortcuts.previous: + page = $('[role="navigation"] a:contains(Previous):first').prop('href'); + break; + case shortcuts.search: + e.preventDefault(); + $keyboard_modal.modal('hide'); + $search_modal.modal('show'); + $search_modal.find('#mkdocs-search-query').focus(); + break; + case shortcuts.help: + $search_modal.modal('hide'); + $keyboard_modal.modal('show'); + break; + default: break; + } + if (page) { + $keyboard_modal.modal('hide'); + window.location.href = page; + } + }); + + $('table').addClass('table table-striped table-hover'); + + // Improve the scrollspy behaviour when users click on a TOC item. + $(".bs-sidenav a").on("click", function() { + var clicked = this; + setTimeout(function() { + var active = $('.nav li.active a'); + active = active[active.length - 1]; + if (clicked !== active) { + $(active).parent().removeClass("active"); + $(clicked).parent().addClass("active"); + } + }, 50); + }); + +}); + + +$('body').scrollspy({ + target: '.bs-sidebar', + offset: 100 +}); + +/* Prevent disabled links from causing a page reload */ +$("li.disabled a").click(function() { + event.preventDefault(); +}); + +// See https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes +// We only list common keys below. Obscure keys are omited and their use is discouraged. +var keyCodes = { + 8: 'backspace', + 9: 'tab', + 13: 'enter', + 16: 'shift', + 17: 'ctrl', + 18: 'alt', + 19: 'pause/break', + 20: 'caps lock', + 27: 'escape', + 32: 'spacebar', + 33: 'page up', + 34: 'page down', + 35: 'end', + 36: 'home', + 37: '←', + 38: '↑', + 39: '→', + 40: '↓', + 45: 'insert', + 46: 'delete', + 48: '0', + 49: '1', + 50: '2', + 51: '3', + 52: '4', + 53: '5', + 54: '6', + 55: '7', + 56: '8', + 57: '9', + 65: 'a', + 66: 'b', + 67: 'c', + 68: 'd', + 69: 'e', + 70: 'f', + 71: 'g', + 72: 'h', + 73: 'i', + 74: 'j', + 75: 'k', + 76: 'l', + 77: 'm', + 78: 'n', + 79: 'o', + 80: 'p', + 81: 'q', + 82: 'r', + 83: 's', + 84: 't', + 85: 'u', + 86: 'v', + 87: 'w', + 88: 'x', + 89: 'y', + 90: 'z', + 91: 'Left Windows Key / Left ⌘', + 92: 'Right Windows Key', + 93: 'Windows Menu / Right ⌘', + 96: 'numpad 0', + 97: 'numpad 1', + 98: 'numpad 2', + 99: 'numpad 3', + 100: 'numpad 4', + 101: 'numpad 5', + 102: 'numpad 6', + 103: 'numpad 7', + 104: 'numpad 8', + 105: 'numpad 9', + 106: 'multiply', + 107: 'add', + 109: 'subtract', + 110: 'decimal point', + 111: 'divide', + 112: 'f1', + 113: 'f2', + 114: 'f3', + 115: 'f4', + 116: 'f5', + 117: 'f6', + 118: 'f7', + 119: 'f8', + 120: 'f9', + 121: 'f10', + 122: 'f11', + 123: 'f12', + 124: 'f13', + 125: 'f14', + 126: 'f15', + 127: 'f16', + 128: 'f17', + 129: 'f18', + 130: 'f19', + 131: 'f20', + 132: 'f21', + 133: 'f22', + 134: 'f23', + 135: 'f24', + 144: 'num lock', + 145: 'scroll lock', + 186: ';', + 187: '=', + 188: ',', + 189: '‐', + 190: '.', + 191: '?', + 192: '`', + 219: '[', + 220: '\', + 221: ']', + 222: ''', +}; diff --git a/js/bootstrap-2.1.1-min.js b/js/bootstrap-2.1.1-min.js new file mode 100644 index 000000000..e0b220f40 --- /dev/null +++ b/js/bootstrap-2.1.1-min.js @@ -0,0 +1,7 @@ +/** +* Bootstrap.js by @fat & @mdo +* plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-tooltip.js, bootstrap-popover.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-button.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js +* Copyright 2012 Twitter, Inc. +* http://www.apache.org/licenses/LICENSE-2.0.txt +*/ +!function(a){a(function(){a.support.transition=function(){var a=function(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in b)if(a.style[c]!==undefined)return b[c]}();return a&&{end:a}}()})}(window.jQuery),!function(a){var b=function(b,c){this.options=c,this.$element=a(b).delegate('[data-dismiss="modal"]',"click.dismiss.modal",a.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var b=this,c=a.Event("show");this.$element.trigger(c);if(this.isShown||c.isDefaultPrevented())return;a("body").addClass("modal-open"),this.isShown=!0,this.escape(),this.backdrop(function(){var c=a.support.transition&&b.$element.hasClass("fade");b.$element.parent().length||b.$element.appendTo(document.body),b.$element.show(),c&&b.$element[0].offsetWidth,b.$element.addClass("in").attr("aria-hidden",!1).focus(),b.enforceFocus(),c?b.$element.one(a.support.transition.end,function(){b.$element.trigger("shown")}):b.$element.trigger("shown")})},hide:function(b){b&&b.preventDefault();var c=this;b=a.Event("hide"),this.$element.trigger(b);if(!this.isShown||b.isDefaultPrevented())return;this.isShown=!1,a("body").removeClass("modal-open"),this.escape(),a(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),a.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var b=this;a(document).on("focusin.modal",function(a){b.$element[0]!==a.target&&!b.$element.has(a.target).length&&b.$element.focus()})},escape:function(){var a=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(b){b.which==27&&a.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var b=this,c=setTimeout(function(){b.$element.off(a.support.transition.end),b.hideModal()},500);this.$element.one(a.support.transition.end,function(){clearTimeout(c),b.hideModal()})},hideModal:function(a){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;this.$backdrop=a('