diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html index 6b70a6efa..d6a6a869d 100644 --- a/api-guide/authentication/index.html +++ b/api-guide/authentication/index.html @@ -457,7 +457,7 @@ -
Auth needs to be pluggable.
— Jacob Kaplan-Moss, "REST worst practices"
@@ -471,11 +471,11 @@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
+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.userandrequest.authusing the return value of the first class that successfully authenticates.If no class authenticates,
request.userwill be set to an instance ofdjango.contrib.auth.models.AnonymousUser, andrequest.authwill be set toNone.The value of
-request.userandrequest.authfor unauthenticated requests can be modified using theUNAUTHENTICATED_USERandUNAUTHENTICATED_TOKENsettings.Setting the authentication scheme
+Setting the authentication scheme
The default authentication schemes may be set globally, using the
DEFAULT_AUTHENTICATION_CLASSESsetting. For example.-REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( @@ -513,7 +513,7 @@ def example_view(request, format=None): } return Response(content)Unauthorized and Forbidden responses
+Unauthorized and Forbidden responses
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
- HTTP 401 Unauthorized
@@ -522,15 +522,15 @@ def example_view(request, format=None):HTTP 401 responses must always include a
WWW-Authenticateheader, that instructs the client how to authenticate. HTTP 403 responses do not include theWWW-Authenticateheader.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 Deniedresponse will always be used, regardless of the authentication scheme.Apache mod_wsgi specific configuration
+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
WSGIPassAuthorizationdirective 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
+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,
BasicAuthenticationprovides the following credentials.@@ -541,7 +541,7 @@ WSGIPassAuthorization On
WWW-Authenticate: Basic realm="api"Note: If you use
-BasicAuthenticationin production you must ensure that your API is only available overhttps. 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
+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
TokenAuthenticationscheme you'll need to configure the authentication classes to includeTokenAuthentication, and additionally includerest_framework.authtokenin yourINSTALLED_APPSsetting:INSTALLED_APPS = ( @@ -575,7 +575,7 @@ print token.key
Note: If you use
TokenAuthenticationin production you must ensure that your API is only available overhttps.
-Generating Tokens
+Generating Tokens
If you want every user to have an automatically generated Token, you can simply catch the User's
post_savesignal.-from django.conf import settings from django.db.models.signals import post_save @@ -606,7 +606,7 @@ urlpatterns += [{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }Note that the default
-obtain_auth_tokenview explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of theobtain_auth_tokenview, you can do so by overriding theObtainAuthTokenview class, and using that in your url conf instead.Schema migrations
+Schema migrations
The
rest_framework.authtokenapp includes both Django native migrations (for Django versions >1.7) and South migrations (for Django versions <1.7) that will create the authtoken table.
Note: From REST Framework v2.4.0 using South with Django <1.7 requires upgrading South v1.0+
@@ -628,7 +628,7 @@ urlpatterns += [ python manage.py migrate python manage.py createsuperuserSessionAuthentication
+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,
SessionAuthenticationprovides the following credentials.@@ -639,7 +639,7 @@ python manage.py createsuperuser
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,POSTorDELETErequests. 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.
-Custom authentication
+Custom authentication
To implement a custom authentication scheme, subclass
BaseAuthenticationand override the.authenticate(self, request)method. The method should return a two-tuple of(user, auth)if authentication succeeds, orNoneotherwise.In some circumstances instead of returning
None, you may want to raise anAuthenticationFailedexception from the.authenticate()method.Typically the approach you should take is:
@@ -649,7 +649,7 @@ python manage.py createsuperuserYou may also override the
.authenticate_header(self, request)method. If implemented, it should return a string that will be used as the value of theWWW-Authenticateheader in aHTTP 401 Unauthorizedresponse.If the
-.authenticate_header()method is not overridden, the authentication scheme will returnHTTP 403 Forbiddenresponses when an unauthenticated request is denied access.Example
+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 @@ -669,11 +669,11 @@ class ExampleAuthentication(authentication.BaseAuthentication): return (user, None)
-Third party packages
+Third party packages
The following third party packages are also available.
-Django OAuth Toolkit
+Django OAuth Toolkit
The Django OAuth Toolkit package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by Evonove and uses the excellent OAuthLib. The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support.
-Installation & configuration
+Installation & configuration
Install using
pip.@@ -690,31 +690,31 @@ REST_FRAMEWORK = { }pip install django-oauth-toolkitFor more details see the Django REST framework - Getting started documentation.
-Django REST framework OAuth
+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
+Installation & configuration
Install the package using
pip.pip install djangorestframework-oauthFor details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions.
-Digest Authentication
+Digest Authentication
HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. Juan Riaza maintains the djangorestframework-digestauth package which provides HTTP digest authentication support for REST framework.
-Django OAuth2 Consumer
+Django OAuth2 Consumer
The Django OAuth2 Consumer library from Rediker Software is another package that provides OAuth 2.0 support for REST framework. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.
-JSON Web Token Authentication
+JSON Web Token Authentication
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. Blimp maintains the djangorestframework-jwt package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.
-Hawk HTTP Authentication
+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 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 package which provides an easy to use HTTP Signature Authentication mechanism.
-Djoser
+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
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
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
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).
diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html index 477348f4b..a046b17e5 100644 --- a/api-guide/content-negotiation/index.html +++ b/api-guide/content-negotiation/index.html @@ -381,13 +381,13 @@ -Content negotiation
+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
+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.
- More specific media types are given preference to less specific media types.
@@ -408,12 +408,12 @@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
+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, orNoneif 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 aNotAcceptableexception.Example
+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 @@ -431,7 +431,7 @@ class IgnoreClientContentNegotiation(BaseContentNegotiation): """ return (renderers[0], renderers[0].media_type)Setting the content negotiation
+Setting the content negotiation
The default content negotiation class may be set globally, using the
DEFAULT_CONTENT_NEGOTIATION_CLASSsetting. For example, the following settings would use our exampleIgnoreClientContentNegotiationclass.-REST_FRAMEWORK = { 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation', diff --git a/api-guide/exceptions/index.html b/api-guide/exceptions/index.html index df75e30b4..5f3a58678 100644 --- a/api-guide/exceptions/index.html +++ b/api-guide/exceptions/index.html @@ -421,12 +421,12 @@ -Exceptions
+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
+Exception handling in REST framework views
REST framework's views handle various exceptions, and deal with returning appropriate error responses.
The handled exceptions are:
@@ -455,7 +455,7 @@ Content-Length: 94 {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
Custom exception handling
+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, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a
Responseobject, or returnNoneif the exception cannot be handled. If the handler returnsNonethen 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:
@@ -492,8 +492,8 @@ def custom_exception_handler(exc, context):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_REQUESTresponses that are returned by the generic views when serializer validation fails.
-API Reference
-APIException
+API Reference
+APIException
Signature:
APIException()The base class for all exceptions raised inside an
APIViewclass or@api_view.To provide a custom exception, subclass
@@ -504,43 +504,43 @@ class ServiceUnavailable(APIException): status_code = 503 default_detail = 'Service temporarily unavailable, try again later.' -APIExceptionand set the.status_codeand.default_detailproperties on the class.ParseError
+ParseError
Signature:
ParseError(detail=None)Raised if the request contains malformed data when accessing
request.data.By default this exception results in a response with the HTTP status code "400 Bad Request".
-AuthenticationFailed
+AuthenticationFailed
Signature:
AuthenticationFailed(detail=None)Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.
-NotAuthenticated
+NotAuthenticated
Signature:
NotAuthenticated(detail=None)Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.
-PermissionDenied
+PermissionDenied
Signature:
PermissionDenied(detail=None)Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
-NotFound
+NotFound
Signature:
NotFound(detail=None)Raised when a resource does not exists at the given URL. This exception is equivalent to the standard
Http404Django exception.By default this exception results in a response with the HTTP status code "404 Not Found".
-MethodNotAllowed
+MethodNotAllowed
Signature:
MethodNotAllowed(method, detail=None)Raised when an incoming request occurs that does not map to a handler method on the view.
By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
-NotAcceptable
+NotAcceptable
Signature:
NotAcceptable(detail=None)Raised when an incoming request occurs with an
Acceptheader 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
+UnsupportedMediaType
Signature:
UnsupportedMediaType(media_type, detail=None)Raised if there are no parsers that can handle the content type of the request data when accessing
request.data.By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
-Throttled
+Throttled
Signature:
Throttled(wait=None, detail=None)Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
-ValidationError
+ValidationError
Signature:
ValidationError(detail)The
ValidationErrorexception is slightly different from the otherAPIExceptionclasses:diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html index 89936158f..9faad7b27 100644 --- a/api-guide/fields/index.html +++ b/api-guide/fields/index.html @@ -567,7 +567,7 @@ -
Serializer fields
+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.
@@ -576,42 +576,42 @@
Note: The serializer fields are declared in
fields.py, but by convention you should import them usingfrom rest_framework import serializersand refer to fields asserializers.<FieldName>.
-Core arguments
+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_onlyRead-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
Trueto 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
write_onlySet this to
Trueto 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
requiredNormally 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
Falsealso 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.+
allow_null
allow_nullNormally an error will be raised if
Noneis passed to a serializer field. Set this keyword argument toTrueifNoneshould be considered a valid value.Defaults to
-False+
default
defaultIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
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
set_contextmethod, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators.Note that setting a
-defaultvalue implies that the field is not required. Including both thedefaultandrequiredkeyword arguments is invalid and will raise an error.+
source
sourceThe name of the attribute that will be used to populate the field. May be a method that only takes a
selfargument, such asURLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such asEmailField(source='user.email').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
validatorsA 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-inValidationErroris also supported for compatibility with validators defined in the Django codebase or third party Django packages.+
error_messages
error_messagesA dictionary of error codes to error messages.
-+
label
labelA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
-+
help_text
help_textA text string that may be used as a description of the field in HTML form fields or other descriptive elements.
-+
initial
initialA value that should be used for pre-populating the value of HTML form fields.
-+
style
styleA 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. @@ -627,19 +627,19 @@ color_channel = serializers.ChoiceField(For more details see the HTML & Forms documentation.
-Boolean fields
-BooleanField
+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 adefault=Trueoption 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.Corresponds to
django.db.models.fields.BooleanField.Signature:
-BooleanField()NullBooleanField
+NullBooleanField
A boolean representation that also accepts
Noneas a valid value.Corresponds to
django.db.models.fields.NullBooleanField.Signature:
NullBooleanField()
-String fields
-CharField
+String fields
+CharField
A text representation. Optionally validates the text to be shorter than
max_lengthand longer thanmin_length.Corresponds to
django.db.models.fields.CharFieldordjango.db.models.fields.TextField.Signature:
@@ -650,25 +650,25 @@ color_channel = serializers.ChoiceField(CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)trim_whitespace- If set toTruethen leading and trailing whitespace is trimmed. Defaults toTrue.The
-allow_nulloption is also available for string fields, although its usage is discouraged in favor ofallow_blank. It is valid to set bothallow_blank=Trueandallow_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
+EmailField
A text representation, validates the text to be a valid e-mail address.
Corresponds to
django.db.models.fields.EmailFieldSignature:
-EmailField(max_length=None, min_length=None, allow_blank=False)RegexField
+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
regexargument may either be a string, or a compiled python regular expression object.Uses Django's
-django.core.validators.RegexValidatorfor validation.SlugField
+SlugField
A
RegexFieldthat 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
+URLField
A
RegexFieldthat validates the input against a URL matching pattern. Expects fully qualified URLs of the formhttp://<host>/<path>.Corresponds to
django.db.models.fields.URLField. Uses Django'sdjango.core.validators.URLValidatorfor validation.Signature:
-URLField(max_length=200, min_length=None, allow_blank=False)UUIDField
+UUIDField
A field that ensures the input is a valid UUID string. The
to_internal_valuemethod will return auuid.UUIDinstance. On output the field will return a string in the canonical hyphenated format, for example:@@ -683,7 +683,7 @@ color_channel = serializers.ChoiceField( -"de305d54-75b4-431b-adb2-eb6b9e546013"FilePathField
+FilePathField
A field whose choices are limited to the filenames in a certain directory on the filesystem
Corresponds to
django.forms.fields.FilePathField.Signature:
@@ -694,7 +694,7 @@ color_channel = serializers.ChoiceField(FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)allow_files- Specifies whether files in the specified location should be included. Default isTrue. Either this orallow_foldersmust beTrue.- -
allow_folders- Specifies whether folders in the specified location should be included. Default isFalse. Either this orallow_filesmust beTrue.IPAddressField
+IPAddressField
A field that ensures the input is a valid IPv4 or IPv6 string.
Corresponds to
django.forms.fields.IPAddressFieldanddjango.forms.fields.GenericIPAddressField.Signature:
@@ -703,8 +703,8 @@ color_channel = serializers.ChoiceField(IPAddressField(protocol='both', unpack_ipv4=False, **options)unpack_ipv4Unpacks 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
+Numeric fields
+IntegerField
An integer representation.
Corresponds to
django.db.models.fields.IntegerField,django.db.models.fields.SmallIntegerField,django.db.models.fields.PositiveIntegerFieldanddjango.db.models.fields.PositiveSmallIntegerField.Signature:
@@ -712,7 +712,7 @@ color_channel = serializers.ChoiceField(IntegerField(max_value=None, min_value=None)max_valueValidate that the number provided is no greater than this value.- -
min_valueValidate that the number provided is no less than this value.FloatField
+FloatField
A floating point representation.
Corresponds to
django.db.models.fields.FloatField.Signature:
@@ -720,7 +720,7 @@ color_channel = serializers.ChoiceField(FloatField(max_value=None, min_value=None)max_valueValidate that the number provided is no greater than this value.- -
min_valueValidate that the number provided is no less than this value.DecimalField
+DecimalField
A decimal representation, represented in Python by a
Decimalinstance.Corresponds to
django.db.models.fields.DecimalField.Signature:
@@ -731,7 +731,7 @@ color_channel = serializers.ChoiceField(DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)max_valueValidate that the number provided is no greater than this value.- -
min_valueValidate that the number provided is no less than this value.Example usage
+Example usage
To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
@@ -741,8 +741,8 @@ color_channel = serializers.ChoiceField(serializers.DecimalField(max_digits=5, decimal_places=2)This field also takes an optional argument,
coerce_to_string. If set toTruethe representation will be output as a string. If set toFalsethe representation will be left as aDecimalinstance and the final representation will be determined by the renderer.If unset, this will default to the same value as the
COERCE_DECIMAL_TO_STRINGsetting, which isTrueunless set otherwise.
-Date and time fields
-DateTimeField
+Date and time fields
+DateTimeField
A date and time representation.
Corresponds to
django.db.models.fields.DateTimeField.Signature:
@@ -750,11 +750,11 @@ color_channel = serializers.ChoiceField(DateTimeField(format=None, input_formats=None)format- A string representing the output format. If not specified, this defaults to the same value as theDATETIME_FORMATsettings key, which will be'iso-8601'unless set. Setting to a format string indicates thatto_representationreturn values should be coerced to string output. Format strings are described below. Setting this value toNoneindicates that Pythondatetimeobjects should be returned byto_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, theDATETIME_INPUT_FORMATSsetting will be used, which defaults to['iso-8601'].+
DateTimeFieldformat strings.
DateTimeFieldformat 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
Noneis used for the formatdatetimeobjects will be returned byto_representationand the final output representation will determined by the renderer class.In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example:
-2013-01-29T12:34:56.123Z.+
auto_nowandauto_now_addmodel fields.
auto_nowandauto_now_addmodel fields.When using
ModelSerializerorHyperlinkedModelSerializer, note that any model fields withauto_now=Trueorauto_now_add=Truewill use serializer fields that areread_only=Trueby default.If you want to override this behavior, you'll need to declare the
DateTimeFieldexplicitly on the serializer. For example:-class CommentSerializer(serializers.ModelSerializer): @@ -763,7 +763,7 @@ color_channel = serializers.ChoiceField( class Meta: model = CommentDateField
+DateField
A date representation.
Corresponds to
django.db.models.fields.DateFieldSignature:
@@ -771,9 +771,9 @@ color_channel = serializers.ChoiceField(DateField(format=None, input_formats=None)format- A string representing the output format. If not specified, this defaults to the same value as theDATE_FORMATsettings key, which will be'iso-8601'unless set. Setting to a format string indicates thatto_representationreturn values should be coerced to string output. Format strings are described below. Setting this value toNoneindicates that Pythondateobjects should be returned byto_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, theDATE_INPUT_FORMATSsetting will be used, which defaults to['iso-8601'].+
DateFieldformat strings
DateFieldformat stringsFormat 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
+TimeField
A time representation.
Corresponds to
django.db.models.fields.TimeFieldSignature:
@@ -781,9 +781,9 @@ color_channel = serializers.ChoiceField(TimeField(format=None, input_formats=None)format- A string representing the output format. If not specified, this defaults to the same value as theTIME_FORMATsettings key, which will be'iso-8601'unless set. Setting to a format string indicates thatto_representationreturn values should be coerced to string output. Format strings are described below. Setting this value toNoneindicates that Pythontimeobjects should be returned byto_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, theTIME_INPUT_FORMATSsetting will be used, which defaults to['iso-8601'].+
TimeFieldformat strings
TimeFieldformat stringsFormat 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
+DurationField
A Duration representation. Corresponds to
django.db.models.fields.DurationFieldThe
-validated_datafor these fields will contain adatetime.timedeltainstance. @@ -791,8 +791,8 @@ The representation is a string following this format'[DD] [HH:[MM:]]ss[.uNote: This field is only available with Django versions >= 1.8.
Signature:
DurationField()
-Choice selection fields
-ChoiceField
+Choice selection fields
+ChoiceField
A field that can accept a value out of a limited set of choices.
Used by
ModelSerializerto automatically generate fields if the corresponding model field includes achoices=…argument.Signature:
@@ -803,7 +803,7 @@ The representation is a string following this formatChoiceField(choices)'[DD] [HH:[MM:]]ss[.uhtml_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_blankandallow_nullare valid options onChoiceField, although it is highly recommended that you only use one and not both.allow_blankshould be preferred for textual choices, andallow_nullshould be preferred for numeric or other non-textual choices.MultipleChoiceField
+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_valuereturns asetcontaining the selected values.Signature:
MultipleChoiceField(choices)@@ -814,11 +814,11 @@ The representation is a string following this format
'[DD] [HH:[MM:]]ss[.uAs with
ChoiceField, both theallow_blankandallow_nulloptions are valid, although it is highly recommended that you only use one and not both.allow_blankshould be preferred for textual choices, andallow_nullshould be preferred for numeric or other non-textual choices.
-File upload fields
-Parsers and file uploads.
+File upload fields
+Parsers and file uploads.
The
-FileFieldandImageFieldclasses are only suitable for use withMultiPartParserorFileUploadParser. 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
+FileField
A file representation. Performs Django's standard FileField validation.
Corresponds to
django.forms.fields.FileField.Signature:
@@ -827,7 +827,7 @@ Django's regular ImageField +FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)ImageField
An image representation. Validates the uploaded file content as matching a known image format.
Corresponds to
django.forms.fields.ImageField.Signature:
@@ -838,8 +838,8 @@ Django's regular Composite fields -ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)ListField
+Composite fields
+ListField
A field class that validates a list of objects.
Signature:
ListField(child)@@ -855,7 +855,7 @@ Django's regular DictField +
DictField
A field class that validates a dictionary of objects. The keys in
DictFieldare always assumed to be string values.Signature:
DictField(child)@@ -868,15 +868,15 @@ Django's regular JSONField +
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)-
- +
binary- If set toTruethen the field will output and validate a JSON encoded string, rather that a primitive data structure. Defaults toFalse.binary- If set toTruethen the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults toFalse.
-Miscellaneous fields
-ReadOnlyField
+Miscellaneous fields
+ReadOnlyField
A field class that simply returns the value of the field without modification.
This field is used by default with
ModelSerializerwhen including field names that relate to an attribute rather than a model field.Signature:
@@ -886,7 +886,7 @@ Django's regular HiddenField +ReadOnlyField()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:
@@ -894,12 +894,12 @@ Django's regular validators documentation.ModelField
+ModelField
A generic field that can be tied to any arbitrary model field. The
ModelFieldclass 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
ModelSerializerto correspond to custom model field classes.Signature:
ModelField(model_field=<Django ModelField instance>)The
-ModelFieldclass is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate aModelField, 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
+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)@@ -920,12 +920,12 @@ class UserSerializer(serializers.ModelSerializer): return (now() - obj.date_joined).days
-Custom fields
+Custom fields
If you want to create a custom field, you'll need to subclass
Fieldand 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/datetimeorNone. 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 aserializers.ValidationErrorif the data is invalid.Note that the
-WritableFieldclass that was present in version 2.x no longer exists. You should subclassFieldand overrideto_internal_value()if the field supports data input.Examples
+Examples
Let's look at an example of serializing a class that represents an RGB color value:
-class Color(object): """ @@ -962,7 +962,7 @@ class ColorField(serializers.Field): """ return obj.__class__.__name__Raising validation errors
+Raising validation errors
Our
ColorFieldclass above currently does not perform any data validation. To indicate invalid data, we should raise aserializers.ValidationError, like so:def to_internal_value(self, data): @@ -1005,17 +1005,17 @@ def to_internal_value(self, data): return Color(red, green, blue)This style keeps you error messages more cleanly separated from your code, and should be preferred.
-Third party packages
+Third party packages
The following third party packages are also available.
-DRF Compound Fields
+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=Trueoption. 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
+DRF Extra Fields
The drf-extra-fields package provides extra serializer fields for REST framework, including
-Base64ImageFieldandPointFieldclasses.djangrestframework-recursive
+djangrestframework-recursive
the djangorestframework-recursive package provides a
-RecursiveFieldfor serializing and deserializing recursive structuresdjango-rest-framework-gis
+django-rest-framework-gis
The django-rest-framework-gis package provides geographic addons for django rest framework like a
-GeometryFieldfield and a GeoJSON serializer.django-rest-framework-hstore
+django-rest-framework-hstore
The django-rest-framework-hstore package provides an
diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html index 0b17c93f6..957b00f9c 100644 --- a/api-guide/filtering/index.html +++ b/api-guide/filtering/index.html @@ -447,7 +447,7 @@ -HStoreFieldto support django-hstoreDictionaryFieldmodel field.Filtering
+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.
@@ -455,7 +455,7 @@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
GenericAPIViewis 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
+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:
@@ -474,7 +474,7 @@ class PurchaseList(generics.ListAPIView): user = self.request.user return Purchase.objects.filter(purchaser=user) -Filtering against the URL
+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()), @@ -491,7 +491,7 @@ class PurchaseList(generics.ListAPIView): username = self.kwargs['username'] return Purchase.objects.filter(purchaser__username=username)Filtering against query parameters
+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 ashttp://example.com/api/purchases?username=denvercoder9, and filter the queryset only if theusernameparameter is included in the URL:class PurchaseList(generics.ListAPIView): @@ -509,11 +509,11 @@ class PurchaseList(generics.ListAPIView): return queryset
-Generic Filtering
+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.
-
Setting filter backends
+Setting filter backends
The default filter backends may be set globally, using the
DEFAULT_FILTER_BACKENDSsetting. For example.-REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) @@ -531,12 +531,12 @@ class UserListView(generics.ListAPIView): serializer = UserSerializer filter_backends = (filters.DjangoFilterBackend,)Filtering and object lookups
+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.00Overriding the initial queryset
+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, ifProducthad a many-to-many relationship withUser, namedpurchase, you might want to write a view like this:class PurchasedProductsList(generics.ListAPIView): """ @@ -552,8 +552,8 @@ class UserListView(generics.ListAPIView): return user.purchase_set.all()
-API Guide
-DjangoFilterBackend
+API Guide
+DjangoFilterBackend
The
DjangoFilterBackendclass supports highly customizable field filtering, using the django-filter package.To use REST framework's
DjangoFilterBackend, first installdjango-filter.-pip install django-filter @@ -562,8 +562,8 @@ class UserListView(generics.ListAPIView):pip install django-crispy-formsWith crispy forms installed, the browsable API will present a filtering control for
-DjangoFilterBackend, like so:-
Specifying filter fields
++
Specifying filter fields
If all you need is simple equality-based filtering, you can set a
filter_fieldsattribute on the view, or viewset, listing the set of fields you wish to filter against.-class ProductList(generics.ListAPIView): queryset = Product.objects.all() @@ -574,7 +574,7 @@ class UserListView(generics.ListAPIView):This will automatically create a
FilterSetclass for the given fields, and will allow you to make requests such as:-http://example.com/api/products?category=clothing&in_stock=TrueSpecifying a FilterSet
+Specifying a FilterSet
For more advanced filtering requirements you can specify a
FilterSetclass that should be used by the view. For example:import django_filters from myapp.models import Product @@ -640,10 +640,10 @@ class ProductFilter(django_filters.FilterSet):- For Django 1.3 support, make sure to install
django-filterversion 0.5.4, as later versions drop support for 1.3.
-SearchFilter
+SearchFilter
The
SearchFilterclass 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
-SearchFiltercontrol:+
The
SearchFilterclass will only be applied if the view has asearch_fieldsattribute set. Thesearch_fieldsattribute should be a list of names of text type fields on the model, such asCharFieldorTextField.class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -671,9 +671,9 @@ class ProductFilter(django_filters.FilterSet):By default, the search parameter is named
'search', but this may be overridden with theSEARCH_PARAMsetting.For more details, see the Django documentation.
-OrderingFilter
+OrderingFilter
The
-OrderingFilterclass supports simple query parameter controlled ordering of results.+
By default, the query parameter is named
'ordering', but this may by overridden with theORDERING_PARAMsetting.For example, to order users by username:
http://example.com/api/users?ordering=username @@ -684,7 +684,7 @@ class ProductFilter(django_filters.FilterSet):Multiple orderings may also be specified:
-http://example.com/api/users?ordering=account,usernameSpecifying which fields may be ordered against
+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_fieldsattribute on the view, like so:-class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -701,7 +701,7 @@ class ProductFilter(django_filters.FilterSet): filter_backends = (filters.OrderingFilter,) ordering_fields = '__all__'Specifying a default ordering
+Specifying a default ordering
If an
orderingattribute is set on the view, this will be used as the default ordering.Typically you'd instead control this by setting
order_byon the initial queryset, but using theorderingparameter 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): @@ -713,7 +713,7 @@ class ProductFilter(django_filters.FilterSet):The
orderingattribute may be either a string or a list/tuple of strings.
-DjangoObjectPermissionsFilter
+DjangoObjectPermissionsFilter
The
DjangoObjectPermissionsFilteris intended to be used together with thedjango-guardianpackage, with custom'view'permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.If you're using
DjangoObjectPermissionsFilter, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclassDjangoObjectPermissionsand add'view'permissions to theperms_mapattribute.A complete example using both
@@ -746,11 +746,11 @@ class ProductFilter(django_filters.FilterSet):DjangoObjectPermissionsFilterandDjangoObjectPermissionsmight look something like this.For more information on adding
'view'permissions for models, see the relevant section of thedjango-guardiandocumentation, and this blogpost.
-Custom generic filtering
+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
+Example
For example, you might need to restrict users to only being able to see objects they created.
class IsOwnerFilterBackend(filters.BaseFilterBackend): """ @@ -760,17 +760,17 @@ class ProductFilter(django_filters.FilterSet): 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
+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.
-Third party packages
+Third party packages
The following third party packages provide additional filter implementations.
-Django REST framework filters package
+Django REST framework filters package
The django-rest-framework-filters package works together with the
-DjangoFilterBackendclass, 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
+Django REST framework full word search filter
The djangorestframework-word-filter developed as alternative to
-filters.SearchFilterwhich will search full word in text, or exact match.Django URL Filter
+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
diff --git a/api-guide/format-suffixes/index.html b/api-guide/format-suffixes/index.html index 20af14a2d..6867511ea 100644 --- a/api-guide/format-suffixes/index.html +++ b/api-guide/format-suffixes/index.html @@ -375,7 +375,7 @@ -QuerySets.Format suffixes
+Format suffixes
Section 6.2.1 does not say that content negotiation should be used all the time.
@@ -383,7 +383,7 @@ used all the time.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
+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:
@@ -419,7 +419,7 @@ def comment_list(request, format=None):The name of the kwarg used may be modified by using the
FORMAT_SUFFIX_KWARGsetting.Also note that
-format_suffix_patternsdoes not support descending intoincludeURL patterns.Using with
+i18n_patternsUsing with
i18n_patternsIf using the
i18n_patternsfunction provided by Django, as well asformat_suffix_patternsyou should make sure that thei18n_patternsfunction is applied as the final, or outermost function. For example:url patterns = [ … @@ -430,12 +430,12 @@ urlpatterns = i18n_patterns( )
-Query parameter formats
+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
formatquery parameter. For example:http://example.com/organizations/?format=csv.The name of this query parameter can be modified using the
URL_FORMAT_OVERRIDEsetting. Set the value toNoneto disable this behavior.
-Accept headers vs. format suffixes
+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 Acceptheaders 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
diff --git a/api-guide/generic-views/index.html b/api-guide/generic-views/index.html index fbce43e1a..b57a9843b 100644 --- a/api-guide/generic-views/index.html +++ b/api-guide/generic-views/index.html @@ -483,7 +483,7 @@ -Generic views
+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.
@@ -491,7 +491,7 @@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
-APIViewclass, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.Examples
+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 @@ -528,11 +528,11 @@ class UserList(generics.ListCreateAPIView):url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
-API Reference
-GenericAPIView
+API Reference
+GenericAPIView
This class extends REST framework's
APIViewclass, 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
+Attributes
Basic settings:
The following attributes control the basic view behavior.
@@ -551,9 +551,9 @@ class UserList(generics.ListCreateAPIView):
-
filter_backends- A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as theDEFAULT_FILTER_BACKENDSsetting.Methods
+Methods
Base methods:
-+
get_queryset(self)
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
querysetattribute.This method should always be used rather than accessing
self.querysetdirectly, asself.querysetgets 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.
@@ -562,7 +562,7 @@ class UserList(generics.ListCreateAPIView): user = self.request.user return user.accounts.all()+
get_object(self)
get_object(self)Returns an object instance that should be used for detail views. Defaults to using the
lookup_fieldparameter 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:
@@ -577,7 +577,7 @@ class UserList(generics.ListCreateAPIView): return objNote 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 theget_object_or_404lookup.+
filter_queryset(self, queryset)
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): @@ -593,7 +593,7 @@ class UserList(generics.ListCreateAPIView): return queryset+
get_serializer_class(self)
get_serializer_class(self)Returns the class that should be used for the serializer. Defaults to returning the
serializer_classattribute.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:
@@ -602,7 +602,7 @@ class UserList(generics.ListCreateAPIView): return FullAccountSerializer return BasicAccountSerializer+
get_paginate_by(self)
get_paginate_by(self)Returns the page size to use with pagination. By default this uses the
paginate_byattribute, and may be overridden by the client if thepaginate_by_paramattribute is set.You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.
For example:
@@ -645,72 +645,72 @@ class UserList(generics.ListCreateAPIView):filter_queryset(self, queryset)- Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
-Mixins
+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
+ListModelMixin
Provides a
.list(request, *args, **kwargs)method, that implements listing a queryset.If the queryset is populated, this returns a
-200 OKresponse, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.CreateModelMixin
+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 Createdresponse, with a serialized representation of the object as the body of the response. If the representation contains a key namedurl, then theLocationheader of the response will be populated with that value.If the request data provided for creating the object was invalid, a
-400 Bad Requestresponse will be returned, with the error details as the body of the response.RetrieveModelMixin
+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 OKresponse, with a serialized representation of the object as the body of the response. Otherwise it will return a404 Not Found.UpdateModelMixin
+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 theupdatemethod, except that all fields for the update will be optional. This allows support for HTTPPATCHrequests.If an object is updated this returns a
200 OKresponse, with a serialized representation of the object as the body of the response.If an object is created, for example when making a
DELETErequest followed by aPUTrequest to the same URL, this returns a201 Createdresponse, 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 Requestresponse will be returned, with the error details as the body of the response.DestroyModelMixin
+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 Contentresponse, otherwise it will return a404 Not Found.
-Concrete View Classes
+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
+CreateAPIView
Used for create-only endpoints.
Provides a
postmethod handler.Extends: GenericAPIView, CreateModelMixin
-ListAPIView
+ListAPIView
Used for read-only endpoints to represent a collection of model instances.
Provides a
getmethod handler.Extends: GenericAPIView, ListModelMixin
-RetrieveAPIView
+RetrieveAPIView
Used for read-only endpoints to represent a single model instance.
Provides a
getmethod handler.Extends: GenericAPIView, RetrieveModelMixin
-DestroyAPIView
+DestroyAPIView
Used for delete-only endpoints for a single model instance.
Provides a
deletemethod handler.Extends: GenericAPIView, DestroyModelMixin
-UpdateAPIView
+UpdateAPIView
Used for update-only endpoints for a single model instance.
Provides
putandpatchmethod handlers.Extends: GenericAPIView, UpdateModelMixin
-ListCreateAPIView
+ListCreateAPIView
Used for read-write endpoints to represent a collection of model instances.
Provides
getandpostmethod handlers.Extends: GenericAPIView, ListModelMixin, CreateModelMixin
-RetrieveUpdateAPIView
+RetrieveUpdateAPIView
Used for read or update endpoints to represent a single model instance.
Provides
get,putandpatchmethod handlers.Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin
-RetrieveDestroyAPIView
+RetrieveDestroyAPIView
Used for read or delete endpoints to represent a single model instance.
Provides
getanddeletemethod handlers.Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin
-RetrieveUpdateDestroyAPIView
+RetrieveUpdateDestroyAPIView
Used for read-write-delete endpoints to represent a single model instance.
Provides
get,put,patchanddeletemethod handlers.Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
-Customizing the generic views
+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
+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): """ @@ -732,7 +732,7 @@ class UserList(generics.ListCreateAPIView): 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
+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): @@ -744,17 +744,17 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,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
+PUT as create
Prior to version 3.0 the REST framework mixins treated
PUTas either an update or a create operation, depending on if the object already existed or not.Allowing
PUTas 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 returning404responses.Both styles "
PUTas 404" and "PUTas 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
AllowPUTAsCreateMixinclass as a mixin to your views.
-Third party packages
+Third party packages
The following third party packages provide additional generic view implementations.
-Django REST Framework bulk
+Django REST Framework bulk
The django-rest-framework-bulk package implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
-Django Rest Multiple Models
+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.
diff --git a/api-guide/metadata/index.html b/api-guide/metadata/index.html index 3cc9c1b4d..4212a75bf 100644 --- a/api-guide/metadata/index.html +++ b/api-guide/metadata/index.html @@ -381,7 +381,7 @@ -Metadata
+Metadata
[The
@@ -418,7 +418,7 @@ Content-Type: application/json } }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.Setting the metadata scheme
+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' @@ -434,7 +434,7 @@ Content-Type: application/json })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
+Creating schema endpoints
If you have specific requirements for creating schema endpoints that are accessed with regular
GETrequests, you might consider re-using the metadata API for doing so.For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
@list_route(methods=['GET']) @@ -445,10 +445,10 @@ def schema(self, request):There are a couple of reasons that you might choose to take this approach, including that
OPTIONSresponses are not cacheable.
-Custom metadata classes
+Custom metadata classes
If you want to provide a custom metadata class you should override
BaseMetadataand implement thedetermine_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
+Example
The following class could be used to limit the information that is returned to
OPTIONSrequests.-class MinimalMetadata(BaseMetadata): """ diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html index 119b0a4aa..a09f84730 100644 --- a/api-guide/pagination/index.html +++ b/api-guide/pagination/index.html @@ -427,7 +427,7 @@ -Pagination
+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.
@@ -440,14 +440,14 @@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 themixins.ListModelMixinandgenerics.GenericAPIViewclasses for an example.Setting the pagination style
+Setting the pagination style
The default pagination style may be set globally, using the
DEFAULT_PAGINATION_CLASSsettings key. For example, to use the built-in limit/offset pagination, you would do:REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' }You can also set the pagination class on an individual view by using the
-pagination_classattribute. 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
+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 @@ -471,8 +471,8 @@ class StandardResultsSetPagination(PageNumberPagination): }
-API Reference
-PageNumberPagination
+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 @@ -488,7 +488,7 @@ class StandardResultsSetPagination(PageNumberPagination): ] }Setup
+Setup
To enable the
PageNumberPaginationstyle globally, use the following configuration, modifying thePAGE_SIZEas desired:REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', @@ -496,7 +496,7 @@ class StandardResultsSetPagination(PageNumberPagination): }On
-GenericAPIViewsubclasses you may also set thepagination_classattribute to selectPageNumberPaginationon a per-view basis.Configuration
+Configuration
The
PageNumberPaginationclass includes a number of attributes that may be overridden to modify the pagination style.To set these attributes you should override the
PageNumberPaginationclass, and then enable your custom pagination class as above.@@ -508,7 +508,7 @@ class StandardResultsSetPagination(PageNumberPagination):
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 toNoneto disable HTML pagination controls completely. Defaults to"rest_framework/pagination/numbers.html".
-LimitOffsetPagination
+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_sizein other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.Request:
@@ -525,7 +525,7 @@ class StandardResultsSetPagination(PageNumberPagination): ] }Setup
+Setup
To enable the
LimitOffsetPaginationstyle globally, use the following configuration:REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' @@ -533,7 +533,7 @@ class StandardResultsSetPagination(PageNumberPagination):Optionally, you may also set a
PAGE_SIZEkey. If thePAGE_SIZEparameter is also used then thelimitquery parameter will be optional, and may be omitted by the client.On
-GenericAPIViewsubclasses you may also set thepagination_classattribute to selectLimitOffsetPaginationon a per-view basis.Configuration
+Configuration
The
LimitOffsetPaginationclass includes a number of attributes that may be overridden to modify the pagination style.To set these attributes you should override the
LimitOffsetPaginationclass, and then enable your custom pagination class as above.@@ -544,7 +544,7 @@ class StandardResultsSetPagination(PageNumberPagination):
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 toNoneto disable HTML pagination controls completely. Defaults to"rest_framework/pagination/numbers.html".
-CursorPagination
+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:
@@ -552,7 +552,7 @@ class StandardResultsSetPagination(PageNumberPagination):- Provides a consistent pagination view. When used properly
CursorPaginationensures 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
+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 theOrderingFilterfilter class together withCursorPagination. When used withOrderingFilteryou 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:
@@ -564,7 +564,7 @@ class StandardResultsSetPagination(PageNumberPagination):Using an ordering field that does not satisfy these constraints will generally still work, but you'll be loosing some of the benefits of cursor pagination.
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
+Setup
To enable the
CursorPaginationstyle globally, use the following configuration, modifying thePAGE_SIZEas desired:REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', @@ -572,7 +572,7 @@ class StandardResultsSetPagination(PageNumberPagination): }On
-GenericAPIViewsubclasses you may also set thepagination_classattribute to selectCursorPaginationon a per-view basis.Configuration
+Configuration
The
CursorPaginationclass includes a number of attributes that may be overridden to modify the pagination style.To set these attributes you should override the
CursorPaginationclass, and then enable your custom pagination class as above.@@ -582,14 +582,14 @@ class StandardResultsSetPagination(PageNumberPagination):
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 toNoneto disable HTML pagination controls completely. Defaults to"rest_framework/pagination/previous_and_next.html".
-Custom pagination styles
+Custom pagination styles
To create a custom pagination serializer class you should subclass
pagination.BasePaginationand override thepaginate_queryset(self, queryset, request, view=None)andget_paginated_response(self, data)methods:
- The
paginate_querysetmethod is passed the initial queryset and should return an iterable object that contains only the data in the requested page.- The
get_paginated_responsemethod is passed the serialized page data and should return aResponseinstance.Note that the
-paginate_querysetmethod may set state on the pagination instance, that may later be used by theget_paginated_responsemethod.Example
+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): @@ -609,7 +609,7 @@ class StandardResultsSetPagination(PageNumberPagination): }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
-OrderedDictwhen constructing the body of paginated responses, but this is optional.Header based pagination
+Header based pagination
Let's modify the built-in
PageNumberPaginationstyle, so that instead of include the pagination links in the body of the response, we'll instead include aLinkheader, in a similar style to the GitHub API.-class LinkHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): @@ -630,7 +630,7 @@ class StandardResultsSetPagination(PageNumberPagination): return Response(data, headers=headers)Using your custom pagination class
+Using your custom pagination class
To have your custom pagination class be used by default, use the
DEFAULT_PAGINATION_CLASSsetting:-REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', @@ -642,9 +642,9 @@ class StandardResultsSetPagination(PageNumberPagination):
A custom pagination style, using the 'Link' header'
-HTML pagination controls
+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
-PageNumberPaginationandLimitOffsetPaginationclasses display a list of page numbers with previous and next controls. TheCursorPaginationclass displays a simpler style that only displays a previous and next control.Customizing the controls
+Customizing the controls
You can override the templates that render the HTML pagination controls. The two built-in styles are:
- @@ -652,13 +652,13 @@ class StandardResultsSetPagination(PageNumberPagination):
rest_framework/pagination/numbers.htmlProviding 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 = Noneas an attribute on the class. You'll then need to configure yourDEFAULT_PAGINATION_CLASSsettings key to use your custom class as the default pagination style.Low-level API
+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_controlsattribute on the pagination instance. Custom pagination classes should be set toTruein thepaginate_querysetmethod 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
+Third party packages
The following third party packages are also available.
-DRF-extensions
+DRF-extensions
The
diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html index 0888d69f0..01560ad95 100644 --- a/api-guide/parsers/index.html +++ b/api-guide/parsers/index.html @@ -437,7 +437,7 @@ -DRF-extensionspackage includes aPaginateByMaxMixinmixin class that allows your API clients to specify?page_size=maxto obtain the maximum allowed page size.Parsers
+Parsers
Machine interacting web services tend to use more structured formats for sending data than form-encoded, since they're @@ -445,14 +445,14 @@ sending more complex data than simple forms
— 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
+How the parser is determined
The set of valid parsers for a view is always defined as a list of classes. When
request.datais accessed, REST framework will examine theContent-Typeheader 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-Typeheader 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
jsonencoded data using jQuery with the .ajax() method, you should make sure to include thecontentType: 'application/json'setting.
-Setting the parsers
+Setting the parsers
The default set of parsers may be set globally, using the
DEFAULT_PARSER_CLASSESsetting. For example, the following settings would allow only requests withJSONcontent, instead of the default of JSON or form data.REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( @@ -485,29 +485,29 @@ def example_view(request, format=None): return Response({'received data': request.data})
-API Reference
-JSONParser
+API Reference
+JSONParser
Parses
JSONrequest content..media_type:
-application/jsonFormParser
+FormParser
Parses HTML form content.
request.datawill be populated with aQueryDictof data.You will typically want to use both
FormParserandMultiPartParsertogether in order to fully support HTML form data..media_type:
-application/x-www-form-urlencodedMultiPartParser
+MultiPartParser
Parses multipart HTML form content, which supports file uploads. Both
request.datawill be populated with aQueryDict.You will typically want to use both
FormParserandMultiPartParsertogether in order to fully support HTML form data..media_type:
-multipart/form-dataFileUploadParser
+FileUploadParser
Parses raw file upload content. The
request.dataproperty will be a dictionary with a single key'file'containing the uploaded file.If the view used with
FileUploadParseris called with afilenameURL keyword argument, then that argument will be used as the filename. If it is called without afilenameURL keyword argument, then the client must set the filename in theContent-DispositionHTTP header. For exampleContent-Disposition: attachment; filename=upload.jpg..media_type:
-*/*Notes:
+Notes:
-
- The
FileUploadParseris 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 theMultiPartParserparser instead.- Since this parser's
media_typematches any content type,FileUploadParsershould generally be the only parser set on an API view.FileUploadParserrespects Django's standardFILE_UPLOAD_HANDLERSsetting, and therequest.upload_handlersattribute. See the Django documentation for more details.Basic usage example:
+Basic usage example:
class FileUploadView(views.APIView): parser_classes = (FileUploadParser,) @@ -519,19 +519,19 @@ def example_view(request, format=None): return Response(status=204)
-Custom parsers
+Custom parsers
To implement a custom parser, you should override
BaseParser, set the.media_typeproperty, 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.dataproperty.The arguments passed to
-.parse()are:stream
+stream
A stream-like object representing the body of the request.
-media_type
+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'smedia_typeattribute, and may include media type parameters. For example"text/plain; charset=utf-8".parser_context
+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
+Example
The following is an example plaintext parser that will populate the
request.dataproperty with a string representing the body of the request.class PlainTextParser(BaseParser): """ @@ -546,11 +546,11 @@ def example_view(request, format=None): return stream.read()
-Third party packages
+Third party packages
The following third party packages are also available.
-YAML
+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
+Installation & configuration
Install using pip.
@@ -564,9 +564,9 @@ def example_view(request, format=None): ), }$ pip install djangorestframework-yamlXML
+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
+Installation & configuration
Install using pip.
@@ -580,9 +580,9 @@ def example_view(request, format=None): ), } -$ pip install djangorestframework-xmlMessagePack
+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
+CamelCase JSON
djangorestframework-camel-case provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by Vitaly Babiy.
diff --git a/api-guide/permissions/index.html b/api-guide/permissions/index.html index 70acd5d6a..3b3420af3 100644 --- a/api-guide/permissions/index.html +++ b/api-guide/permissions/index.html @@ -437,7 +437,7 @@ -Permissions
+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
@@ -447,7 +447,7 @@Permissions are used to grant or deny access 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 the
IsAuthenticatedclass 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
-IsAuthenticatedOrReadOnlyclass in REST framework.How permissions are determined
+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
@@ -457,7 +457,7 @@ If any permission check fails anexceptions.PermissionDeniedorexceptions.NotAuthenticatedexception will be raised, and the main body of the view will not run.exceptions.PermissionDeniedorThe request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticateheaders. — An HTTP 403 Forbidden response will be returned.- The request was not successfully authenticated, and the highest priority authentication class does use
-WWW-Authenticateheaders. — An HTTP 401 Unauthorized response, with an appropriateWWW-Authenticateheader will be returned.Object level permissions
+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
@@ -470,10 +470,10 @@ or if you override the.get_object()is called. As with view level permissions, anexceptions.PermissionDeniedexception will be raised if the user is not allowed to act on the given object.get_objectmethod on a generic view, then yo self.check_object_permissions(self.request, obj) return obj -Limitations of object level permissions
+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
+Setting the permission policy
The default permission policy may be set globally, using the
DEFAULT_PERMISSION_CLASSESsetting. For example.REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( @@ -515,20 +515,20 @@ def example_view(request, format=None): return Response(content)
-API Reference
-AllowAny
+API Reference
+AllowAny
The
AllowAnypermission 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
+IsAuthenticated
The
IsAuthenticatedpermission 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
+IsAdminUser
The
IsAdminUserpermission class will deny permission to any user, unlessuser.is_staffisTruein 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
+IsAuthenticatedOrReadOnly
The
IsAuthenticatedOrReadOnlywill 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,HEADorOPTIONS.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
+DjangoModelPermissions
This permission class ties into Django's standard
django.contrib.authmodel permissions. This permission must only be applied to views that has a.querysetproperty set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.
- @@ -537,13 +537,13 @@ def example_view(request, format=None):
POSTrequests require the user to have theaddpermission on the model.The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a
viewmodel permission forGETrequests.To use custom model permissions, override
-DjangoModelPermissionsand set the.perms_mapproperty. Refer to the source code for details.Using with views that do not include a
+querysetattribute.Using with views that do not include a
querysetattribute.If you're using this permission with a view that uses an overridden
get_queryset()method there may not be aquerysetattribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example:-queryset = User.objects.none() # Required for DjangoModelPermissionsDjangoModelPermissionsOrAnonReadOnly
+DjangoModelPermissionsOrAnonReadOnly
Similar to
-DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.DjangoObjectPermissions
+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.querysetproperty 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.@@ -557,7 +557,7 @@ def example_view(request, format=None):
Note: If you need object level
viewpermissions forGET,HEADandOPTIONSrequests, you'll want to consider also adding theDjangoObjectPermissionsFilterclass to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
-Custom permissions
+Custom permissions
To implement a custom permission, override
BasePermissionand implement either, or both, of the following methods:
- @@ -582,7 +582,7 @@ class CustomerAccessPermission(permissions.BasePermission): def has_permission(self, request, view): ... -
.has_permission(self, request, view)Examples
+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 @@ -615,13 +615,13 @@ class BlacklistPermission(permissions.BasePermission):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 appropriateAPIExceptionif 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
+Third party packages
The following third party packages are also available.
-Composed Permissions
+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
+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
+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 retrive per user.
diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html index 227b9839a..8e00e029e 100644 --- a/api-guide/relations/index.html +++ b/api-guide/relations/index.html @@ -469,7 +469,7 @@ -Serializer relations
+Serializer relations
Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
@@ -479,7 +479,7 @@ Good programmers worry about data structures and their relationships.
Note: The relational fields are declared in
relations.py, but by convention you should import them from theserializersmodule, usingfrom rest_framework import serializersand refer to fields asserializers.<FieldName>.
-Inspecting relationships.
+Inspecting relationships.
When using the
ModelSerializerclass, 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 @@ -490,7 +490,7 @@ AccountSerializer(): name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all())API Reference
+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) @@ -509,7 +509,7 @@ class Track(models.Model): def __unicode__(self): return '%d: %s' % (self.order, self.title)StringRelatedField
+StringRelatedField
StringRelatedFieldmay be used to represent the target of the relationship using its__unicode__method.For example, the following serializer.
class AlbumSerializer(serializers.ModelSerializer): @@ -536,7 +536,7 @@ class Track(models.Model):-
many- If applied to a to-many relationship, you should set this argument toTrue.PrimaryKeyRelatedField
+PrimaryKeyRelatedField
PrimaryKeyRelatedFieldmay be used to represent the target of the relationship using its primary key.For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer): @@ -566,7 +566,7 @@ class Track(models.Model):allow_null- If set toTrue, the field will accept values ofNoneor the empty string for nullable relationships. Defaults toFalse.- -
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
HyperlinkedRelatedFieldmay be used to represent the target of the relationship using a hyperlink.For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer): @@ -608,7 +608,7 @@ class Track(models.Model):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 aslookup_field.- -
format- If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using theformatargument.SlugRelatedField
+SlugRelatedField
SlugRelatedFieldmay be used to represent the target of the relationship using a field on the target.For example, the following serializer:
-class AlbumSerializer(serializers.ModelSerializer): @@ -643,7 +643,7 @@ class Track(models.Model):many- If applied to a to-many relationship, you should set this argument toTrue.- -
allow_null- If set toTrue, the field will accept values ofNoneor the empty string for nullable relationships. Defaults toFalse.HyperlinkedIdentityField
+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') @@ -668,10 +668,10 @@ class Track(models.Model):format- If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using theformatargument.
-Nested relationships
+Nested relationships
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=Trueflag to the serializer field.Example
+Example
For example, the following serializer:
-class TrackSerializer(serializers.ModelSerializer): class Meta: @@ -706,7 +706,7 @@ class AlbumSerializer(serializers.ModelSerializer): ], }Writable nested serializers
+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/orupdate()methods in order to explicitly specify how the child relationships should be saved.-class TrackSerializer(serializers.ModelSerializer): class Meta: @@ -742,10 +742,10 @@ True >>> serializer.save() <Album: Album object>Custom relational fields
+Custom relational fields
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 thevalueargument, and should return the representation that should be used to serialize the target. Thevalueargument 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.Example
+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 @@ -774,7 +774,7 @@ class AlbumSerializer(serializers.ModelSerializer): }
-Custom hyperlinked fields
+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)
@@ -785,7 +785,7 @@ attributes are not configured to correctly match the URL conf.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
-ObjectDoesNotExistexception.Example
+Example
Say we have a URL for a customer object that takes two keyword arguments, like so:
@@ -804,7 +804,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField): 'organization_slug': obj.organization.slug, 'customer_pk': obj.pk } - return reverse(view_name, url_kwargs, request=request, format=format) + return reverse(view_name, kwargs=url_kwargs, request=request, format=format) def get_object(self, view_name, view_args, view_kwargs): lookup_kwargs = { @@ -816,20 +816,20 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):/api/<organization_slug>/customers/<customer_pk>/Note that if you wanted to use this style together with the generic views then you'd also need to override
.get_objecton 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
+querysetargumentFurther notes
+The
querysetargumentThe
querysetargument 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
querysetargument if aModelSerializerclass was being used.This behavior is now replaced with always using an explicit
querysetargument for writable relational fields.Doing so reduces the amount of hidden 'magic' that
-ModelSerializerprovides, makes the behavior of the field more clear, and ensures that it is trivial to move between using theModelSerializershortcut, or using fully explicitSerializerclasses.Customizing the HTML display
+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 thechoicesproperty. These choices are used to populate select HTML inputs in the browsable API.To provide customized representations for such inputs, override
display_value()of aRelatedFieldsubclass. 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
+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:
@@ -844,7 +844,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField): style={'base_template': 'input.html'} )Reverse relations
+Reverse relations
Note that reverse relationships are not automatically included by the
ModelSerializerandHyperlinkedModelSerializerclasses. To include a reverse relationship, you must explicitly add it to the fields list. For example:class AlbumSerializer(serializers.ModelSerializer): class Meta: @@ -861,7 +861,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField): fields = ('track_set', ...)See the Django documentation on reverse relationships for more details.
-Generic relationships
+Generic relationships
If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.
For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
class TaggedItem(models.Model): @@ -927,16 +927,16 @@ class Note(models.Model):Note that reverse generic keys, expressed using the
GenericRelationfield, 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
+ManyToManyFields with a Through Model
By default, relational fields that target a
ManyToManyFieldwith athroughmodel specified are set to read-only.If you explicitly specify a relational field pointing to a
ManyToManyFieldwith a through model, be sure to setread_onlytoTrue.
-Third Party Packages
+Third Party Packages
The following third party packages are also available.
-DRF Nested Routers
+DRF Nested Routers
The drf-nested-routers package provides routers and relationship fields for working with nested resources.
diff --git a/api-guide/renderers/index.html b/api-guide/renderers/index.html index 7c11600e0..163ca3aa7 100644 --- a/api-guide/renderers/index.html +++ b/api-guide/renderers/index.html @@ -495,17 +495,17 @@ -Renderers
+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.
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
+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
Acceptheader, 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 URLhttp://example.com/api/users_count.jsonmight be an endpoint that always returns JSON data.For more information see the documentation on content negotiation.
-Setting the renderers
+Setting the renderers
The default set of renderers may be set globally, using the
DEFAULT_RENDERER_CLASSESsetting. For example, the following settings would useJSONas the main media type and also include the self describing API.-REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( @@ -543,13 +543,13 @@ def user_count_view(request, format=None): content = {'user_count': user_count} return Response(content)Ordering of renderer classes
+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 anAcceptheader 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
JSONRendereryour default renderer, in order to sendJSONresponses to clients that do not specify anAcceptheader.If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making
TemplateHTMLRendereryour default renderer, in order to play nicely with older browsers that send broken accept headers.
-API Reference
-JSONRenderer
+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} @@ -564,7 +564,7 @@ def user_count_view(request, format=None):.media_type:
application/json.format:
'.json'.charset:
-NoneTemplateHTMLRenderer
+TemplateHTMLRenderer
Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the
Responsedoes not need to be serialized. Also, unlike other renderers, you may want to include atemplate_nameargument when creating theResponse.The TemplateHTMLRenderer will create a
@@ -592,7 +592,7 @@ Unlike other renderers, the data passed to theRequestContext, using theresponse.dataas the context dict, and determine a template name to use to render the context.Responsedoes not ne.format:
'.html'.charset:
utf-8See also:
-StaticHTMLRendererStaticHTMLRenderer
+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',)) @@ -606,7 +606,7 @@ def simple_html_view(request):.format:
'.html'.charset:
utf-8See also:
-TemplateHTMLRendererBrowsableAPIRenderer
+BrowsableAPIRenderer
Renders data into HTML for the Browsable API:
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.
@@ -614,13 +614,13 @@ def simple_html_view(request):.format:
'.api'.charset:
utf-8.template:
-'rest_framework/api.html'Customizing BrowsableAPIRenderer
+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 theget_default_renderer()method. For example:-class CustomBrowsableAPIRenderer(BrowsableAPIRenderer): def get_default_renderer(self, view): return JSONRenderer()AdminRenderer
+AdminRenderer
Renders data into HTML for an admin-like display:
This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
@@ -629,7 +629,7 @@ def simple_html_view(request):.format:
'.admin'.charset:
utf-8.template:
-'rest_framework/admin.html'HTMLFormRenderer
+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_formtemplate tag.-{% load rest_framework %} @@ -645,25 +645,25 @@ def simple_html_view(request):.format:
'.form'.charset:
utf-8.template:
-'rest_framework/horizontal/form.html'MultiPartRenderer
+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
+Custom renderers
To implement a custom renderer, you should override
BaseRenderer, set the.media_typeand.formatproperties, 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
dataThe request data, as set by the
-Response()instantiation.+
media_type=None
media_type=NoneOptional. 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'smedia_typeattribute, and may include media type parameters. For example"application/json; nested=true".+
renderer_context=None
renderer_context=NoneOptional. 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
+Example
The following is an example plaintext renderer that will return a response with the
dataparameter as the content of the response.-from django.utils.encoding import smart_unicode from rest_framework import renderers @@ -676,7 +676,7 @@ class PlainTextRenderer(renderers.BaseRenderer): def render(self, data, media_type=None, renderer_context=None): return data.encode(self.charset)Setting the character set
+Setting the character set
By default renderer classes are assumed to be using the
UTF-8encoding. To use a different encoding, set thecharsetattribute on the renderer.class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' @@ -699,7 +699,7 @@ class PlainTextRenderer(renderers.BaseRenderer): return data
-Advanced renderer usage
+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.
@@ -707,7 +707,7 @@ class PlainTextRenderer(renderers.BaseRenderer):- 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 theAcceptheader to vary the encoding of the response.Varying behaviour by media type
+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_rendererto determine the negotiated renderer that will be used for the response.For example:
-@api_view(('GET',)) @@ -731,17 +731,17 @@ def list_users(request): data = serializer.data return Response(data)Underspecifying the media type
+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_typevalue such asimage/*, 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_typeattribute. For example:-return Response(data, content_type='image/png')Designing your media types
+Designing your media types
For the purposes of many Web APIs, simple
JSONresponses 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
+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
Http404orPermissionDeniedexception, or a subclass ofAPIException.If you're using either the
TemplateHTMLRendereror theStaticHTMLRendererand 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.
@@ -753,11 +753,11 @@ In this case you can underspecify the media types it should respond to, by usingTemplates will render with a
RequestContextwhich includes thestatus_codeanddetailskeys.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
+Third party packages
The following third party packages are also available.
-YAML
+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
+Installation & configuration
Install using pip.
@@ -771,9 +771,9 @@ In this case you can underspecify the media types it should respond to, by using ), }$ pip install djangorestframework-yamlXML
+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
+Installation & configuration
Install using pip.
@@ -787,13 +787,13 @@ In this case you can underspecify the media types it should respond to, by using ), }$ pip install djangorestframework-xmlJSONP
+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
jsonpapproach is essentially a browser hack, and is only appropriate for globally readable API endpoints, whereGETrequests are unauthenticated and do not require any user permissions.
-Installation & configuration
+Installation & configuration
Install using pip.
@@ -804,15 +804,15 @@ In this case you can underspecify the media types it should respond to, by using ), }$ pip install djangorestframework-jsonpMessagePack
+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.
-CSV
+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
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
+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)
+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
diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html index c7971fdd5..384d0b91f 100644 --- a/api-guide/requests/index.html +++ b/api-guide/requests/index.html @@ -437,16 +437,16 @@ -.xlsand.xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project.Requests
+Requests
If you're doing REST-based web service stuff ... you should ignore request.POST.
— Malcom Tredinnick, Django developers group
REST framework's
Requestclass extends the standardHttpRequest, adding support for REST framework's flexible request parsing and request authentication.
-Request parsing
+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
+.data
request.datareturns the parsed content of the request body. This is similar to the standardrequest.POSTandrequest.FILESattributes except that:
- It includes all parsed content, including file and non-file inputs.
@@ -454,60 +454,60 @@- 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
+.query_params
request.query_paramsis a more correctly named synonym forrequest.GET.For clarity inside your code, we recommend using
-request.query_paramsinstead of the Django's standardrequest.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not justGETrequests..parsers
+.parsers
The
APIViewclass or@api_viewdecorator will ensure that this property is automatically set to a list ofParserinstances, based on theparser_classesset on the view or based on theDEFAULT_PARSER_CLASSESsetting.You won't typically need to access this property.
Note: If a client sends malformed content, then accessing
request.datamay raise aParseError. By default REST framework'sAPIViewclass or@api_viewdecorator will catch the error and return a400 Bad Requestresponse.If a client sends a request with a content-type that cannot be parsed then a
UnsupportedMediaTypeexception will be raised, which by default will be caught and return a415 Unsupported Media Typeresponse.
-Content negotiation
+Content negotiation
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.
-.accepted_renderer
+.accepted_renderer
The renderer instance what was selected by the content negotiation stage.
-.accepted_media_type
+.accepted_media_type
A string representing the media type that was accepted by the content negotiation stage.
-Authentication
+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
+.user
request.usertypically returns an instance ofdjango.contrib.auth.models.User, although the behavior depends on the authentication policy being used.If the request is unauthenticated the default value of
request.useris an instance ofdjango.contrib.auth.models.AnonymousUser.For more details see the authentication documentation.
-.auth
+.auth
request.authreturns any additional authentication context. The exact behavior ofrequest.authdepends 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.authisNone.For more details see the authentication documentation.
-.authenticators
+.authenticators
The
APIViewclass or@api_viewdecorator will ensure that this property is automatically set to a list ofAuthenticationinstances, based on theauthentication_classesset on the view or based on theDEFAULT_AUTHENTICATORSsetting.You won't typically need to access this property.
-Browser enhancements
+Browser enhancements
REST framework supports a few browser enhancements such as browser-based
-PUT,PATCHandDELETEforms..method
+.method
request.methodreturns the uppercased string representation of the request's HTTP method.Browser-based
PUT,PATCHandDELETEforms are transparently supported.For more information see the browser enhancements documentation.
-.content_type
+.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_typeproperty in preference to usingrequest.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
+.stream
request.streamreturns a stream representing the content of the request body.You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.
If you do need to access the raw content directly, you should use the
.streamproperty in preference to usingrequest.content, as it provides transparent support for browser-based non-form content.For more information see the browser enhancements documentation.
-Standard HttpRequest attributes
+Standard HttpRequest attributes
As REST framework's
Requestextends Django'sHttpRequest, all the other standard attributes and methods are also available. For example therequest.METAandrequest.sessiondictionaries are available as normal.Note that due to implementation reasons the
diff --git a/api-guide/responses/index.html b/api-guide/responses/index.html index c60c0124d..c68f18618 100644 --- a/api-guide/responses/index.html +++ b/api-guide/responses/index.html @@ -417,7 +417,7 @@ -Requestclass does not inherit fromHttpRequestclass, but instead extends the class using composition.Responses
+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.
@@ -427,8 +427,8 @@There's no requirement for you to use the
Responseclass, you can also return regularHttpResponseorStreamingHttpResponseobjects from your views if required. Using theResponseclass 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
APIViewclass or@api_viewfunction for views that returnResponseobjects. 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()
+Creating responses
+Response()
Signature:
Response(data, status=None, template_name=None, headers=None, content_type=None)Unlike regular
HttpResponseobjects, you do not instantiateResponseobjects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.The renderers used by the
@@ -442,31 +442,31 @@Responseclass cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating theResponseobject.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
+Attributes
+.data
The unrendered content of a
-Requestobject..status_code
+.status_code
The numeric status code of the HTTP response.
-.content
+.content
The rendered content of the response. The
-.render()method must have been called before.contentcan be accessed..template_name
+.template_name
The
-template_name, if supplied. Only required ifHTMLRendereror some other custom template renderer is the accepted renderer for the response..accepted_renderer
+.accepted_renderer
The renderer instance that will be used to render the response.
Set automatically by the
-APIViewor@api_viewimmediately before the response is returned from the view..accepted_media_type
+.accepted_media_type
The media type that was selected by the content negotiation stage.
Set automatically by the
-APIViewor@api_viewimmediately before the response is returned from the view..renderer_context
+.renderer_context
A dictionary of additional context information that will be passed to the renderer's
.render()method.Set automatically by the
APIViewor@api_viewimmediately before the response is returned from the view.
-Standard HttpResponse attributes
+Standard HttpResponse attributes
The
Responseclass extendsSimpleTemplateResponse, 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()
+.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 theaccepted_rendererinstance.You won't typically need to call
diff --git a/api-guide/reverse/index.html b/api-guide/reverse/index.html index 236aebe21..574d32fd2 100644 --- a/api-guide/reverse/index.html +++ b/api-guide/reverse/index.html @@ -371,7 +371,7 @@ -.render()yourself, as it's handled by Django's standard response cycle.Returning URLs
+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
@@ -386,7 +386,7 @@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
+reverse
Signature:
reverse(viewname, *args, **kwargs)Has the same behavior as
django.core.urlresolvers.reverse, except that it returns a fully qualified URL, using the request to determine the host and port.You should include the request as a keyword argument to the function, for example:
@@ -403,7 +403,7 @@ class APIRootView(APIView): } return Response(data)reverse_lazy
+reverse_lazy
Signature:
reverse_lazy(viewname, *args, **kwargs)Has the same behavior as
django.core.urlresolvers.reverse_lazy, except that it returns a fully qualified URL, using the request to determine the host and port.As with the
diff --git a/api-guide/routers/index.html b/api-guide/routers/index.html index d01f9a40e..381e54b37 100644 --- a/api-guide/routers/index.html +++ b/api-guide/routers/index.html @@ -417,14 +417,14 @@ -reversefunction, you should include the request as a keyword argument to the function, for example:Routers
+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.
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
+Usage
Here's an example of a simple URL conf, that uses
SimpleRouter.from rest_framework import routers @@ -456,7 +456,7 @@ urlpatterns = router.urlsThis means you'll need to explicitly set the
base_nameargument when registering the viewset, as it could not be automatically determined from the model name.
-Using
+includewith routersUsing
includewith routersThe
.urlsattribute 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.urlsto a list of existing views…router = routers.SimpleRouter() @@ -482,7 +482,7 @@ urlpatterns += router.urls ]If using namespacing with hyperlinked serializers you'll also need to ensure that any
-view_nameparameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such asview_name='api:user-detail'for serializer fields hyperlinked to the user detail view.Extra link and actions
+Extra link and actions
Any methods on the viewset decorated with
@detail_routeor@list_routewill also be routed. For example, given a method like this on theUserViewSetclass:from myapp.permissions import IsAdminOrIsSelf @@ -516,8 +516,8 @@ class UserViewSet(ModelViewSet):- URL pattern:
^users/{pk}/change-password/$Name:'user-change-password'For more information see the viewset documentation on marking extra actions for routing.
-API Guide
-SimpleRouter
+API Guide
+SimpleRouter
This router includes routes for the standard set of
list,create,retrieve,update,partial_updateanddestroyactions. The viewset can also mark additional methods to be routed, using the@detail_routeor@list_routedecorators.
@@ -541,7 +541,7 @@ This behavior can be modified by setting the URL Style HTTP Method Action URL Name trailing_slashargumen lookup_field = 'my_model_id' lookup_value_regex = '[0-9a-f]{32}' -DefaultRouter
+DefaultRouter
This router is similar to
SimpleRouteras 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.jsonstyle format suffixes.
@@ -559,7 +559,7 @@ This behavior can be modified by setting the URL Style HTTP Method Action URL Name trailing_slashargumenAs with
SimpleRouterthe trailing slashes on the URL routes can be removed by setting thetrailing_slashargument toFalsewhen instantiating the router.-router = DefaultRouter(trailing_slash=False)Custom Routers
+Custom Routers
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
The simplest way to implement a custom router is to subclass one of the existing router classes. The
.routesattribute is used to template the URL patterns that will be mapped to each viewset. The.routesattribute is a list ofRoutenamed tuples.The arguments to the
@@ -575,14 +575,14 @@ This behavior can be modified by setting theRoutenamed tuple are:trailing_slashargumen{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
-suffixargument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.Customizing dynamic routes
+Customizing dynamic routes
You can also customize how the
@list_routeand@detail_routedecorators are routed. To route either or both of these decorators, include aDynamicListRouteand/orDynamicDetailRoutenamed tuple in the.routeslist.The arguments to
DynamicListRouteandDynamicDetailRouteare:url: A string representing the URL to be routed. May include the same format strings as
Route, and additionally accepts the{methodname}and{methodnamehyphen}format strings.name: The name of the URL as used in
reversecalls. May include the following format strings:{basename},{methodname}and{methodnamehyphen}.initkwargs: A dictionary of any additional arguments that should be passed when instantiating the view.
-Example
+Example
The following example will only route to the
listandretrieveactions, and does not use the trailing slash convention.from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter @@ -644,21 +644,21 @@ urlpatterns = router.urlsFor another example of setting the
-.routesattribute, see the source code for theSimpleRouterclass.Advanced custom routers
+Advanced custom routers
If you want to provide totally custom behavior, you can override
BaseRouterand override theget_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 theself.registryattribute.You may also want to override the
-get_default_base_name(self, viewset)method, or else always explicitly set thebase_nameargument when registering your viewsets with the router.Third Party Packages
+Third Party Packages
The following third party packages are also available.
-DRF Nested Routers
+DRF Nested Routers
The drf-nested-routers package provides routers and relationship fields for working with nested resources.
-ModelRouter (wq.db.rest)
+ModelRouter (wq.db.rest)
The wq.db package provides an advanced ModelRouter class (and singleton instance) that extends
DefaultRouterwith aregister_model()API. Much like Django'sadmin.site.register, the only required argument torest.router.register_modelis 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
+DRF-extensions
The
diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html index 1e029642d..9a2084b4b 100644 --- a/api-guide/serializers/index.html +++ b/api-guide/serializers/index.html @@ -543,7 +543,7 @@ -DRF-extensionspackage provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.Serializers
+Serializers
Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it @@ -552,7 +552,7 @@ will take some serious design work.
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,XMLor 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
-FormandModelFormclasses. We provide aSerializerclass which gives you a powerful, generic way to control the output of your responses, as well as aModelSerializerclass which provides a useful shortcut for creating serializers that deal with model instances and querysets.Declaring Serializers
+Declaring Serializers
Let's start by creating a simple object we can use for example purposes:
-from datetime import datetime @@ -573,7 +573,7 @@ class CommentSerializer(serializers.Serializer): content = serializers.CharField(max_length=200) created = serializers.DateTimeField()Serializing objects
+Serializing objects
We can now use
CommentSerializerto serialize a comment, or list of comments. Again, using theSerializerclass looks a lot like using aFormclass.-serializer = CommentSerializer(comment) serializer.data @@ -586,7 +586,7 @@ json = JSONRenderer().render(serializer.data) json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'Deserializing objects
+Deserializing objects
Deserialization is similar. First we parse a stream into Python native datatypes...
-from django.utils.six import BytesIO from rest_framework.parsers import JSONParser @@ -601,7 +601,7 @@ serializer.is_valid() serializer.validated_data # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}Saving instances
+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()andupdate()methods. For example:class CommentSerializer(serializers.Serializer): email = serializers.EmailField() @@ -639,13 +639,13 @@ serializer = CommentSerializer(data=data) 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()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_dataargument when.create()or.update()are called.Overriding
+.save()directly.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:
@@ -659,7 +659,7 @@ serializer = CommentSerializer(comment, data=data) send_email(from=email, message=message)Note that in the case above we're now having to access the serializer
-.validated_dataproperty directly.Validation
+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.errorsproperty will contain a dictionary representing the resulting error messages. For example:serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() @@ -669,13 +669,13 @@ serializer.errorsEach 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_errorskey may also be present, and will list any general validation errors. The name of thenon_field_errorskey may be customized using theNON_FIELD_ERRORS_KEYREST 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
+Raising an exception on invalid data
The
.is_valid()method takes an optionalraise_exceptionflag that will cause it to raise aserializers.ValidationErrorexception 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 Requestresponses by default.-# Return a 400 response if the data was invalid. serializer.is_valid(raise_exception=True)Field-level validation
+Field-level validation
You can specify custom field-level validation by adding
.validate_<field_name>methods to yourSerializersubclass. 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
@@ -696,7 +696,7 @@ class BlogPostSerializer(serializers.Serializer):validate_<field_name>methods should return the validated value or raise aserializers.ValidationError. For example:
Note: If your
<field_name>is declared on your serializer with the parameterrequired=Falsethen this validation step will not take place if the field is not included.
-Object-level validation
+Object-level validation
To do any other validation that requires access to multiple fields, add a method called
.validate()to yourSerializersubclass. This method takes a single argument, which is a dictionary of field values. It should raise aValidationErrorif necessary, or just return the validated values. For example:-from rest_framework import serializers @@ -713,7 +713,7 @@ class EventSerializer(serializers.Serializer): raise serializers.ValidationError("finish must occur after start") return dataValidators
+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: @@ -737,15 +737,15 @@ class GameRecord(serializers.Serializer): )For more information see the validators documentation.
-Accessing the initial data and instance
+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.instanceattribute will beNone.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_dataattribute will not exist.Partial updates
+Partial updates
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the
partialargument in order to allow partial updates.-# Update `comment` with partial data serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)Dealing with nested objects
+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
Serializerclass is itself a type ofField, and can be used to represent relationships where one object type is nested inside another.-class UserSerializer(serializers.Serializer): @@ -770,7 +770,7 @@ class CommentSerializer(serializers.Serializer): content = serializers.CharField(max_length=200) created = serializers.DateTimeField()Writable nested representations
+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() @@ -779,7 +779,7 @@ serializer.errors # {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}Similarly, the
-.validated_dataproperty will include nested data structures.Writing
+.create()methods for nested representationsWriting
.create()methods for nested representationsIf 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): @@ -795,7 +795,7 @@ serializer.errors Profile.objects.create(user=user, **profile_data) return userWriting
+.update()methods for nested representationsWriting
.update()methods for nested representationsFor 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
@@ -829,7 +829,7 @@ serializer.errorsNULLin the database.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.It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.
-Handling saving related instances in model manager classes
+Handling saving related instances in model manager classes
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
Userinstances andProfileinstances are always created together as a pair. We might write a custom manager class that looks something like this:class UserManager(models.Manager): @@ -856,9 +856,9 @@ serializer.errors )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
+Dealing with multiple objects
The
-Serializerclass can also handle serializing or deserializing lists of objects.Serializing multiple objects
+Serializing multiple objects
To serialize a queryset or list of objects instead of a single object instance, you should pass the
many=Trueflag 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) @@ -869,9 +869,9 @@ serializer.data # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} # ]Deserializing multiple objects
+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
+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
contextargument when instantiating the serializer. For example:serializer = AccountSerializer(account, context={'request': request}) @@ -880,7 +880,7 @@ serializer.dataThe context dictionary can be used within any serializer field logic, such as a custom
.to_representation()method, by accessing theself.contextattribute.
-ModelSerializer
+ModelSerializer
Often you'll want serializer classes that map closely to Django model definitions.
The
ModelSerializerclass provides a shortcut that lets you automatically create aSerializerclass with fields that correspond to the Model fields.The
@@ -897,7 +897,7 @@ serializer.dataModelSerializerclass is the same as a regularSerializerclass, except that: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 described below.Inspecting a
+ModelSerializerInspecting a
ModelSerializerSerializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with
ModelSerializerswhere 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 @@ -908,7 +908,7 @@ AccountSerializer(): name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all())Specifying which fields to include
+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
fieldsorexcludeoptions, just as you would with aModelForm. It is strongly recommended that you explicitly set all fields that should be serialized using thefieldsattribute. This will make it less likely to result in unintentionally exposing data when your models change.For example:
-class AccountSerializer(serializers.ModelSerializer): @@ -933,7 +933,7 @@ AccountSerializer():In the example above, if the
Accountmodel had 3 fieldsaccount_name,users, andcreated, this will result in the fieldsaccount_nameandcreatedto be serialized.The names in the
fieldsandexcludeattributes will normally map to model fields on the model class.Alternatively names in the
-fieldsoptions can map to properties or methods which take no arguments that exist on the model class.Specifying nested serialization
+Specifying nested serialization
The default
ModelSerializeruses primary keys for relationships, but you can also easily generate nested representations using thedepthoption:class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -943,7 +943,7 @@ AccountSerializer():The
depthoption 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
+Specifying fields explicitly
You can add extra fields to a
ModelSerializeror override the default fields by declaring fields on the class, just as you would for aSerializerclass.class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) @@ -953,7 +953,7 @@ AccountSerializer(): model = AccountExtra fields can correspond to any property or callable on the model.
-Specifying read only fields
+Specifying read only fields
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the
read_only=Trueattribute, 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): @@ -971,7 +971,7 @@ AccountSerializer():Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.
-Additional keyword arguments
+Additional keyword arguments
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the
extra_kwargsoption. As in the case ofread_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): @@ -989,56 +989,56 @@ AccountSerializer(): user.save() return userRelational fields
+Relational fields
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for
ModelSerializeris 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.
-Inheritance of the 'Meta' class
+Inheritance of the 'Meta' class
The inner
Metaclass on serializers is not inherited from parent classes by default. This is the same behavior as with Django'sModelandModelFormclasses. If you want theMetaclass to inherit from a parent class you must do so explicitly. For example:class AccountSerializer(MyBaseSerializer): class Meta(MyBaseSerializer.Meta): model = AccountTypically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly.
-Customizing field mappings
+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
-ModelSerializerdoes not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regularSerializerclass 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
.serializer_field_mappingA 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.
-+
.serializer_related_field
.serializer_related_fieldThis property should be the serializer field class, that is used for relational fields by default.
For
ModelSerializerthis defaults toPrimaryKeyRelatedField.For
-HyperlinkedModelSerializerthis defaults toserializers.HyperlinkedRelatedField.+
serializer_url_field
serializer_url_fieldThe serializer field class that should be used for any
urlfield on the serializer.Defaults to
-serializers.HyperlinkedIdentityField+
serializer_choice_field
serializer_choice_fieldThe serializer field class that should be used for any choice fields on the serializer.
Defaults to
-serializers.ChoiceFieldThe field_class and field_kwargs API
+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)
.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_mappingattribute.+
.build_relational_field(self, field_name, relation_info)
.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_relational_fieldattribute.The
-relation_infoargument is a named tuple, that containsmodel_field,related_model,to_manyandhas_through_modelproperties.+
.build_nested_field(self, field_name, relation_info, nested_depth)
.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
depthoption has been set.The default implementation dynamically creates a nested serializer class based on either
ModelSerializerorHyperlinkedModelSerializer.The
nested_depthwill be the value of thedepthoption, minus one.The
-relation_infoargument is a named tuple, that containsmodel_field,related_model,to_manyandhas_through_modelproperties.+
.build_property_field(self, field_name, model_class)
.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
-ReadOnlyFieldclass.+
.build_url_field(self, field_name, model_class)
.build_url_field(self, field_name, model_class)Called to generate a serializer field for the serializer's own
-urlfield. The default implementation returns aHyperlinkedIdentityFieldclass.+
.build_unknown_field(self, field_name, model_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
+HyperlinkedModelSerializer
The
HyperlinkedModelSerializerclass is similar to theModelSerializerclass except that it uses hyperlinks to represent relationships, rather than primary keys.By default the serializer will include a
urlfield instead of a primary key field.The url field will be represented using a
@@ -1048,7 +1048,7 @@ The default implementation raises an error, although subclasses may customize th model = Account fields = ('url', 'id', 'account_name', 'users', 'created')HyperlinkedIdentityFieldserializer field, and any relationships on the model will be represented using aHyperlinkedRelatedFieldserializer field.How hyperlinked views are determined
+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 apkkeyword argument.You can override a URL field view name and lookup field by using either, or both of, the
@@ -1081,10 +1081,10 @@ The default implementation raises an error, although subclasses may customize thview_nameandlookup_fieldoptions in theextra_kwargssetting, like so:
Tip: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the
reprof aHyperlinkedModelSerializerinstance 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
+Changing the URL field name
The name of the URL field defaults to 'url'. You can override this globally, by using the
URL_FIELD_NAMEsetting.
-ListSerializer
+ListSerializer
The
ListSerializerclass provides the behavior for serializing and validating multiple objects at once. You won't typically need to useListSerializerdirectly, but should instead simply passmany=Truewhen instantiating a serializer.When a serializer is instantiated and
many=Trueis passed, aListSerializerinstance will be created. The serializer class then becomes a child of the parentListSerializerThere are a few use cases when you might want to customize the
@@ -1102,7 +1102,7 @@ class CustomSerializer(serializers.Serializer): class Meta: list_serializer_class = CustomListSerializer -ListSerializerbehavior. For example:Customizing multiple create
+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 onListSerializerclass that is used whenmany=Trueis passed.For example:
-class BookListSerializer(serializers.ListSerializer): @@ -1115,7 +1115,7 @@ class BookSerializer(serializers.Serializer): class Meta: list_serializer_class = BookListSerializerCustomizing multiple update
+Customizing multiple update
By default the
ListSerializerclass 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:
@@ -1153,7 +1153,7 @@ class BookSerializer(serializers.Serializer): 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_removebehavior that was present in REST framework 2.Customizing ListSerializer initialization
+Customizing ListSerializer initialization
When a serializer with
many=Trueis instantiated, we need to determine which arguments and keyword arguments should be passed to the.__init__()method for both the childSerializerclass, and for the parentListSerializerclass.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
@@ -1165,7 +1165,7 @@ class BookSerializer(serializers.Serializer): return CustomListSerializer(*args, **kwargs)many=Trueis passed. You can do so by using themany_initclass method.
-BaseSerializer
+BaseSerializer
BaseSerializerclass that can be used to easily support alternative serialization and deserialization styles.This class implements the same basic API as the
Serializerclass:@@ -1183,7 +1183,7 @@ class BookSerializer(serializers.Serializer):
Because this class provides the same interface as the
Serializerclass, you can use it with the existing generic class based views exactly as you would for a regularSerializerorModelSerializer.The only difference you'll notice when doing so is the
-BaseSerializerclasses 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
+BaseSerializerclassesRead-only
BaseSerializerclassesTo implement a read-only serializer using the
BaseSerializerclass, 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) @@ -1212,7 +1212,7 @@ def all_high_scores(request): serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data)Read-write
+BaseSerializerclassesRead-write
BaseSerializerclassesTo 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 aValidationErrorif 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_dataand.errors.If you want to also support
@@ -1252,7 +1252,7 @@ def all_high_scores(request): def create(self, validated_data): return HighScore.objects.create(**validated_data) -.save()you'll need to also implement either or both of the.create()and.update()methods.Creating new base classes
+Creating new base classes
The
BaseSerializerclass 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): @@ -1288,8 +1288,8 @@ def all_high_scores(request): output[attribute_name] = str(attribute)
-Advanced serializer usage
-Overriding serialization and deserialization behavior
+Advanced serializer usage
+Overriding serialization and deserialization behavior
If you need to alter the serialization, deserialization or validation 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...
@@ -1298,16 +1298,16 @@ def all_high_scores(request):
- 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, obj)
.to_representation(self, obj)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.
-+
.to_internal_value(self, data)
.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). Typically theerrorsargument here will be a dictionary mapping field names to error messages.The
-dataargument passed to this method will normally be the value ofrequest.data, so the datatype it provides will depend on the parser classes you have configured for your API.Dynamically modifying fields
+Dynamically modifying fields
Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the
.fieldsattribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.Modifying the
-fieldsargument 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
+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): """ @@ -1341,23 +1341,23 @@ def all_high_scores(request): >>> print UserSerializer(user, fields=('id', 'email')) {'id': 2, 'email': 'jon@example.com'}Customizing the default fields
+Customizing the default fields
REST framework 2 provided an API to allow developers to override how a
ModelSerializerclass 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.
A new interface for controlling this behavior is currently planned for REST framework 3.1.
-Third party packages
+Third party packages
The following third party packages are also available.
-Django REST marshmallow
+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
+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
+MongoengineModelSerializer
The django-rest-framework-mongoengine package provides a
-MongoEngineModelSerializerserializer class that supports using MongoDB as the storage layer for Django REST framework.GeoFeatureModelSerializer
+GeoFeatureModelSerializer
The django-rest-framework-gis package provides a
-GeoFeatureModelSerializerserializer class that supports GeoJSON both for read and write operations.HStoreSerializer
+HStoreSerializer
The django-rest-framework-hstore package provides an
diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html index 861a13ade..96c1f7f9e 100644 --- a/api-guide/settings/index.html +++ b/api-guide/settings/index.html @@ -413,7 +413,7 @@ -HStoreSerializerto support django-hstoreDictionaryFieldmodel field and itsschema-modefeature.Settings
+Settings
Namespaces are one honking great idea - let's do more of those!
@@ -429,7 +429,7 @@ ) } -Accessing settings
+Accessing settings
If you need to access the values of REST framework's API settings in your project, you should use the
api_settingsobject. For example.from rest_framework.settings import api_settings @@ -438,10 +438,10 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSESThe
api_settingsobject 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
+API Reference
+API policy settings
The following settings control the basic API policies, and are applied to every
-APIViewclass based view, or@api_viewfunction based view.DEFAULT_RENDERER_CLASSES
+DEFAULT_RENDERER_CLASSES
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a
Responseobject.Default:
-( @@ -449,7 +449,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES 'rest_framework.renderers.BrowsableAPIRenderer', )DEFAULT_PARSER_CLASSES
+DEFAULT_PARSER_CLASSES
A list or tuple of parser classes, that determines the default set of parsers used when accessing the
request.dataproperty.Default:
-( @@ -458,7 +458,7 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES 'rest_framework.parsers.MultiPartParser' )DEFAULT_AUTHENTICATION_CLASSES
+DEFAULT_AUTHENTICATION_CLASSES
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the
request.userorrequest.authproperties.Default:
-( @@ -466,32 +466,32 @@ print api_settings.DEFAULT_AUTHENTICATION_CLASSES 'rest_framework.authentication.BasicAuthentication' )DEFAULT_PERMISSION_CLASSES
+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
+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
+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'
-Generic view settings
+Generic view settings
The following settings control the behavior of the generic class based views.
-DEFAULT_PAGINATION_SERIALIZER_CLASS
+DEFAULT_PAGINATION_SERIALIZER_CLASS
A class the determines the default serialization style for paginated responses.
Default:
-rest_framework.pagination.PaginationSerializerDEFAULT_FILTER_BACKENDS
+DEFAULT_FILTER_BACKENDS
A list of filter backend classes that should be used for generic filtering. If set to
-Nonethen generic filtering is disabled.PAGINATE_BY
+PAGINATE_BY
The default page size to use for pagination. If set to
None, pagination is disabled by default.Default:
-NonePAGINATE_BY_PARAM
+PAGINATE_BY_PARAM
This setting is pending deprecation.
See the pagination documentation for further guidance on setting the pagination style.
@@ -507,7 +507,7 @@ If set toNonethen generic filtering is disabled.GET http://example.com/api/accounts?page_size=25Default:
-NoneMAX_PAGINATE_BY
+MAX_PAGINATE_BY
This setting is pending deprecation.
See the pagination documentation for further guidance on setting the pagination style.
@@ -524,40 +524,40 @@ If set toNonethen generic filtering is disabled.GET http://example.com/api/accounts?page_size=999Default:
-NoneSEARCH_PARAM
+SEARCH_PARAM
The name of a query parameter, which can be used to specify the search term used by
SearchFilter.Default:
-searchORDERING_PARAM
+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
+Versioning settings
+DEFAULT_VERSION
The value that should be used for
request.versionwhen no versioning information is present.Default:
-NoneALLOWED_VERSIONS
+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:
-NoneVERSION_PARAMETER
+VERSION_PARAMETER
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default:
'version'
-Authentication settings
+Authentication settings
The following settings control the behavior of unauthenticated requests.
-UNAUTHENTICATED_USER
+UNAUTHENTICATED_USER
The class that should be used to initialize
request.userfor unauthenticated requests.Default:
-django.contrib.auth.models.AnonymousUserUNAUTHENTICATED_TOKEN
+UNAUTHENTICATED_TOKEN
The class that should be used to initialize
request.authfor unauthenticated requests.Default:
None
-Test settings
+Test settings
The following settings control the behavior of APIRequestFactory and APIClient
-TEST_REQUEST_DEFAULT_FORMAT
+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_CLASSESsetting.Default:
-'multipart'TEST_REQUEST_RENDERER_CLASSES
+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:
@@ -567,46 +567,46 @@ If set toNonethen generic filtering is disabled. )
-Content type controls
-URL_FORMAT_OVERRIDE
+Content type controls
+URL_FORMAT_OVERRIDE
The name of a URL parameter that may be used to override the default content negotiation
Acceptheader behavior, by using aformat=…query parameter in the request URL.For example:
http://example.com/organizations/?format=csvIf the value of this setting is
Nonethen URL format overrides will be disabled.Default:
-'format'FORMAT_SUFFIX_KWARG
+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_patternsto include suffixed URL patterns.For example:
http://example.com/organizations.csv/Default:
'format'
-Date and time formatting
+Date and time formatting
The following settings are used to control how date and time representations may be parsed and rendered.
-DATETIME_FORMAT
+DATETIME_FORMAT
A format string that should be used by default for rendering the output of
DateTimeFieldserializer fields. IfNone, thenDateTimeFieldserializer fields will return Pythondatetimeobjects, 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
+DATETIME_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to
DateTimeFieldserializer fields.May be a list including the string
'iso-8601'or Python strftime format strings.Default:
-['iso-8601']DATE_FORMAT
+DATE_FORMAT
A format string that should be used by default for rendering the output of
DateFieldserializer fields. IfNone, thenDateFieldserializer fields will return Pythondateobjects, 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
+DATE_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to
DateFieldserializer fields.May be a list including the string
'iso-8601'or Python strftime format strings.Default:
-['iso-8601']TIME_FORMAT
+TIME_FORMAT
A format string that should be used by default for rendering the output of
TimeFieldserializer fields. IfNone, thenTimeFieldserializer fields will return Pythontimeobjects, 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
+TIME_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to
TimeFieldserializer fields.May be a list including the string
'iso-8601'or Python strftime format strings.Default:
['iso-8601']
-Encodings
-UNICODE_JSON
+Encodings
+UNICODE_JSON
When set to
True, JSON responses will allow unicode characters in responses. For example:@@ -615,7 +615,7 @@ If set to{"unicode black star":"★"}Nonethen generic filtering is disabled.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:
-TrueCOMPACT_JSON
+COMPACT_JSON
When set to
True, JSON responses will return compact representations, with no spacing after':'and','characters. For example:@@ -624,14 +624,14 @@ If set to{"is_admin":false,"email":"jane@example"}Nonethen generic filtering is disabled.The default style is to return minified responses, in line with Heroku's API design guidelines.
Default:
-TrueCOERCE_DECIMAL_TO_STRING
+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 serializerDecimalFieldclass will return strings instead ofDecimalobjects. When set toFalse, serializers will returnDecimalobjects, which the default JSON encoder will return as floats.Default:
True
-View names and descriptions
+View names and descriptions
The following settings are used to generate the view names and descriptions, as used in responses to
-OPTIONSrequests, and as used in the browsable API.VIEW_NAME_FUNCTION
+VIEW_NAME_FUNCTION
A string representing the function that should be used when generating view names.
This should be a function with the following signature:
view_name(cls, suffix=None) @@ -641,7 +641,7 @@ If set toNonethen generic filtering is disabled.suffix: The optional suffix used when differentiating individual views in a viewset.Default:
-'rest_framework.views.get_view_name'VIEW_DESCRIPTION_FUNCTION
+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
rstmarkup in your view docstrings being output in the browsable API.This should be a function with the following signature:
@@ -653,8 +653,8 @@ If set toNonethen generic filtering is disabled.Default:
'rest_framework.views.get_view_description'
-Miscellaneous settings
-EXCEPTION_HANDLER
+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:
@@ -664,13 +664,13 @@ If set toNonethen generic filtering is disabled.exc: The exception.Default:
-'rest_framework.views.exception_handler'NON_FIELD_ERRORS_KEY
+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
+URL_FIELD_NAME
A string representing the key that should be used for the URL fields generated by
HyperlinkedModelSerializer.Default:
-'url'NUM_PROXIES
+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
Nonethen less strict IP matching will be used by the throttle classes.Default:
diff --git a/api-guide/status-codes/index.html b/api-guide/status-codes/index.html index 878c66f13..81c077330 100644 --- a/api-guide/status-codes/index.html +++ b/api-guide/status-codes/index.html @@ -387,7 +387,7 @@ -NoneStatus Codes
+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
@@ -413,12 +413,12 @@ class ExampleTestCase(APITestCase):For more information on proper usage of HTTP status codes see RFC 2616 and RFC 6585.
-Informational - 1xx
+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_PROTOCOLSSuccessful - 2xx
+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 @@ -428,7 +428,7 @@ HTTP_204_NO_CONTENT HTTP_205_RESET_CONTENT HTTP_206_PARTIAL_CONTENTRedirection - 3xx
+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 @@ -439,7 +439,7 @@ HTTP_305_USE_PROXY HTTP_306_RESERVED HTTP_307_TEMPORARY_REDIRECTClient Error - 4xx
+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 @@ -463,7 +463,7 @@ HTTP_428_PRECONDITION_REQUIRED HTTP_429_TOO_MANY_REQUESTS HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGEServer Error - 5xx
+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 @@ -473,7 +473,7 @@ HTTP_504_GATEWAY_TIMEOUT HTTP_505_HTTP_VERSION_NOT_SUPPORTED HTTP_511_NETWORK_AUTHENTICATION_REQUIREDHelper functions
+Helper functions
The following helper functions are available for identifying the category of the response code.
is_informational() # 1xx is_success() # 2xx diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html index 6ece73330..0c8b9cd3e 100644 --- a/api-guide/testing/index.html +++ b/api-guide/testing/index.html @@ -437,15 +437,15 @@ -Testing
+Testing
Code without tests is broken as designed.
REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
-APIRequestFactory
+APIRequestFactory
Extends Django's existing
-RequestFactoryclass.Creating test requests
+Creating test requests
The
APIRequestFactoryclass supports an almost identical API to Django's standardRequestFactoryclass. This means that the standard.get(),.post(),.put(),.patch(),.delete(),.head()and.options()methods are all available.-from rest_framework.test import APIRequestFactory @@ -453,7 +453,7 @@ factory = APIRequestFactory() request = factory.post('/notes/', {'title': 'new idea'})Using the
+formatargumentUsing the
formatargumentMethods which create a request body, such as
post,putandpatch, include aformatargument, 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() @@ -461,11 +461,11 @@ request = factory.post('/notes/', {'title': 'new idea'}, format='json')By default the available formats are
'multipart'and'json'. For compatibility with Django's existingRequestFactorythe 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
+Explicitly encoding the request body
If you need to explicitly encode the request body, you can do so by setting the
content_typeflag. For example:-request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')PUT and PATCH with form data
+PUT and PATCH with form data
One difference worth noting between Django's
RequestFactoryand REST framework'sAPIRequestFactoryis 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() @@ -480,7 +480,7 @@ content = encode_multipart('BoUnDaRyStRiNg', data) content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg' request = factory.put('/notes/547/', content, content_type=content_type)Forcing authentication
+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 @@ -509,16 +509,16 @@ request.user = user response = view(request)
-Forcing CSRF validation
+Forcing CSRF validation
By default, requests created with
APIRequestFactorywill 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 theenforce_csrf_checksflag when instantiating the factory.factory = APIRequestFactory(enforce_csrf_checks=True)
Note: It's worth noting that Django's standard
RequestFactorydoesn'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
+APIClient
Extends Django's existing
-Clientclass.Making requests
+Making requests
The
APIClientclass supports the same request interface as Django's standardClientclass. This means the that standard.get(),.post(),.put(),.patch(),.delete(),.head()and.options()methods are all available. For example:from rest_framework.test import APIClient @@ -526,8 +526,8 @@ 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)
+Authenticating
+.login(**kwargs)
The
loginmethod functions exactly as it does with Django's regularClientclass. This allows you to authenticate requests against any views which includeSessionAuthentication.# Make all requests in the context of a logged in session. client = APIClient() @@ -538,7 +538,7 @@ client.login(username='lauren', password='secret') client.logout()The
-loginmethod is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API..credentials(**kwargs)
+.credentials(**kwargs)
The
credentialsmethod 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 @@ -553,7 +553,7 @@ client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) client.credentials()The
-credentialsmethod 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)
+.force_authenticate(user=None, token=None)
Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
-user = User.objects.get(username='lauren') @@ -563,13 +563,13 @@ client.force_authenticate(user=user)To unauthenticate subsequent requests, call
force_authenticatesetting the user and/or token toNone.-client.force_authenticate(user=None)CSRF validation
+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 theenforce_csrf_checksflag when instantiating the client.client = APIClient(enforce_csrf_checks=True)As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling
login().
-Test cases
+Test cases
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use
APIClientinstead of Django's defaultClient.-
- @@ -577,7 +577,7 @@ client.force_authenticate(user=user)
APISimpleTestCaseAPITestCaseAPILiveServerTestCaseExample
+Example
You can use any of REST framework's test case classes as you would for the regular Django test case classes. The
self.clientattribute will be anAPIClientinstance.from django.core.urlresolvers import reverse from rest_framework import status @@ -597,8 +597,8 @@ class AccountTests(APITestCase): self.assertEqual(Account.objects.get().name, 'DabApps')
-Testing responses
-Checking the response data
+Testing responses
+Checking the response data
When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
For example, it's easier to inspect
response.data:response = self.client.get('/users/4/') @@ -608,7 +608,7 @@ self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})-response = self.client.get('/users/4/') self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})Rendering responses
+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 accessresponse.content, you'll first need to render the response.view = UserDetail.as_view() request = factory.get('/users/4') @@ -617,15 +617,15 @@ response.render() # Cannot access `response.content` without this. self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
-Configuration
-Setting the default format
+Configuration
+Setting the default format
The default format used to make test requests may be set using the
TEST_REQUEST_DEFAULT_FORMATsetting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in yoursettings.pyfile:-REST_FRAMEWORK = { ... 'TEST_REQUEST_DEFAULT_FORMAT': 'json' }Setting the available formats
+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_CLASSESsetting.For example, to add support for using
format='html'in test requests, you might have something like this in yoursettings.pyfile.REST_FRAMEWORK = { diff --git a/api-guide/throttling/index.html b/api-guide/throttling/index.html index d5cfe0272..babeaf549 100644 --- a/api-guide/throttling/index.html +++ b/api-guide/throttling/index.html @@ -407,7 +407,7 @@ -Throttling
+Throttling
HTTP/1.1 420 Enhance Your Calm
Twitter API rate limiting response
@@ -417,11 +417,11 @@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
+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.Throttledexception will be raised, and the main body of the view will not run.Setting the throttling policy
+Setting the throttling policy
The default throttling policy may be set globally, using the
DEFAULT_THROTTLE_CLASSESandDEFAULT_THROTTLE_RATESsettings. For example.-REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( @@ -459,12 +459,12 @@ def example_view(request, format=None): } return Response(content)How clients are identified
+How clients are identified
The
X-Forwarded-ForandRemote-AddrHTTP headers are used to uniquely identify client IP addresses for throttling. If theX-Forwarded-Forheader is present then it will be used, otherwise the value of theRemote-Addrheader 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_PROXIESsetting. 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 theX-Forwarded-Forheader, once any application proxy IP addresses have first been excluded. If set to zero, then theRemote-Addrheader will always be used as the identifying IP address.It is important to understand that if you configure the
NUM_PROXIESsetting, then all clients behind a unique NAT'd gateway will be treated as a single client.Further context on how the
-X-Forwarded-Forheader works, and identifying a remote client IP can be found here.Setting up the cache
+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
LocMemCachebackend 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 thecacheattribute. For example:class CustomAnonRateThrottle(AnonRateThrottle): @@ -472,8 +472,8 @@ def example_view(request, format=None):You'll need to remember to also set your custom throttle class in the
'DEFAULT_THROTTLE_CLASSES'settings key, or using thethrottle_classesview attribute.
-API Reference
-AnonRateThrottle
+API Reference
+AnonRateThrottle
The
AnonRateThrottlewill 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).
@@ -481,7 +481,7 @@ def example_view(request, format=None):
- The
DEFAULT_THROTTLE_RATES['anon']setting.-
AnonRateThrottleis suitable if you want to restrict the rate of requests from unknown sources.UserRateThrottle
+UserRateThrottle
The
UserRateThrottlewill 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).
@@ -509,7 +509,7 @@ class SustainedRateThrottle(UserRateThrottle): }
-
UserRateThrottleis suitable if you want simple global rate restrictions per-user.ScopedRateThrottle
+ScopedRateThrottle
The
ScopedRateThrottleclass 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_scopeproperty. 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_RATESsetting using a key from the request "scope".For example, given the following views...
@@ -538,11 +538,11 @@ class UploadView(APIView):User requests to either
ContactListVieworContactDetailViewwould be restricted to a total of 1000 requests per-day. User requests toUploadViewwould be restricted to 20 requests per day.
-Custom throttles
+Custom throttles
To create a custom throttle, override
BaseThrottleand implement.allow_request(self, request, view). The method should returnTrueif the request should be allowed, andFalseotherwise.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, orNone. The.wait()method will only be called if.allow_request()has previously returnedFalse.If the
-.wait()method is implemented and the request is throttled, then aRetry-Afterheader will be included in the response.Example
+Example
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
class RandomRateThrottle(throttling.BaseThrottle): def allow_request(self, request, view): diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html index ab919b2fb..838955847 100644 --- a/api-guide/validators/index.html +++ b/api-guide/validators/index.html @@ -415,14 +415,14 @@ -Validators
+Validators
Validators can be useful for re-using validation logic between different types of fields.
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 REST framework
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's
ModelFormclass.With
ModelFormthe 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:@@ -431,7 +431,7 @@
- Printing the
reprof 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
-ModelSerializerall of this is handled automatically for you. If you want to drop down to using aSerializerclasses instead, then you need to define the validation rules explicitly.Example
+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) @@ -456,7 +456,7 @@ CustomerReportSerializer():The interesting bit here is the
referencefield. 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
+UniqueValidator
This validator can be used to enforce the
unique=Trueconstraint on model fields. It takes a single required argument, and an optionalmessagesargument:@@ -469,7 +469,7 @@ It takes a single required argument, and an optional
messagesargum validators=[UniqueValidator(queryset=BlogPost.objects.all())] )UniqueTogetherValidator
+UniqueTogetherValidator
This validator can be used to enforce
unique_togetherconstraints on model instances. It has two required arguments, and a single optionalmessagesargument:@@ -494,9 +494,9 @@ It has two required arguments, and a single optional
messagesargum
Note: The
UniqueTogetherValidationclass always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields withdefaultvalues are an exception to this as they always supply a value even when omitted from user input.
-UniqueForDateValidator
-UniqueForMonthValidator
-UniqueForYearValidator
+UniqueForDateValidator
+UniqueForMonthValidator
+UniqueForYearValidator
These validators can be used to enforce the
unique_for_date,unique_for_monthandunique_for_yearconstraints on model instances. They take the following arguments:
- @@ -519,23 +519,23 @@ It has two required arguments, and a single optional
querysetrequired - This is the queryset against which uniqueness should be enforced.messagesargumThe 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
-ModelSerializeryou'll probably simply rely on the defaults that REST framework generates for you, but if you are usingSerializeror simply want more explicit control, use on of the styles demonstrated below.Using with a writable date field.
+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
defaultargument, or by settingrequired=True.-published = serializers.DateTimeField(required=True)Using with a read-only date field.
+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=Trueand additionally set adefault=...argument.published = serializers.DateTimeField(read_only=True, default=timezone.now)The field will not be writable to the user, but the default value will still be passed through to the
-validated_data.Using with a hidden date field.
+Using with a hidden date field.
If you want the date field to be entirely hidden from the user, then use
HiddenField. This field type does not accept user input, but instead always returns it's default value to thevalidated_datain the serializer.published = serializers.HiddenField(default=timezone.now)
Note: The
UniqueFor<Range>Validationclasses always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields withdefaultvalues are an exception to this as they always supply a value even when omitted from user input.
-Advanced 'default' argument usage
+Advanced 'default' argument usage
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator.
Two patterns that you may want to use for this sort of validation include:
@@ -543,13 +543,13 @@ It has two required arguments, and a single optional
messagesargum- Using a standard field with
read_only=True, but that also includes adefault=…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
+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
+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( @@ -558,15 +558,15 @@ It has two required arguments, and a single optionalmessagesargum )
-Writing custom validators
+Writing custom validators
You can use any of Django's existing validators, or write your own custom validators.
-Function based
+Function based
A validator may be any callable that raises a
serializers.ValidationErroron failure.-def even_number(value): if value % 2 != 0: raise serializers.ValidationError('This field must be an even number.')Class based
+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): @@ -577,7 +577,7 @@ It has two required arguments, and a single optionalmessagesargum message = 'This field must be a multiple of %d.' % self.base raise serializers.ValidationError(message)Using
+set_context()Using
set_context()In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a
set_contextmethod on a class based validator.-def set_context(self, serializer_field): # Determine if this is an update or a create operation. diff --git a/api-guide/versioning/index.html b/api-guide/versioning/index.html index 9c25e0c07..7fea161ab 100644 --- a/api-guide/versioning/index.html +++ b/api-guide/versioning/index.html @@ -407,7 +407,7 @@ -Versioning
+Versioning
Versioning an interface is just a "polite" way to kill deployed clients.
— Roy Fielding.
@@ -415,17 +415,17 @@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
+Versioning with REST framework
When API versioning is enabled, the
request.versionattribute will contain a string that corresponds to the version requested in the incoming client request.By default, versioning is not enabled, and
-request.versionwill always returnNone.Varying behavior based on the version
+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 AccountSerializerReversing URLs for versioned APIs
+Reversing URLs for versioned APIs
The
reversefunction included by REST framework ties in with the versioning scheme. You need to make sure to include the currentrequestas a keyword argument, like so.from rest_framework.reverse import reverse @@ -436,7 +436,7 @@ reverse('bookings-list', request=request)- If
NamespacedVersioningwas being used, and the API version was 'v1', then the URL lookup used would be'v1:bookings-list', which might resolve to a URL likehttp://example.org/v1/bookings/.- If
-QueryParameterVersioningwas being used, and the API version was1.0, then the returned URL might be something likehttp://example.org/bookings/?version=1.0Versioned APIs and hyperlinked serializers
+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() @@ -444,7 +444,7 @@ reverse('bookings-list', request=request) return Response({'all_bookings': serializer.data})Doing so will allow any returned URLs to include the appropriate versioning.
-Configuring the versioning scheme
+Configuring the versioning scheme
The versioning scheme is defined by the
DEFAULT_VERSIONING_CLASSsettings key.REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' @@ -455,7 +455,7 @@ reverse('bookings-list', request=request)-class ProfileList(APIView): versioning_class = versioning.QueryParameterVersioningOther versioning settings
+Other versioning settings
The following settings keys are also used to control versioning:
- @@ -475,8 +475,8 @@ class ExampleView(APIVIew): versioning_class = ExampleVersioning
DEFAULT_VERSION. The value that should be used forrequest.versionwhen no versioning information is present. Defaults toNone.
-API Reference
-AcceptHeaderVersioning
+API Reference
+AcceptHeaderVersioning
This scheme requires the client to specify the version as part of the media type in the
Acceptheader. 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 @@ -485,7 +485,7 @@ Accept: application/json; version=1.0In the example request above
request.versionattribute 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
+Using accept headers with vendor media types
Strictly speaking the
jsonmedia 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' @@ -495,7 +495,7 @@ Accept: application/json; version=1.0 Host: example.com Accept: application/vnd.megacorp.bookings+json; version=1.0URLPathVersioning
+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 @@ -515,7 +515,7 @@ Accept: application/json ) ]NamespaceVersioning
+NamespaceVersioning
To the client, this scheme is the same as
URLParameterVersioning. 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 @@ -536,7 +536,7 @@ urlpatterns = [ ]Both
-URLParameterVersioningandNamespaceVersioningare reasonable if you just need a simple versioning scheme. TheURLParameterVersioningapproach might be better suitable for small ad-hoc projects, and theNamespaceVersioningis probably easier to manage for larger projects.HostNameVersioning
+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 @@ -549,16 +549,16 @@ Accept: application/jsonNote that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The
HostNameVersioningscheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as127.0.0.1. There are various online services which you 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
+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
+Custom versioning schemes
To implement a custom versioning scheme, subclass
-BaseVersioningand override the.determine_versionmethod.Example
+Example
The following example uses a custom
X-API-Versionheader to determine the requested version.-class XAPIVersionScheme(versioning.BaseVersioning): def determine_version(self, request, *args, **kwargs): diff --git a/api-guide/views/index.html b/api-guide/views/index.html index 50ba9bd1a..1de64d331 100644 --- a/api-guide/views/index.html +++ b/api-guide/views/index.html @@ -397,7 +397,7 @@ -Class Based Views
+Class Based Views
Django's class based views are a welcome departure from the old-style views.
@@ -433,52 +433,52 @@ class ListUsers(APIView): usernames = [user.username for user in User.objects.all()] return Response(usernames)API policy attributes
+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
+.renderer_classes
+.parser_classes
+.authentication_classes
+.throttle_classes
+.permission_classes
+.content_negotiation_class
+API policy instantiation methods
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
-.get_renderers(self)
-.get_parsers(self)
-.get_authenticators(self)
-.get_throttles(self)
-.get_permissions(self)
-.get_content_negotiator(self)
-API policy implementation methods
+.get_renderers(self)
+.get_parsers(self)
+.get_authenticators(self)
+.get_throttles(self)
+.get_permissions(self)
+.get_content_negotiator(self)
+API policy implementation methods
The following methods are called before dispatching to the handler method.
-.check_permissions(self, request)
-.check_throttles(self, request)
-.perform_content_negotiation(self, request, force=False)
-Dispatch methods
+.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)
+.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)
+.handle_exception(self, exc)
Any exception thrown by the handler method will be passed to this method, which either returns a
Responseinstance, or re-raises the exception.The default implementation handles any subclass of
rest_framework.exceptions.APIException, as well as Django'sHttp404andPermissionDeniedexceptions, 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)
+.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 DjangoHttpRequest.You won't typically need to override this method.
-.finalize_response(self, request, response, *args, **kwargs)
+.finalize_response(self, request, response, *args, **kwargs)
Ensures that any
Responseobject 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
+Function Based Views
Saying [that Class based views] is always the superior solution is a mistake.
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 DjangoHttpRequest) and allows them to return aResponse(instead of a DjangoHttpResponse), and allow you to configure how the request is processed.@api_view()
+@api_view()
Signature:
@api_view(http_method_names=['GET'])The core of this functionality is the
api_viewdecorator, 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 @@ -495,7 +495,7 @@ def hello_world(request): return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"})API policy decorators
+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_viewdecorator. 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_classesdecorator, passing a list of throttle classes:from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle diff --git a/api-guide/viewsets/index.html b/api-guide/viewsets/index.html index 50ea919b6..25efe58e6 100644 --- a/api-guide/viewsets/index.html +++ b/api-guide/viewsets/index.html @@ -403,7 +403,7 @@ -ViewSets
+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.
@@ -412,7 +412,7 @@A
ViewSetclass 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
ViewSetare 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
+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 @@ -461,7 +461,7 @@ urlpatterns = router.urls- By using routers, we no longer need to deal with wiring up the URL conf ourselves.
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
-Marking extra actions for routing
+Marking extra actions for routing
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
class UserViewSet(viewsets.ViewSet): """ @@ -543,17 +543,17 @@ class UserViewSet(viewsets.ModelViewSet):The two new actions will then be available at the urls
^users/{pk}/set_password/$and^users/{pk}/unset_password/$
-API Reference
-ViewSet
+API Reference
+ViewSet
The
ViewSetclass inherits fromAPIView. You can use any of the standard attributes such aspermission_classes,authentication_classesin order to control the API policy on the viewset.The
-ViewSetclass does not provide any implementations of actions. In order to use aViewSetclass you'll override the class and define the action implementations explicitly.GenericViewSet
+GenericViewSet
The
GenericViewSetclass inherits fromGenericAPIView, and provides the default set ofget_object,get_querysetmethods and other generic view base behavior, but does not include any actions by default.In order to use a
-GenericViewSetclass you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.ModelViewSet
+ModelViewSet
The
ModelViewSetclass inherits fromGenericAPIViewand includes implementations for various actions, by mixing in the behavior of the various mixin classes.The actions provided by the
-ModelViewSetclass are.list(),.retrieve(),.create(),.update(), and.destroy().Example
+Example
Because
ModelViewSetextendsGenericAPIView, you'll normally need to provide at least thequerysetandserializer_classattributes. For example:class AccountViewSet(viewsets.ModelViewSet): """ @@ -577,9 +577,9 @@ class UserViewSet(viewsets.ModelViewSet):Note however that upon removal of the
querysetproperty from yourViewSet, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify thebase_namekwarg 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
+ReadOnlyModelViewSet
The
-ReadOnlyModelViewSetclass also inherits fromGenericAPIView. As withModelViewSetit also includes implementations for various actions, but unlikeModelViewSetonly provides the 'read-only' actions,.list()and.retrieve().Example
+Example
As with
ModelViewSet, you'll normally need to provide at least thequerysetandserializer_classattributes. For example:class AccountViewSet(viewsets.ReadOnlyModelViewSet): """ @@ -589,9 +589,9 @@ class UserViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializerAgain, as with
-ModelViewSet, you can use any of the standard attributes and method overrides available toGenericAPIView.Custom ViewSet base classes
+Custom ViewSet base classes
You may need to provide custom
-ViewSetclasses that do not have the full set ofModelViewSetactions, or that customize the behavior in some other way.Example
+Example
To create a base viewset class that provides
create,listandretrieveoperations, inherit fromGenericViewSet, and mixin the required actions:class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, diff --git a/css/default.css b/css/default.css index 7f0f8afd8..192e86860 100644 --- a/css/default.css +++ b/css/default.css @@ -413,3 +413,7 @@ ul.sponsor { #mkdocs_search_modal article p{ word-wrap: break-word; } + +.toclink { + color: #333; +} diff --git a/index.html b/index.html index 19e2cb535..f9d6b2949 100644 --- a/index.html +++ b/index.html @@ -467,7 +467,7 @@
Above: Screenshot from the browsable API
-Requirements
+Requirements
REST framework requires the following:
-
- Python (2.7, 3.2, 3.3, 3.4, 3.5)
@@ -480,7 +480,7 @@- [django-crispy-forms][django-crispy-forms] - Improved HTML display for filtering.
- django-guardian (1.1.1+) - Object level permissions support.
Installation
+Installation
Install using
pip, including any optional packages you want...pip install djangorestframework pip install markdown # Markdown support for the browsable API. @@ -502,7 +502,7 @@ pip install django-filter # Filtering support ]Note that the URL path can be whatever you want, but you must include
-'rest_framework.urls'with the'rest_framework'namespace.Example
+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
@@ -544,9 +544,9 @@ urlpatterns = [ ]REST_FRAMEWORK. Start off by adding the following to yoursettings.pymodule: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
+Quickstart
Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.
-Tutorial
+Tutorial
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
- 1 - Serialization
@@ -557,7 +557,7 @@ urlpatterns = [- 6 - Viewsets & routers
There is a live example API of the finished tutorial API for testing purposes, available here.
-API Guide
+API Guide
The API guide is your complete reference manual to all the functionality provided by REST framework.
-Topics
+Topics
General guides to using REST framework.
-
- Documenting your API
@@ -607,20 +607,20 @@ urlpatterns = [- Kickstarter Announcement
- Release Notes
Development
+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
+Support
For support please see the REST framework discussion group, try the
#restframeworkchannel onirc.freenode.net, search the IRC archives, or raise a question on Stack Overflow, making sure to include the 'django-rest-framework' tag.Paid support is available from DabApps, and can include work on REST framework core, or support with building your REST framework API. Please contact DabApps if you'd like to discuss commercial support options.
For updates on REST framework development, you may also want to follow the author on Twitter.
-Security
+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
+License
Copyright (c) 2011-2015, Tom Christie All rights reserved.
Redistribution and use in source and binary forms, with or without diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json index e23ef1522..938c9f84a 100644 --- a/mkdocs/search_index.json +++ b/mkdocs/search_index.json @@ -1257,7 +1257,7 @@ }, { "location": "/api-guide/fields/", - "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields.\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue']\n style = {'base_template': 'radio.html'}\n}\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now\n and \nauto_now_add\n model fields.\n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather that a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, is \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", + "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields.\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue']\n style = {'base_template': 'radio.html'}\n}\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now\n and \nauto_now_add\n model fields.\n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, is \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", "title": "Serializer fields" }, { @@ -1422,7 +1422,7 @@ }, { "location": "/api-guide/fields/#jsonfield", - "text": "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) binary - If set to True then the field will output and validate a JSON encoded string, rather that a primitive data structure. Defaults to False .", + "text": "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) 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 .", "title": "JSONField" }, { @@ -1492,7 +1492,7 @@ }, { "location": "/api-guide/relations/", - "text": "Serializer relations\n\n\n\n\nBad programmers worry about the code.\nGood programmers worry about data structures and their relationships.\n\n\n \nLinus Torvalds\n\n\n\n\nRelational fields are used to represent model relationships. They can be applied to \nForeignKey\n, \nManyToManyField\n and \nOneToOneField\n relationships, as well as to reverse relationships, and custom relationships such as \nGenericForeignKey\n.\n\n\n\n\nNote:\n The relational fields are declared in \nrelations.py\n, but by convention you should import them from the \nserializers\n module, using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nInspecting relationships.\n\n\nWhen using the \nModelSerializer\n class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nAPI Reference\n\n\nIn order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.\n\n\nclass Album(models.Model):\n album_name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks')\n order = models.IntegerField()\n title = models.CharField(max_length=100)\n duration = models.IntegerField()\n\n class Meta:\n unique_together = ('album', 'order')\n ordering = ['order']\n\n def __unicode__(self):\n return '%d: %s' % (self.order, self.title)\n\n\n\nStringRelatedField\n\n\nStringRelatedField\n may be used to represent the target of the relationship using its \n__unicode__\n method.\n\n\nFor example, the following serializer.\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.StringRelatedField(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to the following representation.\n\n\n{\n 'album_name': 'Things We Lost In The Fire',\n 'artist': 'Low',\n 'tracks': [\n '1: Sunflower',\n '2: Whitetail',\n '3: Dinosaur Act',\n ...\n ]\n}\n\n\n\nThis field is read only.\n\n\nArguments\n:\n\n\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\n\n\nPrimaryKeyRelatedField\n\n\nPrimaryKeyRelatedField\n may be used to represent the target of the relationship using its primary key.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'The Roots',\n 'artist': 'Undun',\n 'tracks': [\n 89,\n 90,\n 91,\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nArguments\n:\n\n\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\npk_field\n - Set to a field to control serialization/deserialization of the primary key's value. For example, \npk_field=UUIDField(format='hex')\n would serialize a UUID primary key into its compact hex representation.\n\n\n\n\nHyperlinkedRelatedField\n\n\nHyperlinkedRelatedField\n may be used to represent the target of the relationship using a hyperlink.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='track-detail'\n )\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'Graceland',\n 'artist': 'Paul Simon',\n 'tracks': [\n 'http://www.example.com/api/tracks/45/',\n 'http://www.example.com/api/tracks/46/',\n 'http://www.example.com/api/tracks/47/',\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\n\n\nNote\n: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the \nlookup_field\n and \nlookup_url_kwarg\n arguments.\n\n\nThis is suitable for URLs that contain a single primary key or slug argument as part of the URL.\n\n\nIf you require more complex hyperlinked representation you'll need to customize the field, as described in the \ncustom hyperlinked fields\n section, below.\n\n\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship. If you're using \nthe standard router classes\n this will be a string with the format \nmodelname\n-detail\n. \nrequired\n.\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\nSlugRelatedField\n\n\nSlugRelatedField\n may be used to represent the target of the relationship using a field on the target.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'Dear John',\n 'artist': 'Loney Dear',\n 'tracks': [\n 'Airport Surroundings',\n 'Everything Turns to You',\n 'I Was Only Going Out',\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nWhen using \nSlugRelatedField\n as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with \nunique=True\n.\n\n\nArguments\n:\n\n\n\n\nslug_field\n - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, \nusername\n. \nrequired\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\n\n\nHyperlinkedIdentityField\n\n\nThis field can be applied as an identity relationship, such as the \n'url'\n field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:\n\n\nclass AlbumSerializer(serializers.HyperlinkedModelSerializer):\n track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'track_listing')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'The Eraser',\n 'artist': 'Thom Yorke',\n 'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n\n\n\nThis field is always read-only.\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship. If you're using \nthe standard router classes\n this will be a string with the format \nmodel_name\n-detail\n. \nrequired\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\n\n\nNested relationships\n\n\nNested relationships can be expressed by using serializers as fields.\n\n\nIf the field is used to represent a to-many relationship, you should add the \nmany=True\n flag to the serializer field.\n\n\nExample\n\n\nFor example, the following serializer:\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a nested representation like this:\n\n\n album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse')\n\n Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\nTrack: Track object\n\n\n serializer = AlbumSerializer(instance=album)\n\n serializer.data\n{\n 'album_name': 'The Grey Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ...\n ],\n}\n\n\n\nWritable nested serializers\n\n\nBy default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create \ncreate()\n and/or \nupdate()\n methods in order to explicitly specify how the child relationships should be saved.\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n def create(self, validated_data):\n tracks_data = validated_data.pop('tracks')\n album = Album.objects.create(**validated_data)\n for track_data in tracks_data:\n Track.objects.create(album=album, **track_data)\n return album\n\n\n data = {\n 'album_name': 'The Grey Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ],\n}\n\n serializer = AlbumSerializer(data=data)\n\n serializer.is_valid()\nTrue\n\n serializer.save()\n\nAlbum: Album object\n\n\n\n\nCustom relational fields\n\n\nTo implement a custom relational field, you should override \nRelatedField\n, and implement the \n.to_representation(self, value)\n method. This method takes the target of the field as the \nvalue\n argument, and should return the representation that should be used to serialize the target. The \nvalue\n argument will typically be a model instance.\n\n\nIf you want to implement a read-write relational field, you must also implement the \n.to_internal_value(self, data)\n method.\n\n\nExample\n\n\nFor example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.\n\n\nimport time\n\nclass TrackListingField(serializers.RelatedField):\n def to_representation(self, value):\n duration = time.strftime('%M:%S', time.gmtime(value.duration))\n return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackListingField(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nThis custom field would then serialize to the following representation.\n\n\n{\n 'album_name': 'Sometimes I Wish We Were an Eagle',\n 'artist': 'Bill Callahan',\n 'tracks': [\n 'Track 1: Jim Cain (04:39)',\n 'Track 2: Eid Ma Clack Shaw (04:19)',\n 'Track 3: The Wind and the Dove (04:34)',\n ...\n ]\n}\n\n\n\n\n\nCustom hyperlinked fields\n\n\nIn some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.\n\n\nYou can achieve this by overriding \nHyperlinkedRelatedField\n. There are two methods that may be overridden:\n\n\nget_url(self, obj, view_name, request, format)\n\n\nThe \nget_url\n method is used to map the object instance to its URL representation.\n\n\nMay raise a \nNoReverseMatch\n if the \nview_name\n and \nlookup_field\n\nattributes are not configured to correctly match the URL conf.\n\n\nget_object(self, queryset, view_name, view_args, view_kwargs)\n\n\nIf you want to support a writable hyperlinked field then you'll also want to override \nget_object\n, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.\n\n\nThe return value of this method should the object that corresponds to the matched URL conf arguments.\n\n\nMay raise an \nObjectDoesNotExist\n exception.\n\n\nExample\n\n\nSay we have a URL for a customer object that takes two keyword arguments, like so:\n\n\n/api/\norganization_slug\n/customers/\ncustomer_pk\n/\n\n\n\nThis cannot be represented with the default implementation, which accepts only a single lookup field.\n\n\nIn this case we'd need to override \nHyperlinkedRelatedField\n to get the behavior we want:\n\n\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs)\n\n\n\nNote that if you wanted to use this style together with the generic views then you'd also need to override \n.get_object\n on the view in order to get the correct lookup behavior.\n\n\nGenerally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.\n\n\n\n\nFurther notes\n\n\nThe \nqueryset\n argument\n\n\nThe \nqueryset\n argument is only ever required for \nwritable\n relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.\n\n\nIn version 2.x a serializer class could \nsometimes\n automatically determine the \nqueryset\n argument \nif\n a \nModelSerializer\n class was being used.\n\n\nThis behavior is now replaced with \nalways\n using an explicit \nqueryset\n argument for writable relational fields.\n\n\nDoing so reduces the amount of hidden 'magic' that \nModelSerializer\n provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the \nModelSerializer\n shortcut, or using fully explicit \nSerializer\n classes.\n\n\nCustomizing the HTML display\n\n\nThe built-in \n__str__\n method of the model will be used to generate string representations of the objects used to populate the \nchoices\n property. These choices are used to populate select HTML inputs in the browsable API.\n\n\nTo provide customized representations for such inputs, override \ndisplay_value()\n of a \nRelatedField\n subclass. This method will receive a model object, and should return a string suitable for representing it. For example:\n\n\nclass TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):\n def display_value(self, instance):\n return 'Track: %s' % (instance.title)\n\n\n\nSelect field cutoffs\n\n\nWhen rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with \"More than 1000 items\u2026\" will be displayed.\n\n\nThis behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.\n\n\nThere are two keyword arguments you can use to control this behavior:\n\n\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to \nNone\n to disable any limiting. Defaults to \n1000\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nIn cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the \nstyle\n keyword argument. For example:\n\n\nassigned_to = serializers.SlugRelatedField(\n queryset=User.objects.all(),\n slug field='username',\n style={'base_template': 'input.html'}\n)\n\n\n\nReverse relations\n\n\nNote that reverse relationships are not automatically included by the \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n class Meta:\n fields = ('tracks', ...)\n\n\n\nYou'll normally want to ensure that you've set an appropriate \nrelated_name\n argument on the relationship, that you can use as the field name. For example:\n\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks')\n ...\n\n\n\nIf you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the \nfields\n argument. For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n class Meta:\n fields = ('track_set', ...)\n\n\n\nSee the Django documentation on \nreverse relationships\n for more details.\n\n\nGeneric relationships\n\n\nIf you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.\n\n\nFor example, given the following model for a tag, which has a generic relationship with other arbitrary models:\n\n\nclass TaggedItem(models.Model):\n \"\"\"\n Tags arbitrary model instances using a generic relation.\n\n See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n tagged_object = GenericForeignKey('content_type', 'object_id')\n\n def __unicode__(self):\n return self.tag_name\n\n\n\nAnd the following two models, which may be have associated tags:\n\n\nclass Bookmark(models.Model):\n \"\"\"\n A bookmark consists of a URL, and 0 or more descriptive tags.\n \"\"\"\n url = models.URLField()\n tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n \"\"\"\n A note consists of some text, and 0 or more descriptive tags.\n \"\"\"\n text = models.CharField(max_length=1000)\n tags = GenericRelation(TaggedItem)\n\n\n\nWe could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.\n\n\nclass TaggedObjectRelatedField(serializers.RelatedField):\n \"\"\"\n A custom field to use for the `tagged_object` generic relationship.\n \"\"\"\n\n def to_representation(self, value):\n \"\"\"\n Serialize tagged objects to a simple textual representation.\n \"\"\"\n if isinstance(value, Bookmark):\n return 'Bookmark: ' + value.url\n elif isinstance(value, Note):\n return 'Note: ' + value.text\n raise Exception('Unexpected type of tagged object')\n\n\n\nIf you need the target of the relationship to have a nested representation, you can use the required serializers inside the \n.to_representation()\n method:\n\n\n def to_representation(self, value):\n \"\"\"\n Serialize bookmark instances using a bookmark serializer,\n and note instances using a note serializer.\n \"\"\"\n if isinstance(value, Bookmark):\n serializer = BookmarkSerializer(value)\n elif isinstance(value, Note):\n serializer = NoteSerializer(value)\n else:\n raise Exception('Unexpected type of tagged object')\n\n return serializer.data\n\n\n\nNote that reverse generic keys, expressed using the \nGenericRelation\n field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.\n\n\nFor more information see \nthe Django documentation on generic relations\n.\n\n\nManyToManyFields with a Through Model\n\n\nBy default, relational fields that target a \nManyToManyField\n with a\n\nthrough\n model specified are set to read-only.\n\n\nIf you explicitly specify a relational field pointing to a\n\nManyToManyField\n with a through model, be sure to set \nread_only\n\nto \nTrue\n.\n\n\n\n\nThird Party Packages\n\n\nThe following third party packages are also available.\n\n\nDRF Nested Routers\n\n\nThe \ndrf-nested-routers package\n provides routers and relationship fields for working with nested resources.", + "text": "Serializer relations\n\n\n\n\nBad programmers worry about the code.\nGood programmers worry about data structures and their relationships.\n\n\n \nLinus Torvalds\n\n\n\n\nRelational fields are used to represent model relationships. They can be applied to \nForeignKey\n, \nManyToManyField\n and \nOneToOneField\n relationships, as well as to reverse relationships, and custom relationships such as \nGenericForeignKey\n.\n\n\n\n\nNote:\n The relational fields are declared in \nrelations.py\n, but by convention you should import them from the \nserializers\n module, using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nInspecting relationships.\n\n\nWhen using the \nModelSerializer\n class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nAPI Reference\n\n\nIn order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.\n\n\nclass Album(models.Model):\n album_name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks')\n order = models.IntegerField()\n title = models.CharField(max_length=100)\n duration = models.IntegerField()\n\n class Meta:\n unique_together = ('album', 'order')\n ordering = ['order']\n\n def __unicode__(self):\n return '%d: %s' % (self.order, self.title)\n\n\n\nStringRelatedField\n\n\nStringRelatedField\n may be used to represent the target of the relationship using its \n__unicode__\n method.\n\n\nFor example, the following serializer.\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.StringRelatedField(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to the following representation.\n\n\n{\n 'album_name': 'Things We Lost In The Fire',\n 'artist': 'Low',\n 'tracks': [\n '1: Sunflower',\n '2: Whitetail',\n '3: Dinosaur Act',\n ...\n ]\n}\n\n\n\nThis field is read only.\n\n\nArguments\n:\n\n\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\n\n\nPrimaryKeyRelatedField\n\n\nPrimaryKeyRelatedField\n may be used to represent the target of the relationship using its primary key.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'The Roots',\n 'artist': 'Undun',\n 'tracks': [\n 89,\n 90,\n 91,\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nArguments\n:\n\n\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\npk_field\n - Set to a field to control serialization/deserialization of the primary key's value. For example, \npk_field=UUIDField(format='hex')\n would serialize a UUID primary key into its compact hex representation.\n\n\n\n\nHyperlinkedRelatedField\n\n\nHyperlinkedRelatedField\n may be used to represent the target of the relationship using a hyperlink.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='track-detail'\n )\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'Graceland',\n 'artist': 'Paul Simon',\n 'tracks': [\n 'http://www.example.com/api/tracks/45/',\n 'http://www.example.com/api/tracks/46/',\n 'http://www.example.com/api/tracks/47/',\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\n\n\nNote\n: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the \nlookup_field\n and \nlookup_url_kwarg\n arguments.\n\n\nThis is suitable for URLs that contain a single primary key or slug argument as part of the URL.\n\n\nIf you require more complex hyperlinked representation you'll need to customize the field, as described in the \ncustom hyperlinked fields\n section, below.\n\n\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship. If you're using \nthe standard router classes\n this will be a string with the format \nmodelname\n-detail\n. \nrequired\n.\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\nSlugRelatedField\n\n\nSlugRelatedField\n may be used to represent the target of the relationship using a field on the target.\n\n\nFor example, the following serializer:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'Dear John',\n 'artist': 'Loney Dear',\n 'tracks': [\n 'Airport Surroundings',\n 'Everything Turns to You',\n 'I Was Only Going Out',\n ...\n ]\n}\n\n\n\nBy default this field is read-write, although you can change this behavior using the \nread_only\n flag.\n\n\nWhen using \nSlugRelatedField\n as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with \nunique=True\n.\n\n\nArguments\n:\n\n\n\n\nslug_field\n - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, \nusername\n. \nrequired\n\n\nqueryset\n - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set \nread_only=True\n.\n\n\nmany\n - If applied to a to-many relationship, you should set this argument to \nTrue\n.\n\n\nallow_null\n - If set to \nTrue\n, the field will accept values of \nNone\n or the empty string for nullable relationships. Defaults to \nFalse\n.\n\n\n\n\nHyperlinkedIdentityField\n\n\nThis field can be applied as an identity relationship, such as the \n'url'\n field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:\n\n\nclass AlbumSerializer(serializers.HyperlinkedModelSerializer):\n track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'track_listing')\n\n\n\nWould serialize to a representation like this:\n\n\n{\n 'album_name': 'The Eraser',\n 'artist': 'Thom Yorke',\n 'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n\n\n\nThis field is always read-only.\n\n\nArguments\n:\n\n\n\n\nview_name\n - The view name that should be used as the target of the relationship. If you're using \nthe standard router classes\n this will be a string with the format \nmodel_name\n-detail\n. \nrequired\n.\n\n\nlookup_field\n - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is \n'pk'\n.\n\n\nlookup_url_kwarg\n - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as \nlookup_field\n.\n\n\nformat\n - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the \nformat\n argument.\n\n\n\n\n\n\nNested relationships\n\n\nNested relationships can be expressed by using serializers as fields.\n\n\nIf the field is used to represent a to-many relationship, you should add the \nmany=True\n flag to the serializer field.\n\n\nExample\n\n\nFor example, the following serializer:\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nWould serialize to a nested representation like this:\n\n\n album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse')\n\n Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n\nTrack: Track object\n\n\n Track.objects.create(album=album, order=3, title='Encore', duration=159)\n\nTrack: Track object\n\n\n serializer = AlbumSerializer(instance=album)\n\n serializer.data\n{\n 'album_name': 'The Grey Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ...\n ],\n}\n\n\n\nWritable nested serializers\n\n\nBy default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create \ncreate()\n and/or \nupdate()\n methods in order to explicitly specify how the child relationships should be saved.\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ('order', 'title', 'duration')\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n def create(self, validated_data):\n tracks_data = validated_data.pop('tracks')\n album = Album.objects.create(**validated_data)\n for track_data in tracks_data:\n Track.objects.create(album=album, **track_data)\n return album\n\n\n data = {\n 'album_name': 'The Grey Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ],\n}\n\n serializer = AlbumSerializer(data=data)\n\n serializer.is_valid()\nTrue\n\n serializer.save()\n\nAlbum: Album object\n\n\n\n\nCustom relational fields\n\n\nTo implement a custom relational field, you should override \nRelatedField\n, and implement the \n.to_representation(self, value)\n method. This method takes the target of the field as the \nvalue\n argument, and should return the representation that should be used to serialize the target. The \nvalue\n argument will typically be a model instance.\n\n\nIf you want to implement a read-write relational field, you must also implement the \n.to_internal_value(self, data)\n method.\n\n\nExample\n\n\nFor example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.\n\n\nimport time\n\nclass TrackListingField(serializers.RelatedField):\n def to_representation(self, value):\n duration = time.strftime('%M:%S', time.gmtime(value.duration))\n return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackListingField(many=True)\n\n class Meta:\n model = Album\n fields = ('album_name', 'artist', 'tracks')\n\n\n\nThis custom field would then serialize to the following representation.\n\n\n{\n 'album_name': 'Sometimes I Wish We Were an Eagle',\n 'artist': 'Bill Callahan',\n 'tracks': [\n 'Track 1: Jim Cain (04:39)',\n 'Track 2: Eid Ma Clack Shaw (04:19)',\n 'Track 3: The Wind and the Dove (04:34)',\n ...\n ]\n}\n\n\n\n\n\nCustom hyperlinked fields\n\n\nIn some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.\n\n\nYou can achieve this by overriding \nHyperlinkedRelatedField\n. There are two methods that may be overridden:\n\n\nget_url(self, obj, view_name, request, format)\n\n\nThe \nget_url\n method is used to map the object instance to its URL representation.\n\n\nMay raise a \nNoReverseMatch\n if the \nview_name\n and \nlookup_field\n\nattributes are not configured to correctly match the URL conf.\n\n\nget_object(self, queryset, view_name, view_args, view_kwargs)\n\n\nIf you want to support a writable hyperlinked field then you'll also want to override \nget_object\n, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.\n\n\nThe return value of this method should the object that corresponds to the matched URL conf arguments.\n\n\nMay raise an \nObjectDoesNotExist\n exception.\n\n\nExample\n\n\nSay we have a URL for a customer object that takes two keyword arguments, like so:\n\n\n/api/\norganization_slug\n/customers/\ncustomer_pk\n/\n\n\n\nThis cannot be represented with the default implementation, which accepts only a single lookup field.\n\n\nIn this case we'd need to override \nHyperlinkedRelatedField\n to get the behavior we want:\n\n\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs)\n\n\n\nNote that if you wanted to use this style together with the generic views then you'd also need to override \n.get_object\n on the view in order to get the correct lookup behavior.\n\n\nGenerally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.\n\n\n\n\nFurther notes\n\n\nThe \nqueryset\n argument\n\n\nThe \nqueryset\n argument is only ever required for \nwritable\n relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.\n\n\nIn version 2.x a serializer class could \nsometimes\n automatically determine the \nqueryset\n argument \nif\n a \nModelSerializer\n class was being used.\n\n\nThis behavior is now replaced with \nalways\n using an explicit \nqueryset\n argument for writable relational fields.\n\n\nDoing so reduces the amount of hidden 'magic' that \nModelSerializer\n provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the \nModelSerializer\n shortcut, or using fully explicit \nSerializer\n classes.\n\n\nCustomizing the HTML display\n\n\nThe built-in \n__str__\n method of the model will be used to generate string representations of the objects used to populate the \nchoices\n property. These choices are used to populate select HTML inputs in the browsable API.\n\n\nTo provide customized representations for such inputs, override \ndisplay_value()\n of a \nRelatedField\n subclass. This method will receive a model object, and should return a string suitable for representing it. For example:\n\n\nclass TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):\n def display_value(self, instance):\n return 'Track: %s' % (instance.title)\n\n\n\nSelect field cutoffs\n\n\nWhen rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with \"More than 1000 items\u2026\" will be displayed.\n\n\nThis behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.\n\n\nThere are two keyword arguments you can use to control this behavior:\n\n\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to \nNone\n to disable any limiting. Defaults to \n1000\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nIn cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the \nstyle\n keyword argument. For example:\n\n\nassigned_to = serializers.SlugRelatedField(\n queryset=User.objects.all(),\n slug field='username',\n style={'base_template': 'input.html'}\n)\n\n\n\nReverse relations\n\n\nNote that reverse relationships are not automatically included by the \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n class Meta:\n fields = ('tracks', ...)\n\n\n\nYou'll normally want to ensure that you've set an appropriate \nrelated_name\n argument on the relationship, that you can use as the field name. For example:\n\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks')\n ...\n\n\n\nIf you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the \nfields\n argument. For example:\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n class Meta:\n fields = ('track_set', ...)\n\n\n\nSee the Django documentation on \nreverse relationships\n for more details.\n\n\nGeneric relationships\n\n\nIf you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.\n\n\nFor example, given the following model for a tag, which has a generic relationship with other arbitrary models:\n\n\nclass TaggedItem(models.Model):\n \"\"\"\n Tags arbitrary model instances using a generic relation.\n\n See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n tagged_object = GenericForeignKey('content_type', 'object_id')\n\n def __unicode__(self):\n return self.tag_name\n\n\n\nAnd the following two models, which may be have associated tags:\n\n\nclass Bookmark(models.Model):\n \"\"\"\n A bookmark consists of a URL, and 0 or more descriptive tags.\n \"\"\"\n url = models.URLField()\n tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n \"\"\"\n A note consists of some text, and 0 or more descriptive tags.\n \"\"\"\n text = models.CharField(max_length=1000)\n tags = GenericRelation(TaggedItem)\n\n\n\nWe could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.\n\n\nclass TaggedObjectRelatedField(serializers.RelatedField):\n \"\"\"\n A custom field to use for the `tagged_object` generic relationship.\n \"\"\"\n\n def to_representation(self, value):\n \"\"\"\n Serialize tagged objects to a simple textual representation.\n \"\"\"\n if isinstance(value, Bookmark):\n return 'Bookmark: ' + value.url\n elif isinstance(value, Note):\n return 'Note: ' + value.text\n raise Exception('Unexpected type of tagged object')\n\n\n\nIf you need the target of the relationship to have a nested representation, you can use the required serializers inside the \n.to_representation()\n method:\n\n\n def to_representation(self, value):\n \"\"\"\n Serialize bookmark instances using a bookmark serializer,\n and note instances using a note serializer.\n \"\"\"\n if isinstance(value, Bookmark):\n serializer = BookmarkSerializer(value)\n elif isinstance(value, Note):\n serializer = NoteSerializer(value)\n else:\n raise Exception('Unexpected type of tagged object')\n\n return serializer.data\n\n\n\nNote that reverse generic keys, expressed using the \nGenericRelation\n field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.\n\n\nFor more information see \nthe Django documentation on generic relations\n.\n\n\nManyToManyFields with a Through Model\n\n\nBy default, relational fields that target a \nManyToManyField\n with a\n\nthrough\n model specified are set to read-only.\n\n\nIf you explicitly specify a relational field pointing to a\n\nManyToManyField\n with a through model, be sure to set \nread_only\n\nto \nTrue\n.\n\n\n\n\nThird Party Packages\n\n\nThe following third party packages are also available.\n\n\nDRF Nested Routers\n\n\nThe \ndrf-nested-routers package\n provides routers and relationship fields for working with nested resources.", "title": "Serializer relations" }, { @@ -1562,7 +1562,7 @@ }, { "location": "/api-guide/relations/#example_2", - "text": "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\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs) 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.", + "text": "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\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs) 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.", "title": "Example" }, { @@ -2652,7 +2652,7 @@ }, { "location": "/topics/html-and-forms/", - "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n {% for profile in profiles %}\n \nli\n{{ profile.name }}\n/li\n\n {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk '%}\" method=\"POST\"\n\n {% csrf_token %}\n {% render_form serializer %}\n \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n \u2026\n \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer %}\n \ndiv class=\"form-group\"\n\n \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n \n/div\n\n \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\n or relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\n or relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\n or nested serializer with \nmany=True\n\n\nhide_label", + "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n {% for profile in profiles %}\n \nli\n{{ profile.name }}\n/li\n\n {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk '%}\" method=\"POST\"\n\n {% csrf_token %}\n {% render_form serializer %}\n \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n \u2026\n \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer %}\n \ndiv class=\"form-group\"\n\n \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n \n/div\n\n \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\n or relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\n or relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\n or nested serializer with \nmany=True\n\n\nhide_label", "title": "HTML & Forms" }, { @@ -2662,7 +2662,7 @@ }, { "location": "/topics/html-and-forms/#rendering-html", - "text": "In order to return HTML responses you'll need to either TemplateHTMLRenderer , or StaticHTMLRenderer . The TemplateHTMLRenderer class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response. The StaticHTMLRender class expects the response to contain a string of the pre-rendered HTML content. Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views. Here's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template: views.py : from my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset}) profile_list.html : html body h1 Profiles /h1 ul \n {% for profile in profiles %}\n li {{ profile.name }} /li \n {% endfor %} /ul /body /html", + "text": "In order to return HTML responses you'll need to either TemplateHTMLRenderer , or StaticHTMLRenderer . The TemplateHTMLRenderer class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response. The StaticHTMLRender class expects the response to contain a string of the pre-rendered HTML content. Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views. Here's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template: views.py : from my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset}) profile_list.html : html body h1 Profiles /h1 ul \n {% for profile in profiles %}\n li {{ profile.name }} /li \n {% endfor %} /ul /body /html", "title": "Rendering HTML" }, { @@ -2767,7 +2767,7 @@ }, { "location": "/topics/third-party-resources/", - "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.\n\n\nIf you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\nPyowa July 2013 - Django Rest Framework (Video)\n\n\ndjango-rest-framework and angularjs (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework", + "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.\n\n\nIf you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\ndjango-rest-framework-version-transforms\n - Enables the use of delta transformations for versioning of DRF resource representations.\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\nPyowa July 2013 - Django Rest Framework (Video)\n\n\ndjango-rest-framework and angularjs (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework", "title": "Third Party Resources" }, { @@ -2787,7 +2787,7 @@ }, { "location": "/topics/third-party-resources/#existing-third-party-packages", - "text": "Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages . To submit new content, open an issue or create a pull request . Authentication djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. doac - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. 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. Permissions drf-any-permissions - Provides alternative permission handling. djangorestframework-composed-permissions - Provides a simple way to define complex permissions. rest_condition - Another extension for building complex permissions in a simple and convenient way. dry-rest-permissions - Provides a simple way to define permissions for individual api actions. 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. 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 djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. 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 djangorestframework-msgpack - Provides MessagePack renderer and parser support. djangorestframework-camel-case - Provides camel case JSON renderers and parsers. Renderers djangorestframework-csv - Provides CSV renderer support. drf_ujson - Implements JSON rendering using the UJSON package. rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats. 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. Misc cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. django-rest-swagger - An API documentation generator for Swagger UI. django-rest-framework-proxy - Proxy to redirect incoming request to another API server. gaiarestframework - Utils for django-rest-framework drf-extensions - A collection of custom extensions ember-django-adapter - An adapter for working with Ember.js django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . drf-tracking - Utilities to track requests to DRF API views. django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm , which are adapters between DRF serializers and Django forms. drf-haystack - Haystack search for Django Rest Framework", + "text": "Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages . To submit new content, open an issue or create a pull request . Authentication djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. doac - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. 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. Permissions drf-any-permissions - Provides alternative permission handling. djangorestframework-composed-permissions - Provides a simple way to define complex permissions. rest_condition - Another extension for building complex permissions in a simple and convenient way. dry-rest-permissions - Provides a simple way to define permissions for individual api actions. 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. 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 djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. 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 djangorestframework-msgpack - Provides MessagePack renderer and parser support. djangorestframework-camel-case - Provides camel case JSON renderers and parsers. Renderers djangorestframework-csv - Provides CSV renderer support. drf_ujson - Implements JSON rendering using the UJSON package. rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats. 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. Misc cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. django-rest-swagger - An API documentation generator for Swagger UI. django-rest-framework-proxy - Proxy to redirect incoming request to another API server. gaiarestframework - Utils for django-rest-framework drf-extensions - A collection of custom extensions ember-django-adapter - An adapter for working with Ember.js django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . drf-tracking - Utilities to track requests to DRF API views. django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm , which are adapters between DRF serializers and Django forms. drf-haystack - Haystack search for Django Rest Framework django-rest-framework-version-transforms - Enables the use of delta transformations for versioning of DRF resource representations.", "title": "Existing Third Party Packages" }, { @@ -3047,7 +3047,7 @@ }, { "location": "/topics/3.3-announcement/", - "text": "Django REST framework 3.3\n\n\nThe 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding \nthank you\n to all our wonderful sponsors and supporters.\n\n\nThe amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned \n refined large parts of the project.\n\n\nIn order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow \n@_tomchristie\n to keep up to date with these announcements, and be among the first set of sign ups.\n\n\nWe strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished \n professional product.\n\n\n\n\nRelease notes\n\n\nSignificant new functionality in the 3.3 release includes:\n\n\n\n\nFilters presented as HTML controls in the browsable API.\n\n\nA \nforms API\n, allowing serializers to be rendered as HTML forms.\n\n\nDjango 1.9 support.\n\n\nA \nJSONField\n serializer field\n, corresponding to Django 1.9's Postgres \nJSONField\n model field.\n\n\nBrowsable API support \nvia AJAX\n, rather than server side request overloading.\n\n\n\n\n\n\nExample of the new filter controls\n\n\n\n\nSupported versions\n\n\nThis release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.\n\n\nThis brings our supported versions into line with Django's \ncurrently supported versions\n\n\nDeprecations\n\n\nThe AJAX based support for the browsable API means that there are a number of internal cleanups in the \nrequest\n class. For the vast majority of developers this should largely remain transparent:\n\n\n\n\nTo support form based \nPUT\n and \nDELETE\n, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-forms] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.\n\n\nThe \naccept\n query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to \nuse a custom content negotiation class\n.\n\n\nThe custom \nHTTP_X_HTTP_METHOD_OVERRIDE\n header is no longer supported by default. If you require it then you'll need to \nuse custom middleware\n.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nThe \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes should now include either a \nfields\n or \nexclude\n option, although the \nfields = '__all__'\n shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings \nModelSerializer\n more closely in line with Django's \nModelForm\n behavior.", + "text": "Django REST framework 3.3\n\n\nThe 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding \nthank you\n to all our wonderful sponsors and supporters.\n\n\nThe amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned \n refined large parts of the project.\n\n\nIn order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow \n@_tomchristie\n to keep up to date with these announcements, and be among the first set of sign ups.\n\n\nWe strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished \n professional product.\n\n\n\n\nRelease notes\n\n\nSignificant new functionality in the 3.3 release includes:\n\n\n\n\nFilters presented as HTML controls in the browsable API.\n\n\nA \nforms API\n, allowing serializers to be rendered as HTML forms.\n\n\nDjango 1.9 support.\n\n\nA \nJSONField\n serializer field\n, corresponding to Django 1.9's Postgres \nJSONField\n model field.\n\n\nBrowsable API support \nvia AJAX\n, rather than server side request overloading.\n\n\n\n\n\n\nExample of the new filter controls\n\n\n\n\nSupported versions\n\n\nThis release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.\n\n\nThis brings our supported versions into line with Django's \ncurrently supported versions\n\n\nDeprecations\n\n\nThe AJAX based support for the browsable API means that there are a number of internal cleanups in the \nrequest\n class. For the vast majority of developers this should largely remain transparent:\n\n\n\n\nTo support form based \nPUT\n and \nDELETE\n, or to support form content types such as JSON, you should now use the \nAJAX forms\n javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.\n\n\nThe \naccept\n query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to \nuse a custom content negotiation class\n.\n\n\nThe custom \nHTTP_X_HTTP_METHOD_OVERRIDE\n header is no longer supported by default. If you require it then you'll need to \nuse custom middleware\n.\n\n\n\n\nThe following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.\n\n\n\n\nview.paginate_by\n - Use \npaginator.page_size\n instead.\n\n\nview.page_query_param\n - Use \npaginator.page_query_param\n instead.\n\n\nview.paginate_by_param\n - Use \npaginator.page_size_query_param\n instead.\n\n\nview.max_paginate_by\n - Use \npaginator.max_page_size\n instead.\n\n\nsettings.PAGINATE_BY\n - Use \npaginator.page_size\n instead.\n\n\nsettings.PAGINATE_BY_PARAM\n - Use \npaginator.page_size_query_param\n instead.\n\n\nsettings.MAX_PAGINATE_BY\n - Use \npaginator.max_page_size\n instead.\n\n\n\n\nThe \nModelSerializer\n and \nHyperlinkedModelSerializer\n classes should now include either a \nfields\n or \nexclude\n option, although the \nfields = '__all__'\n shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings \nModelSerializer\n more closely in line with Django's \nModelForm\n behavior.", "title": "3.3 Announcement" }, { @@ -3067,7 +3067,7 @@ }, { "location": "/topics/3.3-announcement/#deprecations", - "text": "The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent: To support form based PUT and DELETE , or to support form content types such as JSON, you should now use the [AJAX forms][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.", + "text": "The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent: To support form based PUT and DELETE , or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. The accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class . The custom HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware . The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. view.paginate_by - Use paginator.page_size instead. view.page_query_param - Use paginator.page_query_param instead. view.paginate_by_param - Use paginator.page_size_query_param instead. view.max_paginate_by - Use paginator.max_page_size instead. settings.PAGINATE_BY - Use paginator.page_size instead. settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead. settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead. The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.", "title": "Deprecations" }, { @@ -3092,7 +3092,7 @@ }, { "location": "/topics/release-notes/", - "text": "Release Notes\n\n\n\n\nRelease Early, Release Often\n\n\n Eric S. Raymond, \nThe Cathedral and the Bazaar\n.\n\n\n\n\nVersioning\n\n\nMinor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.\n\n\nMedium version numbers (0.x.0) may include API changes, in line with the \ndeprecation policy\n. You should read the release notes carefully before upgrading between medium point releases.\n\n\nMajor version numbers (x.0.0) are reserved for substantial project milestones.\n\n\nDeprecation policy\n\n\nREST framework releases follow a formal deprecation policy, which is in line with \nDjango's deprecation policy\n.\n\n\nThe timeline for deprecation of a feature present in version 1.0 would work as follows:\n\n\n\n\n\n\nVersion 1.1 would remain \nfully backwards compatible\n with 1.0, but would raise \nPendingDeprecationWarning\n warnings if you use the feature that are due to be deprecated. These warnings are \nsilent by default\n, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using \npython -Wd manage.py test\n, you'll be warned of any API changes you need to make.\n\n\n\n\n\n\nVersion 1.2 would escalate these warnings to \nDeprecationWarning\n, which is loud by default.\n\n\n\n\n\n\nVersion 1.3 would remove the deprecated bits of API entirely.\n\n\n\n\n\n\nNote that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.\n\n\nUpgrading\n\n\nTo upgrade Django REST framework to the latest version, use pip:\n\n\npip install -U djangorestframework\n\n\n\nYou can determine your currently installed version using \npip freeze\n:\n\n\npip freeze | grep djangorestframework\n\n\n\n\n\n3.3.x series\n\n\n3.3.0\n\n\nDate\n: \n28th October 2015\n.\n\n\n\n\nHTML controls for filters. (\n#3315\n)\n\n\nForms API. (\n#3475\n)\n\n\nAJAX browsable API. (\n#3410\n)\n\n\nAdded JSONField. (\n#3454\n)\n\n\nCorrectly map \nto_field\n when creating \nModelSerializer\n relational fields. (\n#3526\n)\n\n\nInclude keyword arguments when mapping \nFilePathField\n to a serializer field. (\n#3536\n)\n\n\nMap appropriate model \nerror_messages\n on \nModelSerializer\n uniqueness constraints. (\n#3435\n)\n\n\nInclude \nmax_length\n constraint for \nModelSerializer\n fields mapped from TextField. (\n#3509\n)\n\n\nAdded support for Django 1.9. (\n#3450\n, \n#3525\n)\n\n\nRemoved support for Django 1.5 \n 1.6. (\n#3421\n, \n#3429\n)\n\n\nRemoved 'south' migrations. (\n#3495\n)\n\n\n\n\n3.2.x series\n\n\n3.2.5\n\n\nDate\n: \n27th October 2015\n.\n\n\n\n\nEscape \nusername\n in optional logout tag. (\n#3550\n)\n\n\n\n\n3.2.4\n\n\nDate\n: \n21th September 2015\n.\n\n\n\n\nDon't error on missing \nViewSet.search_fields\n attribute. (\n#3324\n, \n#3323\n)\n\n\nFix \nallow_empty\n not working on serializers with \nmany=True\n. (\n#3361\n, \n#3364\n)\n\n\nLet \nDurationField\n accepts integers. (\n#3359\n)\n\n\nMulti-level dictionaries not supported in multipart requests. (\n#3314\n)\n\n\nFix \nListField\n truncation on HTTP PATCH (\n#3415\n, \n#2761\n)\n\n\n\n\n3.2.3\n\n\nDate\n: \n24th August 2015\n.\n\n\n\n\nAdded \nhtml_cutoff\n and \nhtml_cutoff_text\n for limiting select dropdowns. (\n#3313\n)\n\n\nAdded regex style to \nSearchFilter\n. (\n#3316\n)\n\n\nResolve issues with setting blank HTML fields. (\n#3318\n) (\n#3321\n)\n\n\nCorrectly display existing 'select multiple' values in browsable API forms. (\n#3290\n)\n\n\nResolve duplicated validation message for \nIPAddressField\n. ([#3249[gh3249]) (\n#3250\n)\n\n\nFix to ensure admin renderer continues to work when pagination is disabled. (\n#3275\n)\n\n\nResolve error with \nLimitOffsetPagination\n when count=0, offset=0. (\n#3303\n)\n\n\n\n\n3.2.2\n\n\nDate\n: \n13th August 2015\n.\n\n\n\n\nAdd \ndisplay_value()\n method for use when displaying relational field select inputs. (\n#3254\n)\n\n\nFix issue with \nBooleanField\n checkboxes incorrectly displaying as checked. (\n#3258\n)\n\n\nEnsure empty checkboxes properly set \nBooleanField\n to \nFalse\n in all cases. (\n#2776\n)\n\n\nAllow \nWSGIRequest.FILES\n property without raising incorrect deprecated error. (\n#3261\n)\n\n\nResolve issue with rendering nested serializers in forms. (\n#3260\n)\n\n\nRaise an error if user accidentally pass a serializer instance to a response, rather than data. (\n#3241\n)\n\n\n\n\n3.2.1\n\n\nDate\n: \n7th August 2015\n.\n\n\n\n\nFix for relational select widgets rendering without any choices. (\n#3237\n)\n\n\nFix for \n1\n, \n0\n rendering as \ntrue\n, \nfalse\n in the admin interface. \n#3227\n)\n\n\nFix for ListFields with single value in HTML form input. (\n#3238\n)\n\n\nAllow \nrequest.FILES\n for compat with Django's \nHTTPRequest\n class. (\n#3239\n)\n\n\n\n\n3.2.0\n\n\nDate\n: \n6th August 2015\n.\n\n\n\n\nAdd \nAdminRenderer\n. (\n#2926\n)\n\n\nAdd \nFilePathField\n. (\n#1854\n)\n\n\nAdd \nallow_empty\n to \nListField\n. (\n#2250\n)\n\n\nSupport django-guardian 1.3. (\n#3165\n)\n\n\nSupport grouped choices. (\n#3225\n)\n\n\nSupport error forms in browsable API. (\n#3024\n)\n\n\nAllow permission classes to customize the error message. (\n#2539\n)\n\n\nSupport \nsource=\nmethod\n on hyperlinked fields. (\n#2690\n)\n\n\nListField(allow_null=True)\n now allows null as the list value, not null items in the list. (\n#2766\n)\n\n\nManyToMany()\n maps to \nallow_empty=False\n, \nManyToMany(blank=True)\n maps to \nallow_empty=True\n. (\n#2804\n)\n\n\nSupport custom serialization styles for primary key fields. (\n#2789\n)\n\n\nOPTIONS\n requests support nested representations. (\n#2915\n)\n\n\nSet \nview.action == \"metadata\"\n for viewsets with \nOPTIONS\n requests. (\n#3115\n)\n\n\nSupport \nallow_blank\n on \nUUIDField\n. ([#3130][gh#3130])\n\n\nDo not display view docstrings with 401 or 403 response codes. (\n#3216\n)\n\n\nResolve Django 1.8 deprecation warnings. (\n#2886\n)\n\n\nFix for \nDecimalField\n validation. (\n#3139\n)\n\n\nFix behavior of \nallow_blank=False\n when used with \ntrim_whitespace=True\n. (\n#2712\n)\n\n\nFix issue with some field combinations incorrectly mapping to an invalid \nallow_blank\n argument. (\n#3011\n)\n\n\nFix for output representations with prefetches and modified querysets. (\n#2704\n, \n#2727\n)\n\n\nFix assertion error when CursorPagination is provided with certains invalid query parameters. (#2920)\ngh2920\n.\n\n\nFix \nUnicodeDecodeError\n when invalid characters included in header with \nTokenAuthentication\n. (\n#2928\n)\n\n\nFix transaction rollbacks with \n@non_atomic_requests\n decorator. (\n#3016\n)\n\n\nFix duplicate results issue with Oracle databases using \nSearchFilter\n. (\n#2935\n)\n\n\nFix checkbox alignment and rendering in browsable API forms. (\n#2783\n)\n\n\nFix for unsaved file objects which should use \n\"url\": null\n in the representation. (\n#2759\n)\n\n\nFix field value rendering in browsable API. (\n#2416\n)\n\n\nFix \nHStoreField\n to include \nallow_blank=True\n in \nDictField\n mapping. (\n#2659\n)\n\n\nNumerous other cleanups, improvements to error messaging, private API \n minor fixes.\n\n\n\n\n\n\n3.1.x series\n\n\n3.1.3\n\n\nDate\n: \n4th June 2015\n.\n\n\n\n\nAdd \nDurationField\n. (\n#2481\n, \n#2989\n)\n\n\nAdd \nformat\n argument to \nUUIDField\n. (\n#2788\n, \n#3000\n)\n\n\nMultipleChoiceField\n empties incorrectly on a partial update using multipart/form-data (\n#2993\n, \n#2894\n)\n\n\nFix a bug in options related to read-only \nRelatedField\n. (\n#2981\n, \n#2811\n)\n\n\nFix nested serializers with \nunique_together\n relations. (\n#2975\n)\n\n\nAllow unexpected values for \nChoiceField\n/\nMultipleChoiceField\n representations. (\n#2839\n, \n#2940\n)\n\n\nRollback the transaction on error if \nATOMIC_REQUESTS\n is set. (\n#2887\n, \n#2034\n)\n\n\nSet the action on a view when override_method regardless of its None-ness. (\n#2933\n)\n\n\nDecimalField\n accepts \n2E+2\n as 200 and validates decimal place correctly. (\n#2948\n, \n#2947\n)\n\n\nSupport basic authentication with custom \nUserModel\n that change \nusername\n. (\n#2952\n)\n\n\nIPAddressField\n improvements. (\n#2747\n, \n#2618\n, \n#3008\n)\n\n\nImprove \nDecimalField\n for easier subclassing. (\n#2695\n)\n\n\n\n\n3.1.2\n\n\nDate\n: \n13rd May 2015\n.\n\n\n\n\nDateField.to_representation\n can handle str and empty values. (\n#2656\n, \n#2687\n, \n#2869\n)\n\n\nUse default reason phrases from HTTP standard. (\n#2764\n, \n#2763\n)\n\n\nRaise error when \nModelSerializer\n used with abstract model. (\n#2757\n, \n#2630\n)\n\n\nHandle reversal of non-API view_name in \nHyperLinkedRelatedField\n (\n#2724\n, \n#2711\n)\n\n\nDont require pk strictly for related fields. (\n#2745\n, \n#2754\n)\n\n\nMetadata detects null boolean field type. (\n#2762\n)\n\n\nProper handling of depth in nested serializers. (\n#2798\n)\n\n\nDisplay viewset without paginator. (\n#2807\n)\n\n\nDon't check for deprecated \n.model\n attribute in permissions (\n#2818\n)\n\n\nRestrict integer field to integers and strings. (\n#2835\n, \n#2836\n)\n\n\nImprove \nIntegerField\n to use compiled decimal regex. (\n#2853\n)\n\n\nPrevent empty \nqueryset\n to raise AssertionError. (\n#2862\n)\n\n\nDjangoModelPermissions\n rely on \nget_queryset\n. (\n#2863\n)\n\n\nCheck \nAcceptHeaderVersioning\n with content negotiation in place. (\n#2868\n)\n\n\nAllow \nDjangoObjectPermissions\n to use views that define \nget_queryset\n. (\n#2905\n)\n\n\n\n\n3.1.1\n\n\nDate\n: \n23rd March 2015\n.\n\n\n\n\nSecurity fix\n: Escape tab switching cookie name in browsable API.\n\n\nDisplay input forms in browsable API if \nserializer_class\n is used, even when \nget_serializer\n method does not exist on the view. (\n#2743\n)\n\n\nUse a password input for the AuthTokenSerializer. (\n#2741\n)\n\n\nFix missing anchor closing tag after next button. (\n#2691\n)\n\n\nFix \nlookup_url_kwarg\n handling in viewsets. (\n#2685\n, \n#2591\n)\n\n\nFix problem with importing \nrest_framework.views\n in \napps.py\n (\n#2678\n)\n\n\nLimitOffsetPagination raises \nTypeError\n if PAGE_SIZE not set (\n#2667\n, \n#2700\n)\n\n\nGerman translation for \nmin_value\n field error message references \nmax_value\n. (\n#2645\n)\n\n\nRemove \nMergeDict\n. (\n#2640\n)\n\n\nSupport serializing unsaved models with related fields. (\n#2637\n, \n#2641\n)\n\n\nAllow blank/null on radio.html choices. (\n#2631\n)\n\n\n\n\n3.1.0\n\n\nDate\n: \n5th March 2015\n.\n\n\nFor full details see the \n3.1 release announcement\n.\n\n\n\n\n3.0.x series\n\n\n3.0.5\n\n\nDate\n: \n10th February 2015\n.\n\n\n\n\nFix a bug where \n_closable_objects\n breaks pickling. (\n#1850\n, \n#2492\n)\n\n\nAllow non-standard \nUser\n models with \nThrottling\n. (\n#2524\n)\n\n\nSupport custom \nUser.db_table\n in TokenAuthentication migration. (\n#2479\n)\n\n\nFix misleading \nAttributeError\n tracebacks on \nRequest\n objects. (\n#2530\n, \n#2108\n)\n\n\nManyRelatedField.get_value\n clearing field on partial update. (\n#2475\n)\n\n\nRemoved '.model' shortcut from code. (\n#2486\n)\n\n\nFix \ndetail_route\n and \nlist_route\n mutable argument. (\n#2518\n)\n\n\nPrefetching the user object when getting the token in \nTokenAuthentication\n. (\n#2519\n)\n\n\n\n\n3.0.4\n\n\nDate\n: \n28th January 2015\n.\n\n\n\n\nDjango 1.8a1 support. (\n#2425\n, \n#2446\n, \n#2441\n)\n\n\nAdd \nDictField\n and support Django 1.8 \nHStoreField\n. (\n#2451\n, \n#2106\n)\n\n\nAdd \nUUIDField\n and support Django 1.8 \nUUIDField\n. (\n#2448\n, \n#2433\n, \n#2432\n)\n\n\nBaseRenderer.render\n now raises \nNotImplementedError\n. (\n#2434\n)\n\n\nFix timedelta JSON serialization on Python 2.6. (\n#2430\n)\n\n\nResultDict\n and \nResultList\n now appear as standard dict/list. (\n#2421\n)\n\n\nFix visible \nHiddenField\n in the HTML form of the web browsable API page. (\n#2410\n)\n\n\nUse \nOrderedDict\n for \nRelatedField.choices\n. (\n#2408\n)\n\n\nFix ident format when using \nHTTP_X_FORWARDED_FOR\n. (\n#2401\n)\n\n\nFix invalid key with memcached while using throttling. (\n#2400\n)\n\n\nFix \nFileUploadParser\n with version 3.x. (\n#2399\n)\n\n\nFix the serializer inheritance. (\n#2388\n)\n\n\nFix caching issues with \nReturnDict\n. (\n#2360\n)\n\n\n\n\n3.0.3\n\n\nDate\n: \n8th January 2015\n.\n\n\n\n\nFix \nMinValueValidator\n on \nmodels.DateField\n. (\n#2369\n)\n\n\nFix serializer missing context when pagination is used. (\n#2355\n)\n\n\nNamespaced router URLs are now supported by the \nDefaultRouter\n. (\n#2351\n)\n\n\nrequired=False\n allows omission of value for output. (\n#2342\n)\n\n\nUse textarea input for \nmodels.TextField\n. (\n#2340\n)\n\n\nUse custom \nListSerializer\n for pagination if required. (\n#2331\n, \n#2327\n)\n\n\nBetter behavior with null and '' for blank HTML fields. (\n#2330\n)\n\n\nEnsure fields in \nexclude\n are model fields. (\n#2319\n)\n\n\nFix \nIntegerField\n and \nmax_length\n argument incompatibility. (\n#2317\n)\n\n\nFix the YAML encoder for 3.0 serializers. (\n#2315\n, \n#2283\n)\n\n\nFix the behavior of empty HTML fields. (\n#2311\n, \n#1101\n)\n\n\nFix Metaclass attribute depth ignoring fields attribute. (\n#2287\n)\n\n\nFix \nformat_suffix_patterns\n to work with Django's \ni18n_patterns\n. (\n#2278\n)\n\n\nAbility to customize router URLs for custom actions, using \nurl_path\n. (\n#2010\n)\n\n\nDon't install Django REST Framework as egg. (\n#2386\n)\n\n\n\n\n3.0.2\n\n\nDate\n: \n17th December 2014\n.\n\n\n\n\nEnsure \nrequest.user\n is made available to response middleware. (\n#2155\n)\n\n\nClient.logout()\n also cancels any existing \nforce_authenticate\n. (\n#2218\n, \n#2259\n)\n\n\nExtra assertions and better checks to preventing incorrect serializer API use. (\n#2228\n, \n#2234\n, \n#2262\n, \n#2263\n, \n#2266\n, \n#2267\n, \n#2289\n, \n#2291\n)\n\n\nFixed \nmin_length\n message for \nCharField\n. (\n#2255\n)\n\n\nFix \nUnicodeDecodeError\n, which can occur on serializer \nrepr\n. (\n#2270\n, \n#2279\n)\n\n\nFix empty HTML values when a default is provided. (\n#2280\n, \n#2294\n)\n\n\nFix \nSlugRelatedField\n raising \nUnicodeEncodeError\n when used as a multiple choice input. (\n#2290\n)\n\n\n\n\n3.0.1\n\n\nDate\n: \n11th December 2014\n.\n\n\n\n\nMore helpful error message when the default Serializer \ncreate()\n fails. (\n#2013\n)\n\n\nRaise error when attempting to save serializer if data is not valid. (\n#2098\n)\n\n\nFix \nFileUploadParser\n breaks with empty file names and multiple upload handlers. (\n#2109\n)\n\n\nImprove \nBindingDict\n to support standard dict-functions. (\n#2135\n, \n#2163\n)\n\n\nAdd \nvalidate()\n to \nListSerializer\n. (\n#2168\n, \n#2225\n, \n#2232\n)\n\n\nFix JSONP renderer failing to escape some characters. (\n#2169\n, \n#2195\n)\n\n\nAdd missing default style for \nFileField\n. (\n#2172\n)\n\n\nActions are required when calling \nViewSet.as_view()\n. (\n#2175\n)\n\n\nAdd \nallow_blank\n to \nChoiceField\n. (\n#2184\n, \n#2239\n)\n\n\nCosmetic fixes in the HTML renderer. (\n#2187\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2193\n, \n#2213\n)\n\n\nImprove checks for nested creates and updates. (\n#2194\n, \n#2196\n)\n\n\nvalidated_attrs\n argument renamed to \nvalidated_data\n in \nSerializer\n \ncreate()\n/\nupdate()\n. (\n#2197\n)\n\n\nRemove deprecated code to reflect the dropped Django versions. (\n#2200\n)\n\n\nBetter serializer errors for nested writes. (\n#2202\n, \n#2215\n)\n\n\nFix pagination and custom permissions incompatibility. (\n#2205\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2213\n)\n\n\nAdd missing translation markers for relational fields. (\n#2231\n)\n\n\nImprove field lookup behavior for dicts/mappings. (\n#2244\n, \n#2243\n)\n\n\nOptimized hyperlinked PK. (\n#2242\n)\n\n\n\n\n3.0.0\n\n\nDate\n: 1st December 2014\n\n\nFor full details see the \n3.0 release announcement\n.\n\n\n\n\nFor older release notes, \nplease see the version 2.x documentation\n.", + "text": "Release Notes\n\n\n\n\nRelease Early, Release Often\n\n\n Eric S. Raymond, \nThe Cathedral and the Bazaar\n.\n\n\n\n\nVersioning\n\n\nMinor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.\n\n\nMedium version numbers (0.x.0) may include API changes, in line with the \ndeprecation policy\n. You should read the release notes carefully before upgrading between medium point releases.\n\n\nMajor version numbers (x.0.0) are reserved for substantial project milestones.\n\n\nDeprecation policy\n\n\nREST framework releases follow a formal deprecation policy, which is in line with \nDjango's deprecation policy\n.\n\n\nThe timeline for deprecation of a feature present in version 1.0 would work as follows:\n\n\n\n\n\n\nVersion 1.1 would remain \nfully backwards compatible\n with 1.0, but would raise \nPendingDeprecationWarning\n warnings if you use the feature that are due to be deprecated. These warnings are \nsilent by default\n, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using \npython -Wd manage.py test\n, you'll be warned of any API changes you need to make.\n\n\n\n\n\n\nVersion 1.2 would escalate these warnings to \nDeprecationWarning\n, which is loud by default.\n\n\n\n\n\n\nVersion 1.3 would remove the deprecated bits of API entirely.\n\n\n\n\n\n\nNote that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.\n\n\nUpgrading\n\n\nTo upgrade Django REST framework to the latest version, use pip:\n\n\npip install -U djangorestframework\n\n\n\nYou can determine your currently installed version using \npip freeze\n:\n\n\npip freeze | grep djangorestframework\n\n\n\n\n\n3.3.x series\n\n\n3.3.1\n\n\nDate\n: \n4th November 2015\n.\n\n\n\n\nResolve parsing bug when accessing \nrequest.POST\n (\n#3592\n)\n\n\nCorrectly deal with \nto_field\n referring to primary key. (\n#3593\n)\n\n\nAllow filter HTML to render when no \nfilter_class\n is defined. (\n#3560\n)\n\n\nFix admin rendering issues. (\n#3564\n, \n#3556\n)\n\n\nFix issue with DecimalValidator. (\n#3568\n)\n\n\n\n\n3.3.0\n\n\nDate\n: \n28th October 2015\n.\n\n\n\n\nHTML controls for filters. (\n#3315\n)\n\n\nForms API. (\n#3475\n)\n\n\nAJAX browsable API. (\n#3410\n)\n\n\nAdded JSONField. (\n#3454\n)\n\n\nCorrectly map \nto_field\n when creating \nModelSerializer\n relational fields. (\n#3526\n)\n\n\nInclude keyword arguments when mapping \nFilePathField\n to a serializer field. (\n#3536\n)\n\n\nMap appropriate model \nerror_messages\n on \nModelSerializer\n uniqueness constraints. (\n#3435\n)\n\n\nInclude \nmax_length\n constraint for \nModelSerializer\n fields mapped from TextField. (\n#3509\n)\n\n\nAdded support for Django 1.9. (\n#3450\n, \n#3525\n)\n\n\nRemoved support for Django 1.5 \n 1.6. (\n#3421\n, \n#3429\n)\n\n\nRemoved 'south' migrations. (\n#3495\n)\n\n\n\n\n3.2.x series\n\n\n3.2.5\n\n\nDate\n: \n27th October 2015\n.\n\n\n\n\nEscape \nusername\n in optional logout tag. (\n#3550\n)\n\n\n\n\n3.2.4\n\n\nDate\n: \n21th September 2015\n.\n\n\n\n\nDon't error on missing \nViewSet.search_fields\n attribute. (\n#3324\n, \n#3323\n)\n\n\nFix \nallow_empty\n not working on serializers with \nmany=True\n. (\n#3361\n, \n#3364\n)\n\n\nLet \nDurationField\n accepts integers. (\n#3359\n)\n\n\nMulti-level dictionaries not supported in multipart requests. (\n#3314\n)\n\n\nFix \nListField\n truncation on HTTP PATCH (\n#3415\n, \n#2761\n)\n\n\n\n\n3.2.3\n\n\nDate\n: \n24th August 2015\n.\n\n\n\n\nAdded \nhtml_cutoff\n and \nhtml_cutoff_text\n for limiting select dropdowns. (\n#3313\n)\n\n\nAdded regex style to \nSearchFilter\n. (\n#3316\n)\n\n\nResolve issues with setting blank HTML fields. (\n#3318\n) (\n#3321\n)\n\n\nCorrectly display existing 'select multiple' values in browsable API forms. (\n#3290\n)\n\n\nResolve duplicated validation message for \nIPAddressField\n. ([#3249[gh3249]) (\n#3250\n)\n\n\nFix to ensure admin renderer continues to work when pagination is disabled. (\n#3275\n)\n\n\nResolve error with \nLimitOffsetPagination\n when count=0, offset=0. (\n#3303\n)\n\n\n\n\n3.2.2\n\n\nDate\n: \n13th August 2015\n.\n\n\n\n\nAdd \ndisplay_value()\n method for use when displaying relational field select inputs. (\n#3254\n)\n\n\nFix issue with \nBooleanField\n checkboxes incorrectly displaying as checked. (\n#3258\n)\n\n\nEnsure empty checkboxes properly set \nBooleanField\n to \nFalse\n in all cases. (\n#2776\n)\n\n\nAllow \nWSGIRequest.FILES\n property without raising incorrect deprecated error. (\n#3261\n)\n\n\nResolve issue with rendering nested serializers in forms. (\n#3260\n)\n\n\nRaise an error if user accidentally pass a serializer instance to a response, rather than data. (\n#3241\n)\n\n\n\n\n3.2.1\n\n\nDate\n: \n7th August 2015\n.\n\n\n\n\nFix for relational select widgets rendering without any choices. (\n#3237\n)\n\n\nFix for \n1\n, \n0\n rendering as \ntrue\n, \nfalse\n in the admin interface. \n#3227\n)\n\n\nFix for ListFields with single value in HTML form input. (\n#3238\n)\n\n\nAllow \nrequest.FILES\n for compat with Django's \nHTTPRequest\n class. (\n#3239\n)\n\n\n\n\n3.2.0\n\n\nDate\n: \n6th August 2015\n.\n\n\n\n\nAdd \nAdminRenderer\n. (\n#2926\n)\n\n\nAdd \nFilePathField\n. (\n#1854\n)\n\n\nAdd \nallow_empty\n to \nListField\n. (\n#2250\n)\n\n\nSupport django-guardian 1.3. (\n#3165\n)\n\n\nSupport grouped choices. (\n#3225\n)\n\n\nSupport error forms in browsable API. (\n#3024\n)\n\n\nAllow permission classes to customize the error message. (\n#2539\n)\n\n\nSupport \nsource=\nmethod\n on hyperlinked fields. (\n#2690\n)\n\n\nListField(allow_null=True)\n now allows null as the list value, not null items in the list. (\n#2766\n)\n\n\nManyToMany()\n maps to \nallow_empty=False\n, \nManyToMany(blank=True)\n maps to \nallow_empty=True\n. (\n#2804\n)\n\n\nSupport custom serialization styles for primary key fields. (\n#2789\n)\n\n\nOPTIONS\n requests support nested representations. (\n#2915\n)\n\n\nSet \nview.action == \"metadata\"\n for viewsets with \nOPTIONS\n requests. (\n#3115\n)\n\n\nSupport \nallow_blank\n on \nUUIDField\n. ([#3130][gh#3130])\n\n\nDo not display view docstrings with 401 or 403 response codes. (\n#3216\n)\n\n\nResolve Django 1.8 deprecation warnings. (\n#2886\n)\n\n\nFix for \nDecimalField\n validation. (\n#3139\n)\n\n\nFix behavior of \nallow_blank=False\n when used with \ntrim_whitespace=True\n. (\n#2712\n)\n\n\nFix issue with some field combinations incorrectly mapping to an invalid \nallow_blank\n argument. (\n#3011\n)\n\n\nFix for output representations with prefetches and modified querysets. (\n#2704\n, \n#2727\n)\n\n\nFix assertion error when CursorPagination is provided with certains invalid query parameters. (#2920)\ngh2920\n.\n\n\nFix \nUnicodeDecodeError\n when invalid characters included in header with \nTokenAuthentication\n. (\n#2928\n)\n\n\nFix transaction rollbacks with \n@non_atomic_requests\n decorator. (\n#3016\n)\n\n\nFix duplicate results issue with Oracle databases using \nSearchFilter\n. (\n#2935\n)\n\n\nFix checkbox alignment and rendering in browsable API forms. (\n#2783\n)\n\n\nFix for unsaved file objects which should use \n\"url\": null\n in the representation. (\n#2759\n)\n\n\nFix field value rendering in browsable API. (\n#2416\n)\n\n\nFix \nHStoreField\n to include \nallow_blank=True\n in \nDictField\n mapping. (\n#2659\n)\n\n\nNumerous other cleanups, improvements to error messaging, private API \n minor fixes.\n\n\n\n\n\n\n3.1.x series\n\n\n3.1.3\n\n\nDate\n: \n4th June 2015\n.\n\n\n\n\nAdd \nDurationField\n. (\n#2481\n, \n#2989\n)\n\n\nAdd \nformat\n argument to \nUUIDField\n. (\n#2788\n, \n#3000\n)\n\n\nMultipleChoiceField\n empties incorrectly on a partial update using multipart/form-data (\n#2993\n, \n#2894\n)\n\n\nFix a bug in options related to read-only \nRelatedField\n. (\n#2981\n, \n#2811\n)\n\n\nFix nested serializers with \nunique_together\n relations. (\n#2975\n)\n\n\nAllow unexpected values for \nChoiceField\n/\nMultipleChoiceField\n representations. (\n#2839\n, \n#2940\n)\n\n\nRollback the transaction on error if \nATOMIC_REQUESTS\n is set. (\n#2887\n, \n#2034\n)\n\n\nSet the action on a view when override_method regardless of its None-ness. (\n#2933\n)\n\n\nDecimalField\n accepts \n2E+2\n as 200 and validates decimal place correctly. (\n#2948\n, \n#2947\n)\n\n\nSupport basic authentication with custom \nUserModel\n that change \nusername\n. (\n#2952\n)\n\n\nIPAddressField\n improvements. (\n#2747\n, \n#2618\n, \n#3008\n)\n\n\nImprove \nDecimalField\n for easier subclassing. (\n#2695\n)\n\n\n\n\n3.1.2\n\n\nDate\n: \n13rd May 2015\n.\n\n\n\n\nDateField.to_representation\n can handle str and empty values. (\n#2656\n, \n#2687\n, \n#2869\n)\n\n\nUse default reason phrases from HTTP standard. (\n#2764\n, \n#2763\n)\n\n\nRaise error when \nModelSerializer\n used with abstract model. (\n#2757\n, \n#2630\n)\n\n\nHandle reversal of non-API view_name in \nHyperLinkedRelatedField\n (\n#2724\n, \n#2711\n)\n\n\nDont require pk strictly for related fields. (\n#2745\n, \n#2754\n)\n\n\nMetadata detects null boolean field type. (\n#2762\n)\n\n\nProper handling of depth in nested serializers. (\n#2798\n)\n\n\nDisplay viewset without paginator. (\n#2807\n)\n\n\nDon't check for deprecated \n.model\n attribute in permissions (\n#2818\n)\n\n\nRestrict integer field to integers and strings. (\n#2835\n, \n#2836\n)\n\n\nImprove \nIntegerField\n to use compiled decimal regex. (\n#2853\n)\n\n\nPrevent empty \nqueryset\n to raise AssertionError. (\n#2862\n)\n\n\nDjangoModelPermissions\n rely on \nget_queryset\n. (\n#2863\n)\n\n\nCheck \nAcceptHeaderVersioning\n with content negotiation in place. (\n#2868\n)\n\n\nAllow \nDjangoObjectPermissions\n to use views that define \nget_queryset\n. (\n#2905\n)\n\n\n\n\n3.1.1\n\n\nDate\n: \n23rd March 2015\n.\n\n\n\n\nSecurity fix\n: Escape tab switching cookie name in browsable API.\n\n\nDisplay input forms in browsable API if \nserializer_class\n is used, even when \nget_serializer\n method does not exist on the view. (\n#2743\n)\n\n\nUse a password input for the AuthTokenSerializer. (\n#2741\n)\n\n\nFix missing anchor closing tag after next button. (\n#2691\n)\n\n\nFix \nlookup_url_kwarg\n handling in viewsets. (\n#2685\n, \n#2591\n)\n\n\nFix problem with importing \nrest_framework.views\n in \napps.py\n (\n#2678\n)\n\n\nLimitOffsetPagination raises \nTypeError\n if PAGE_SIZE not set (\n#2667\n, \n#2700\n)\n\n\nGerman translation for \nmin_value\n field error message references \nmax_value\n. (\n#2645\n)\n\n\nRemove \nMergeDict\n. (\n#2640\n)\n\n\nSupport serializing unsaved models with related fields. (\n#2637\n, \n#2641\n)\n\n\nAllow blank/null on radio.html choices. (\n#2631\n)\n\n\n\n\n3.1.0\n\n\nDate\n: \n5th March 2015\n.\n\n\nFor full details see the \n3.1 release announcement\n.\n\n\n\n\n3.0.x series\n\n\n3.0.5\n\n\nDate\n: \n10th February 2015\n.\n\n\n\n\nFix a bug where \n_closable_objects\n breaks pickling. (\n#1850\n, \n#2492\n)\n\n\nAllow non-standard \nUser\n models with \nThrottling\n. (\n#2524\n)\n\n\nSupport custom \nUser.db_table\n in TokenAuthentication migration. (\n#2479\n)\n\n\nFix misleading \nAttributeError\n tracebacks on \nRequest\n objects. (\n#2530\n, \n#2108\n)\n\n\nManyRelatedField.get_value\n clearing field on partial update. (\n#2475\n)\n\n\nRemoved '.model' shortcut from code. (\n#2486\n)\n\n\nFix \ndetail_route\n and \nlist_route\n mutable argument. (\n#2518\n)\n\n\nPrefetching the user object when getting the token in \nTokenAuthentication\n. (\n#2519\n)\n\n\n\n\n3.0.4\n\n\nDate\n: \n28th January 2015\n.\n\n\n\n\nDjango 1.8a1 support. (\n#2425\n, \n#2446\n, \n#2441\n)\n\n\nAdd \nDictField\n and support Django 1.8 \nHStoreField\n. (\n#2451\n, \n#2106\n)\n\n\nAdd \nUUIDField\n and support Django 1.8 \nUUIDField\n. (\n#2448\n, \n#2433\n, \n#2432\n)\n\n\nBaseRenderer.render\n now raises \nNotImplementedError\n. (\n#2434\n)\n\n\nFix timedelta JSON serialization on Python 2.6. (\n#2430\n)\n\n\nResultDict\n and \nResultList\n now appear as standard dict/list. (\n#2421\n)\n\n\nFix visible \nHiddenField\n in the HTML form of the web browsable API page. (\n#2410\n)\n\n\nUse \nOrderedDict\n for \nRelatedField.choices\n. (\n#2408\n)\n\n\nFix ident format when using \nHTTP_X_FORWARDED_FOR\n. (\n#2401\n)\n\n\nFix invalid key with memcached while using throttling. (\n#2400\n)\n\n\nFix \nFileUploadParser\n with version 3.x. (\n#2399\n)\n\n\nFix the serializer inheritance. (\n#2388\n)\n\n\nFix caching issues with \nReturnDict\n. (\n#2360\n)\n\n\n\n\n3.0.3\n\n\nDate\n: \n8th January 2015\n.\n\n\n\n\nFix \nMinValueValidator\n on \nmodels.DateField\n. (\n#2369\n)\n\n\nFix serializer missing context when pagination is used. (\n#2355\n)\n\n\nNamespaced router URLs are now supported by the \nDefaultRouter\n. (\n#2351\n)\n\n\nrequired=False\n allows omission of value for output. (\n#2342\n)\n\n\nUse textarea input for \nmodels.TextField\n. (\n#2340\n)\n\n\nUse custom \nListSerializer\n for pagination if required. (\n#2331\n, \n#2327\n)\n\n\nBetter behavior with null and '' for blank HTML fields. (\n#2330\n)\n\n\nEnsure fields in \nexclude\n are model fields. (\n#2319\n)\n\n\nFix \nIntegerField\n and \nmax_length\n argument incompatibility. (\n#2317\n)\n\n\nFix the YAML encoder for 3.0 serializers. (\n#2315\n, \n#2283\n)\n\n\nFix the behavior of empty HTML fields. (\n#2311\n, \n#1101\n)\n\n\nFix Metaclass attribute depth ignoring fields attribute. (\n#2287\n)\n\n\nFix \nformat_suffix_patterns\n to work with Django's \ni18n_patterns\n. (\n#2278\n)\n\n\nAbility to customize router URLs for custom actions, using \nurl_path\n. (\n#2010\n)\n\n\nDon't install Django REST Framework as egg. (\n#2386\n)\n\n\n\n\n3.0.2\n\n\nDate\n: \n17th December 2014\n.\n\n\n\n\nEnsure \nrequest.user\n is made available to response middleware. (\n#2155\n)\n\n\nClient.logout()\n also cancels any existing \nforce_authenticate\n. (\n#2218\n, \n#2259\n)\n\n\nExtra assertions and better checks to preventing incorrect serializer API use. (\n#2228\n, \n#2234\n, \n#2262\n, \n#2263\n, \n#2266\n, \n#2267\n, \n#2289\n, \n#2291\n)\n\n\nFixed \nmin_length\n message for \nCharField\n. (\n#2255\n)\n\n\nFix \nUnicodeDecodeError\n, which can occur on serializer \nrepr\n. (\n#2270\n, \n#2279\n)\n\n\nFix empty HTML values when a default is provided. (\n#2280\n, \n#2294\n)\n\n\nFix \nSlugRelatedField\n raising \nUnicodeEncodeError\n when used as a multiple choice input. (\n#2290\n)\n\n\n\n\n3.0.1\n\n\nDate\n: \n11th December 2014\n.\n\n\n\n\nMore helpful error message when the default Serializer \ncreate()\n fails. (\n#2013\n)\n\n\nRaise error when attempting to save serializer if data is not valid. (\n#2098\n)\n\n\nFix \nFileUploadParser\n breaks with empty file names and multiple upload handlers. (\n#2109\n)\n\n\nImprove \nBindingDict\n to support standard dict-functions. (\n#2135\n, \n#2163\n)\n\n\nAdd \nvalidate()\n to \nListSerializer\n. (\n#2168\n, \n#2225\n, \n#2232\n)\n\n\nFix JSONP renderer failing to escape some characters. (\n#2169\n, \n#2195\n)\n\n\nAdd missing default style for \nFileField\n. (\n#2172\n)\n\n\nActions are required when calling \nViewSet.as_view()\n. (\n#2175\n)\n\n\nAdd \nallow_blank\n to \nChoiceField\n. (\n#2184\n, \n#2239\n)\n\n\nCosmetic fixes in the HTML renderer. (\n#2187\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2193\n, \n#2213\n)\n\n\nImprove checks for nested creates and updates. (\n#2194\n, \n#2196\n)\n\n\nvalidated_attrs\n argument renamed to \nvalidated_data\n in \nSerializer\n \ncreate()\n/\nupdate()\n. (\n#2197\n)\n\n\nRemove deprecated code to reflect the dropped Django versions. (\n#2200\n)\n\n\nBetter serializer errors for nested writes. (\n#2202\n, \n#2215\n)\n\n\nFix pagination and custom permissions incompatibility. (\n#2205\n)\n\n\nRaise error if \nfields\n on serializer is not a list of strings. (\n#2213\n)\n\n\nAdd missing translation markers for relational fields. (\n#2231\n)\n\n\nImprove field lookup behavior for dicts/mappings. (\n#2244\n, \n#2243\n)\n\n\nOptimized hyperlinked PK. (\n#2242\n)\n\n\n\n\n3.0.0\n\n\nDate\n: 1st December 2014\n\n\nFor full details see the \n3.0 release announcement\n.\n\n\n\n\nFor older release notes, \nplease see the version 2.x documentation\n.", "title": "Release Notes" }, { @@ -3117,7 +3117,7 @@ }, { "location": "/topics/release-notes/#33x-series", - "text": "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 )", + "text": "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 )", "title": "3.3.x series" }, { diff --git a/sitemap.xml b/sitemap.xml index 79586dc71..3be74ce47 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -4,7 +4,7 @@
@@ -13,43 +13,43 @@ http://www.django-rest-framework.org// -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/quickstart/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/1-serialization/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/2-requests-and-responses/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/3-class-based-views/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/ -2015-10-28 +2015-11-04 daily @@ -59,157 +59,157 @@ http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/requests/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/responses/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/views/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/generic-views/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/viewsets/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/routers/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/parsers/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/renderers/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/serializers/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/fields/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/relations/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/validators/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/authentication/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/permissions/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/throttling/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/filtering/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/pagination/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/versioning/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/content-negotiation/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/metadata/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/format-suffixes/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/reverse/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/exceptions/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/status-codes/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//api-guide/testing/ -2015-10-28 +2015-11-04 daily @@ -219,97 +219,97 @@ http://www.django-rest-framework.org//api-guide/settings/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/documenting-your-api/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/internationalization/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/ajax-csrf-cors/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/html-and-forms/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/browser-enhancements/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/browsable-api/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/third-party-resources/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/contributing/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/project-management/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/3.0-announcement/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/3.1-announcement/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/3.2-announcement/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/3.3-announcement/ -2015-10-28 +2015-11-04 daily http://www.django-rest-framework.org//topics/kickstarter-announcement/ -2015-10-28 +2015-11-04 daily diff --git a/topics/3.0-announcement/index.html b/topics/3.0-announcement/index.html index 2d3094483..1c0b78eb2 100644 --- a/topics/3.0-announcement/index.html +++ b/topics/3.0-announcement/index.html @@ -397,14 +397,14 @@ - http://www.django-rest-framework.org//topics/release-notes/ -2015-10-28 +2015-11-04 daily Django REST framework 3.0
+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
+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.
@@ -419,14 +419,14 @@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.
+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
+.dataand.query_paramsproperties.Request objects
+The
.dataand.query_paramsproperties.The usage of
request.DATAandrequest.FILESis now pending deprecation in favor of a singlerequest.dataattribute 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:
@@ -439,8 +439,8 @@ ExampleSerializer(data=request.DATA, files=request.FILES)The usage of
request.QUERY_PARAMSis now pending deprecation in favor of the lowercasedrequest.query_params.
-Serializers
-Single-step object creation.
+Serializers
+Single-step object creation.
Previously the serializers used a two-step object creation, as follows:
- Validating the data would create an object instance. This instance would be available as
@@ -458,7 +458,7 @@ ExampleSerializer(data=request.DATA, files=request.FILES)serializer.object.- Calling
serializer.save()then saves and returns the new object instance.The resulting API changes are further detailed below.
-The
+.create()and.update()methods.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
@@ -490,7 +490,7 @@ def create(self, validated_data): return Snippet.objects.create(**validated_data).save_object()method, which no longer exists.Note that these methods should return the newly created object instance.
-Use
+.validated_datainstead of.object.Use
.validated_datainstead of.object.You must now use the
.validated_dataattribute if you need to inspect the data before saving, rather than using the.objectattribute, which no longer exists.For example the following code is no longer valid:
-if serializer.is_valid(): @@ -506,17 +506,17 @@ def create(self, validated_data): logging.info('Creating ticket "%s"' % name) serializer.save(user=request.user) # Include the user when saving.Using
+.is_valid(raise_exception=True)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 aValidationErrorto 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_HANDLERsettings 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.Using
serializers.ValidationError.Previously
serializers.ValidationErrorerror was simply a synonym fordjango.core.exceptions.ValidationError. This has now been altered so that it inherits from the standardAPIExceptionbase class.The reason behind this is that Django's
ValidationErrorclass 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.ValidationErrorexception class, and not Django's built-in exception.We strongly recommend that you use the namespaced import style of
-import serializersand notfrom serializers import ValidationErrorin order to avoid any potential confusion.Change to
+validate_<field_name>.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: @@ -542,7 +542,7 @@ def create(self, validated_data): 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>.Removal of
transform_<field_name>.The under-used
transform_<field_name>on serializer classes is no longer provided. Instead you should just overrideto_representation()if you need to apply any modifications to the representation style.For example:
-def to_representation(self, instance): @@ -564,7 +564,7 @@ def create(self, validated_data): ret[key] = method(value) return retDifferences between ModelSerializer validation and ModelForm.
+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 onModelSerializerclasses that can't also be easily replicated on regularSerializerclasses.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
@@ -575,7 +575,7 @@ def create(self, validated_data): return attrs.clean()method will not be called as part of serializer validation, as it would be if using aModelForm. Use the serializer.validate()method to perform a final validation step on incoming data where required.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.
+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.
@@ -620,7 +620,7 @@ AssertionError: The `.create()` method does not support nested writable fields b return userThe single-step object creation makes this far simpler and more obvious than the previous
-.restore_object()behavior.Printable serializer representations.
+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): @@ -642,7 +642,7 @@ LocationRatingSerializer(): rating = IntegerField() created_by = PrimaryKeyRelatedField(queryset=User.objects.all())The
+extra_kwargsoption.The
extra_kwargsoption.The
write_only_fieldsoption onModelSerializerhas been moved toPendingDeprecationand replaced with a more genericextra_kwargs.class MySerializer(serializer.ModelSerializer): class Meta: @@ -661,7 +661,7 @@ LocationRatingSerializer(): fields = ('id', 'email', 'notes', 'is_admin')The
-read_only_fieldsoption remains as a convenient shortcut for the more common case.Changes to
+HyperlinkedModelSerializer.Changes to
HyperlinkedModelSerializer.The
view_nameandlookup_fieldoptions have been moved toPendingDeprecation. They are no longer required, as you can use theextra_kwargsargument instead:-class MySerializer(serializer.HyperlinkedModelSerializer): class Meta: @@ -682,7 +682,7 @@ LocationRatingSerializer(): model = MyModel fields = ('url', 'email', 'notes', 'is_admin')Fields for model methods and properties.
+Fields for model methods and properties.
With
ModelSerializeryou can now specify field names in thefieldsoption that refer to model methods or properties. For example, suppose you have the following model:-class Invitation(models.Model): created = models.DateTimeField() @@ -706,7 +706,7 @@ InvitationSerializer(): message = CharField(max_length=1000) expiry_date = ReadOnlyField()The
+ListSerializerclass.The
ListSerializerclass.The
ListSerializerclass has now been added, and allows you to create base serializer classes for only accepting multiple inputs.-class MultipleUserSerializer(ListSerializer): child = UserSerializer() @@ -714,7 +714,7 @@ InvitationSerializer():You can also still use the
many=Trueargument to serializer classes. It's worth noting thatmany=Trueargument transparently creates aListSerializerinstance, 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=Trueflag rather than declaringListSerializerclasses explicitly, but declaring the classes explicitly can be useful if you need to write customcreateorupdatemethods for bulk updates, or provide for other custom behavior.See also the new
-ListFieldclass, which validates input in the same way, but does not include the serializer interfaces of.is_valid(),.data,.save()and so on.The
+BaseSerializerclass.The
BaseSerializerclass.REST framework now includes a simple
BaseSerializerclass that can be used to easily support alternative serialization and deserialization styles.This class implements the same basic API as the
Serializerclass:@@ -732,7 +732,7 @@ InvitationSerializer():
Because this class provides the same interface as the
Serializerclass, you can use it with the existing generic class based views exactly as you would for a regularSerializerorModelSerializer.The only difference you'll notice when doing so is the
-BaseSerializerclasses 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
+BaseSerializerclasses.Read-only
BaseSerializerclasses.To implement a read-only serializer using the
BaseSerializerclass, 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) @@ -761,7 +761,7 @@ def all_high_scores(request): serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data)Read-write
+BaseSerializerclasses.Read-write
BaseSerializerclasses.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 aValidationErrorif 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_dataand.errors.If you want to also support
@@ -801,7 +801,7 @@ def all_high_scores(request): def create(self, validated_data): return HighScore.objects.create(**validated_data).save()you'll need to also implement either or both of the.create()and.update()methods.Creating new generic serializers with
+BaseSerializer.Creating new generic serializers with
BaseSerializer.The
BaseSerializerclass 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): @@ -837,8 +837,8 @@ def all_high_scores(request): output[attribute_name] = str(attribute)
-Serializer fields
-The
+FieldandReadOnlyfield classes.Serializer fields
+The
FieldandReadOnlyfield classes.There are some minor tweaks to the field base classes.
Previously we had these two base classes:
@@ -850,7 +850,7 @@ def all_high_scores(request):
-Fieldis the base class for all fields. It does not include any default implementation for either serializing or deserializing data.ReadOnlyFieldis a concrete implementation for read-only fields that simply returns the attribute value without modification.The
+required,allow_null,allow_blankanddefaultarguments.The
required,allow_null,allow_blankanddefaultarguments.REST framework now has more explicit and clear control over validating empty values for fields.
Previously the meaning of the
required=Falsekeyword 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 beNoneor the empty string.We now have a better separation, with separate
@@ -863,9 +863,9 @@ def all_high_scores(request):required,allow_nullandallow_blankarguments.Typically you'll want to use
required=Falseif the corresponding model field has a default value, and additionally set eitherallow_null=Trueorallow_blank=Trueif required.The
-defaultargument is also available and always implies that the field is not required to be in the input. It is unnecessary to use therequiredargument when a default is specified, and doing so will result in an error.Coercing output types.
+Coercing output types.
The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an
-IntegerFieldwould 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().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 overrideto_internal_value().class UppercaseCharField(serializers.CharField): def to_internal_value(self, data): @@ -875,7 +875,7 @@ def all_high_scores(request): return valuePreviously 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
+ListFieldclass.The
ListFieldclass.The
ListFieldclass has now been added. This field validates list input. It takes achildkeyword argument which is used to specify the field used to validate each item in the list. For example:@@ -887,13 +887,13 @@ def all_high_scores(request):scores = ListField(child=IntegerField(min_value=0, max_value=100))scores = ScoresField()See also the new
-ListSerializerclass, which validates input in the same way, but also includes the serializer interfaces of.is_valid(),.data,.save()and so on.The
+ChoiceFieldclass may now accept a flat list.The
ChoiceFieldclass may now accept a flat list.The
ChoiceFieldclass 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
+MultipleChoiceFieldclass.The
MultipleChoiceFieldclass.The
-MultipleChoiceFieldclass has been added. This field acts likeChoiceField, but returns a set, which may include none, one or many of the valid choices.Changes to the custom field API.
+Changes to the custom field API.
The
from_native(self, value)andto_native(self, data)method names have been replaced with the more obviously namedto_internal_value(self, data)andto_representation(self, value).The
field_from_native()andfield_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): @@ -914,7 +914,7 @@ def all_high_scores(request): def to_representation(self, value): return value.__class__.__name__Explicit
+querysetrequired on relational fields.Explicit
querysetrequired 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): @@ -943,7 +943,7 @@ This removes some magic and makes it easier and more obvious to move between imp model = AccountThe
-querysetargument is only ever required for writable fields, and is not required or valid for fields withread_only=True.Optional argument to
+SerializerMethodField.Optional argument to
SerializerMethodField.The argument to
SerializerMethodFieldis now optional, and defaults toget_<field_name>. For example the following is valid:-class AccountSerializer(serializers.Serializer): # `method_name='get_billing_details'` by default. @@ -955,12 +955,12 @@ This removes some magic and makes it easier and more obvious to move between impIn 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
+sourceusage.Enforcing consistent
sourceusage.I've see several codebases that unnecessarily include the
sourceargument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious thatsourceis usually not required.The following usage will now raise an error:
-email = serializers.EmailField(source='email')The
+UniqueValidatorandUniqueTogetherValidatorclasses.The
UniqueValidatorandUniqueTogetherValidatorclasses.REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit
Serializerclass instead of usingModelSerializer.The
UniqueValidatorshould be applied to a serializer field, and takes a singlequerysetargument.-from rest_framework import serializers @@ -986,14 +986,14 @@ class OrganizationSerializer(serializers.Serializer): fields=('category', 'position') )]The
+UniqueForDateValidatorclasses.The
UniqueForDateValidatorclasses.REST framework also now includes explicit validator classes for validating the
unique_for_date,unique_for_month, andunique_for_yearmodel field constraints. These are used internally instead of calling intoModel.full_clean().These classes are documented in the Validators section of the documentation.
-Generic views
-Simplification of view logic.
+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.
+Changes to pre/post save hooks.
The
pre_saveandpost_savehooks no longer exist, but are replaced withperform_create(self, serializer)andperform_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:
@@ -1010,22 +1010,22 @@ class OrganizationSerializer(serializers.Serializer): # Delete the object instance. instance.delete()Removal of view attributes.
+Removal of view attributes.
The
.objectand.object_listattributes 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.
+PUT as create.
Allowing
PUTas 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 returning404responses.Both styles "
PUTas 404" and "PUTas 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
-AllowPUTAsCreateMixinclass as a mixin to your views.Customizing error responses.
+Customizing error responses.
The generic views now raise
ValidationFailedexception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a400 Bad Requestresponse 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
+The metadata API
Behavior for dealing with
OPTIONSrequests 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
OPTIONSresponses throughout your API, and makes it possible to create third-party metadata policies.
-Serializers as HTML forms
+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:
@@ -1034,7 +1034,7 @@ class OrganizationSerializer(serializers.Serializer):- Nested lists of HTML forms are not yet supported, but are planned for 3.1.
- Because we now use templated HTML form generation, the
-widgetoption is no longer available for serializer fields. You can instead control the template that is used for a given field, by using thestyledictionary.The
+stylekeyword argument for serializer fields.The
stylekeyword argument for serializer fields.The
stylekeyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, theHTMLFormRendereruses thebase_templatekey to determine which template to render the field with.For example, to use a
textareacontrol instead of the defaultinputcontrol, you would use the following…additional_notes = serializers.CharField( @@ -1049,15 +1049,15 @@ class OrganizationSerializer(serializers.Serializer):This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
-API style
+API style
There are some improvements in the default style we use in our API responses.
-Unicode JSON by default.
+Unicode JSON by default.
Unicode JSON is now the default. The
UnicodeJSONRendererclass no longer exists, and theUNICODE_JSONsetting has been added. To revert this behavior use the new setting:-REST_FRAMEWORK = { 'UNICODE_JSON': False }Compact JSON by default.
+Compact JSON by default.
We now output compact JSON in responses by default. For example, we return:
@@ -1069,7 +1069,7 @@ class OrganizationSerializer(serializers.Serializer): 'COMPACT_JSON': False }{"email":"amy@example.com","is_admin":true}File fields as URLs
+File fields as URLs
The
FileFieldandImageFieldclasses are now represented as URLs by default. You should ensure you set Django's standardMEDIA_URLsetting 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_URLsettings key:REST_FRAMEWORK = { @@ -1085,9 +1085,9 @@ 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.Throttle headers using
Retry-After.The custom
-X-Throttle-Wait-Secondheader has now been dropped in favor of the standardRetry-Afterheader. You can revert this behavior if needed by writing a custom exception handler for your application.Date and time objects as ISO-8859-1 strings in serializer data.
+Date and time objects as ISO-8859-1 strings in serializer data.
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as
Date,TimeandDateTimeobjects, and later coerced to strings by the renderer.You can modify this behavior globally by settings the existing
DATE_FORMAT,DATETIME_FORMATandTIME_FORMATsettings keys. Setting these values toNoneinstead of their default value of'iso-8859-1'will result in native objects being returned in serializer data.REST_FRAMEWORK = { @@ -1101,7 +1101,7 @@ return Response(serializer.data)-# Return `DateTime` instances in `serializer.data`, not strings. created = serializers.DateTimeField(format=None)Decimals as strings in serializer data.
+Decimals as strings in serializer data.
Decimals are now coerced to strings by default in the serializer output. Previously they were returned as
Decimalobjects, and later coerced to strings by the renderer.You can modify this behavior globally by using the
COERCE_DECIMAL_TO_STRINGsettings key.REST_FRAMEWORK = { @@ -1118,7 +1118,7 @@ amount = serializers.DecimalField(The default JSON renderer will return float objects for un-coerced
Decimalinstances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
-Miscellaneous notes
+Miscellaneous notes
- The serializer
ChoiceFielddoes 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.
@@ -1126,7 +1126,7 @@ amount = serializers.DecimalField(APIExceptionsubclasses could previously take any arbitrary type in thedetailargument. These exceptions now use translatable text strings, and as a result callforce_texton thedetailargument, which must be a string. If you need complex arguments to anAPIExceptionclass, 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
+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:
diff --git a/topics/3.1-announcement/index.html b/topics/3.1-announcement/index.html index d97c28da1..9a8982c35 100644 --- a/topics/3.1-announcement/index.html +++ b/topics/3.1-announcement/index.html @@ -389,7 +389,7 @@ -
-Django REST framework 3.1
+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:
@@ -401,7 +401,7 @@
- Support for Django 1.8's
HStoreFieldandArrayField.
-Pagination
+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.
@@ -411,19 +411,19 @@- The
paginate_by,page_query_param,paginate_by_paramandmax_paginate_bygeneric 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_classview attribute andDEFAULT_PAGINATION_SERIALIZER_CLASSsettings key are no longer valid. The pagination API does not use serializers to determine the output format, and you'll need to instead override theget_paginated_responsemethod on a pagination class in order to specify how the output format is controlled.New pagination schemes.
+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.
+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:
The cursor based pagination renders a more simple style of control:
-
Support for header-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
LinkorContent-Rangeheaders.For more information, see the custom pagination styles documentation.
-Versioning
+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
@@ -445,7 +445,7 @@ }NamespaceVersioning, and the following hyperlinked serializer:
-Internationalization
+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-Languageheader.You can change the default language by using the standard Django
LANGUAGE_CODEsetting:LANGUAGE_CODE = "es-es" @@ -482,18 +482,18 @@ Host: example.orgFor more details, see the internationalization documentation.
Many thanks to Craig Blaszczyk for helping push this through.
-New field types
+New field types
Django 1.8's new
ArrayField,HStoreFieldandUUIDFieldare now all fully supported.This work also means that we now have both
serializers.DictField(), andserializers.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
UUIDFieldas 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
+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
+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 installthe new packages, and change any import paths.We're making this change in order to help distribute the maintainance 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.
@@ -518,12 +518,12 @@ Host: example.orgThanks go to the latest member of our maintenance team, José Padilla, for handling this work and taking on ownership of these packages.
-Deprecations
+Deprecations
The
request.DATA,request.FILESandrequest.QUERY_PARAMSattributes move from pending deprecation, to deprecated. Userequest.dataandrequest.query_paramsinstead, as discussed in the 3.0 release notes.The ModelSerializer Meta options for
write_only_fields,view_nameandlookup_fieldare also moved from pending deprecation, to deprecated. Useextra_kwargsinstead, 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?
+What's next?
The next focus will be on HTML renderings of API output and will include:
- HTML form rendering of serializers.
diff --git a/topics/3.2-announcement/index.html b/topics/3.2-announcement/index.html index a04a9133a..695be51e9 100644 --- a/topics/3.2-announcement/index.html +++ b/topics/3.2-announcement/index.html @@ -377,14 +377,14 @@ -Django REST framework 3.2
+Django REST framework 3.2
The 3.2 release is the first version to include an admin interface for the browsable API.
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing
BrowsableAPIRenderer, or used together with it, allowing you to switch between the two styles as required.We've also fixed a huge number of issues, and made numerous cleanups and improvements.
Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month.
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.
-AdminRenderer
+AdminRenderer
To include
AdminRenderersimply add it to your settings:REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ @@ -399,10 +399,10 @@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
+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
+Deprecations
There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
-
- @@ -419,10 +419,10 @@
request.DATAwas 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 ofrequest.datainstead.settings.PAGINATE_BY_PARAM- Usepaginator.page_size_query_paraminstead.settings.MAX_PAGINATE_BY- Usemax_page_sizeinstead.Modifications to list behaviors
+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
+ManyToMany fields and blank=True
We've now added an
allow_emptyargument, which can be used withListSerializer, or withmany=Truerelationships. This isTrueby default, but can be set toFalseif 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
ModelFormwith 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
@@ -432,7 +432,7 @@blank=Trueset.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=Trueif you want to allow empty inputs in the equivalentModelSerializerfields.List fields and allow_null
+List fields and allow_null
When using
allow_nullwithListFieldor a nestedmany=Trueserializer the previous behavior was to allownullvalues as items in the list. The behavior is now to allownullvalues instead of the list.For example, take the following field:
-NestedSerializer(many=True, allow_null=True) @@ -450,7 +450,7 @@If you want to allow
nullchild items, you'll need to instead specifyallow_nullon the child class, using an explicitListFieldinstead ofmany=True. For example:-ListField(child=NestedSerializer(allow_null=True))What's next?
+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:
diff --git a/topics/3.3-announcement/index.html b/topics/3.3-announcement/index.html index 1a1715036..083d90e1a 100644 --- a/topics/3.3-announcement/index.html +++ b/topics/3.3-announcement/index.html @@ -369,13 +369,13 @@ -
Django REST framework 3.3
+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
+Release notes
Significant new functionality in the 3.3 release includes:
- Filters presented as HTML controls in the browsable API.
@@ -387,13 +387,13 @@
Example of the new filter controls
-Supported versions
+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
+Deprecations
The AJAX based support for the browsable API means that there are a number of internal cleanups in the
requestclass. For the vast majority of developers this should largely remain transparent:-
diff --git a/topics/ajax-csrf-cors/index.html b/topics/ajax-csrf-cors/index.html index 8a652185d..0572bfbdb 100644 --- a/topics/ajax-csrf-cors/index.html +++ b/topics/ajax-csrf-cors/index.html @@ -369,16 +369,16 @@ -- To support form based
+PUTandDELETE, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-forms] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.- To support form based
PUTandDELETE, 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
acceptquery 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_OVERRIDEheader is no longer supported by default. If you require it then you'll need to use custom middleware.Working with AJAX, CSRF & CORS
+Working with AJAX, CSRF & CORS
-"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
Javascript clients
+Javascript clients
If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
AJAX requests that are made within the same context as the API they are interacting with will typically use
SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as
-TokenAuthentication.CSRF protection
+CSRF protection
Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
To guard against these type of attacks, you need to do two things:
@@ -387,7 +387,7 @@
If you're using
SessionAuthenticationyou'll need to include valid CSRF tokens for anyPOST,PUT,PATCHorDELETEoperations.In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.
-CORS
+CORS
Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.
diff --git a/topics/browsable-api/index.html b/topics/browsable-api/index.html index 0e6ec4fc7..25160130e 100644 --- a/topics/browsable-api/index.html +++ b/topics/browsable-api/index.html @@ -369,17 +369,17 @@ -The Browsable API
+The Browsable API
It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
— Alfred North Whitehead, An Introduction to Mathematics (1911)
API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the
-HTMLformat is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources usingPOST,PUT, andDELETE.URLs
+URLs
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The
-rest_frameworkpackage includes areversehelper for this purpose.Formats
+Formats
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using
-?format=in the request, so you can look at the raw JSON response in a browser by adding?format=jsonto the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.Customizing
+Customizing
The browsable API is built with Twitter's Bootstrap (v 2.1.1), making it easy to customize the look-and-feel.
To customize the default style, create a template called
rest_framework/api.htmlthat extends fromrest_framework/base.html. For example:templates/rest_framework/api.html
@@ -387,7 +387,7 @@ ... # Override blocks with required customizationsOverriding the default theme
+Overriding the default theme
To replace the default theme, add a
bootstrap_themeblock to yourapi.htmland insert alinkto the desired Bootstrap theme css file. This will completely replace the included theme.-{% block bootstrap_theme %} <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css"> @@ -412,7 +412,7 @@
Screenshot of the bootswatch 'Slate' theme
-Blocks
+Blocks
All of the blocks available in the browsable API base template that can be used in your
api.html.-
- @@ -426,11 +426,11 @@
body- The entire html<body>.title- Title of the page.userlinks- This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use{{ block.super }}to preserve the authentication links.Components
+Components
All of the standard Bootstrap components are available.
-Tooltips
+Tooltips
The browsable API makes use of the Bootstrap tooltips component. Any element with the
-js-tooltipclass and atitleattribute has that title content will display a tooltip on hover events.Login Template
+Login Template
To add branding and customize the look-and-feel of the login template, create a template called
login.htmland add it to your project, eg:templates/rest_framework/login.html. The template should extend fromrest_framework/login_base.html.You can add your site name or branding by including the branding block:
{% block branding %} @@ -438,8 +438,8 @@ {% endblock %}You can also customize the style by adding the
-bootstrap_themeorstyleblock similar toapi.html.Advanced Customization
-Context
+Advanced Customization
+Context
The context that's available to the template:
- @@ -460,9 +460,9 @@
allowed_methods: A list of methods allowed by the resourceMETHOD_PARAM: The view can accept a method overrideYou can override the
-BrowsableAPIRenderer.get_context()method to customise the context that gets passed to the template.Not using base.html
+Not using base.html
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have
-api.htmlextendbase.html. Then the page content and capabilities are entirely up to you.Handling
+ChoiceFieldwith large numbers of items.Handling
ChoiceFieldwith large numbers of items.When a relationship or
ChoiceFieldhas too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.The simplest option in this case is to replace the select input with a standard text input. For example:
-author = serializers.HyperlinkedRelatedField( @@ -470,7 +470,7 @@ style={'base_template': 'input.html'} )Autocomplete
+Autocomplete
An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
There are a variety of packages for autocomplete widgets, such as django-autocomplete-light, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the
widgetkeyword argument since it now uses templated HTML generation.Better support for autocomplete inputs is planned in future versions.
diff --git a/topics/browser-enhancements/index.html b/topics/browser-enhancements/index.html index 0ae459fe4..db3ae5540 100644 --- a/topics/browser-enhancements/index.html +++ b/topics/browser-enhancements/index.html @@ -381,14 +381,14 @@ -Browser enhancements
+Browser enhancements
"There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"
— RESTful Web Services, Leonard Richardson & Sam Ruby.
In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide.
As of version 3.3.0 onwards these are enabled with javascript, using the ajax-form library.
-Browser based PUT, DELETE, etc...
+Browser based PUT, DELETE, etc...
The AJAX form library supports browser-based
PUT,DELETEand other methods on HTML forms.After including the library, use the
data-methodattribute on the form, like so:<form action="/" data-method="PUT"> @@ -397,7 +397,7 @@ </form>Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in Ruby on Rails) is no longer supported due to subtle issues that it introduces in request parsing.
-Browser based submission of non-form content
+Browser based submission of non-form content
Browser-based submission of content types such as JSON are supported by the AJAX form library, using form fields with
data-override='content-type'anddata-override='content'attributes.For example:
<form action="/"> @@ -407,12 +407,12 @@ </form>Note that prior to 3.3.0, this support was server-side rather than javascript based.
-URL based format suffixes
+URL based format suffixes
REST framework can take
?format=jsonstyle URL parameters, which can be a useful shortcut for determining which content type should be returned from the view.This behavior is controlled using the
-URL_FORMAT_OVERRIDEsetting.HTTP header based method overriding
+HTTP header based method overriding
Prior to version 3.3.0 the semi extension header
X-HTTP-Method-Overridewas supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware.For example:
-METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' @@ -425,7 +425,7 @@ class MethodOverrideMiddleware(object): return request.method = request.META[METHOD_OVERRIDE_HEADER]URL based accept headers
+URL based accept headers
Until version 3.3.0 REST framework included built-in support for
?accept=application/jsonstyle URL parameters, which would allow theAcceptheader to be overridden.Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed.
For example:
@@ -435,7 +435,7 @@ class MethodOverrideMiddleware(object): header = request.query_params.get('_accept', header) return [token.strip() for token in header.split(',')]Doesn't HTML5 support PUT and DELETE forms?
+Doesn't HTML5 support PUT and DELETE forms?
Nope. It was at one point intended to support
PUTandDELETEforms, but was later dropped from the spec. There remains ongoing discussion about adding support forPUTandDELETE, diff --git a/topics/contributing/index.html b/topics/contributing/index.html index ff36225eb..c989db06c 100644 --- a/topics/contributing/index.html +++ b/topics/contributing/index.html @@ -411,22 +411,22 @@ -Contributing to REST framework
+Contributing to REST framework
The world can only really be changed one piece at a time. The art is picking that piece.
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
+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-frameworktag.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
+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
+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:
@@ -436,7 +436,7 @@
-- 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
+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?
@@ -445,12 +445,12 @@- 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
+Development
To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.gitChanges should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
-Testing
+Testing
To run the tests, clone the repository, and then:
-# Setup the virtual environment virtualenv env @@ -460,7 +460,7 @@ pip install -r requirements.txt # Run the tests ./runtests.pyTest options
+Test options
Run using a more concise output style.
@@ -483,11 +483,11 @@ pip install -r requirements.txt./runtests.py -q./runtests.py test_this_methodNote: 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
+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
toxglobally, and then simply run:-toxPull requests
+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.
@@ -496,12 +496,12 @@ pip install -r requirements.txtOnce you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
Above: Travis build notifications
-Managing compatibility issues
+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.pymodule, and should provide a single common interface that the rest of the codebase can use.Documentation
+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
+Building the documentation
To build the documentation, install MkDocs with
pip install mkdocsand then run the following command.@@ -509,16 +509,16 @@ pip install -r requirements.txtmkdocs buildYou can build the documentation and open a preview in a browser window by using the
servecommand.-mkdocs serveLanguage style
+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
+Markdown style
There are a couple of conventions you should follow when working on the documentation.
-1. Headers
+1. Headers
Headers should use the hash style. For example:
@@ -526,7 +526,7 @@ pip install -r requirements.txt### Some important topic-Some important topic ====================2. Links
+2. Links
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]. @@ -539,7 +539,7 @@ More text...[authentication]: ../api-guide/authentication.mdLinking 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
+3. Notes
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
--- diff --git a/topics/documenting-your-api/index.html b/topics/documenting-your-api/index.html index ad758f7c1..a9688e4c9 100644 --- a/topics/documenting-your-api/index.html +++ b/topics/documenting-your-api/index.html @@ -369,38 +369,38 @@ -Documenting your API
+Documenting your API
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.
— Roy Fielding, REST APIs must be hypertext driven
There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.
-Endpoint documentation
+Endpoint documentation
The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.
-Django REST Swagger
+Django REST Swagger
Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.
The package is fully documented, well supported, and comes highly recommended.
Django REST Swagger supports REST framework versions 2.3 and above.
-REST Framework Docs
+REST Framework Docs
The REST Framework Docs package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.
-Apiary
+Apiary
There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.
-Self describing APIs
+Self describing APIs
The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.
-Setting the title
+Setting the title
The title that is used in the browsable API is generated from the view class name or function name. Any trailing
VieworViewSetsuffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.For example, the view
UserListView, will be namedUser Listwhen presented in the browsable API.When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set
-UserViewSetwill generate views namedUser ListandUser Instance.Setting the description
+Setting the description
The description in the browsable API is generated from the docstring of the view or viewset.
If the python
markdownlibrary is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:class AccountListView(views.APIView): @@ -413,7 +413,7 @@ """Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.
-The
+OPTIONSmethodThe
OPTIONSmethodREST framework APIs also support programmatically accessible descriptions, using the
OPTIONSHTTP method. A view will respond to anOPTIONSrequest with metadata including the name, description, and the various media types it accepts and responds with.When using the generic views, any
OPTIONSrequests will additionally respond with metadata regarding anyPOSTorPUTactions available, describing which fields are on the serializer.You can modify the response behavior to
@@ -426,7 +426,7 @@ return dataOPTIONSrequests by overriding themetadataview method. For example:
-The hypermedia approach
+The hypermedia approach
To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
diff --git a/topics/html-and-forms/index.html b/topics/html-and-forms/index.html index bc7ef0cb0..047556ccb 100644 --- a/topics/html-and-forms/index.html +++ b/topics/html-and-forms/index.html @@ -369,9 +369,9 @@ -HTML & Forms
+HTML & Forms
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
-Rendering HTML
+Rendering HTML
In order to return HTML responses you'll need to either
TemplateHTMLRenderer, orStaticHTMLRenderer.The
TemplateHTMLRendererclass expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.The
@@ -380,6 +380,7 @@StaticHTMLRenderclass expects the response to contain a string of the pre-rendered HTML content.views.py:
-from my_project.example.models import Profile from rest_framework.renderers import TemplateHTMLRenderer +from rest_framework.response import Response from rest_framework.views import APIView @@ -401,7 +402,7 @@ class ProfileList(APIView): </ul> </body></html>Rendering Forms
+Rendering Forms
Serializers may be rendered as forms by using the
render_formtemplate tag, and including the serializer instance as context to the template.The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
views.py:
@@ -442,7 +443,7 @@ class ProfileDetail(APIView): </body></html>Using template packs
+Using template packs
The
render_formtag takes an optionaltemplate_packargument, that specifies which template directory should be used for rendering the form and form fields.REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are
horizontal,vertical, andinline. The default style ishorizontal. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
@@ -465,7 +466,7 @@ class ProfileDetail(APIView): remember_me = serializers.BooleanField()
-+
rest_framework/vertical
rest_framework/verticalPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.
This is the default template pack.
{% load rest_framework %} @@ -480,7 +481,7 @@ class ProfileDetail(APIView):
-+
rest_framework/horizontal
rest_framework/horizontalPresents labels and controls alongside each other, using a 2/10 column split.
This is the form style used in the browsable API and admin renderers.
{% load rest_framework %} @@ -499,7 +500,7 @@ class ProfileDetail(APIView):
-+
rest_framework/inline
rest_framework/inlineA compact form style that presents all the controls inline.
{% load rest_framework %} @@ -512,7 +513,7 @@ class ProfileDetail(APIView): </form>-
Field styles
+Field styles
Serializer fields can have their rendering style customized by using the
stylekeyword argument. This argument is a dictionary of options that control the template and layout used.The most common way to customize the field style is to use the
base_templatestyle keyword argument to select which template in the template pack should be use.For example, to render a
diff --git a/topics/internationalization/index.html b/topics/internationalization/index.html index a34dbe815..096b9f836 100644 --- a/topics/internationalization/index.html +++ b/topics/internationalization/index.html @@ -369,7 +369,7 @@ -CharFieldas an HTML textarea rather than the default HTML input, you would use something like this:Internationalization
+Internationalization
Supporting internationalization is not optional. It must be a core feature.
— Jannis Leidel, speaking at Django Under the Hood, 2015.
@@ -380,7 +380,7 @@- Select a language other than English as the default, using the standard
LANGUAGE_CODEDjango setting.- Allow clients to choose a language themselves, using the
-LocaleMiddlewareincluded with Django. A typical usage for API clients would be to include anAccept-Languagerequest header.Enabling internationalized APIs
+Enabling internationalized APIs
You can change the default language by using the standard Django
LANGUAGE_CODEsetting:@@ -407,7 +407,7 @@ Host: example.orgLANGUAGE_CODE = "es-es"{"detail": {"username": ["Esse campo deve ser unico."]}}If you want to use different string for parts of the response such as
-detailandnon_field_errorsthen you can modify this behavior by using a custom exception handler.Specifying the set of supported languages.
+Specifying the set of supported languages.
By default all available languages will be supported.
If you only wish to support a subset of the available languages, use Django's standard
LANGUAGESsetting:-LANGUAGES = [ @@ -415,14 +415,14 @@ Host: example.org ('en', _('English')), ]Adding new translations
+Adding new translations
REST framework translations are managed online using Transifex. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package.
Sometimes you may need to add translation strings to your project locally. You may need to do this if:
-
- You want to use REST Framework in a language which has not been translated yet on Transifex.
- Your project includes custom error messages, which are not part of REST framework's default translation strings.
Translating a new language locally
+Translating a new language locally
This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading Django's translation docs.
If you're translating a new language you'll need to translate the existing REST framework error messages:
@@ -447,7 +447,7 @@ available for Django to use. You should see a message like
processing fileIf you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source
-django.pofile into aLOCALE_PATHSfolder, and can instead simply run Django's standardmakemessagesprocess.How the language is determined
+How the language is determined
If you want to allow per-request language preferences you'll need to include
django.middleware.locale.LocaleMiddlewarein yourMIDDLEWARE_CLASSESsetting.You can find more information on how the language preference is determined in the Django documentation. For reference, the method is:
diff --git a/topics/kickstarter-announcement/index.html b/topics/kickstarter-announcement/index.html index 56fbe375d..e9fafc076 100644 --- a/topics/kickstarter-announcement/index.html +++ b/topics/kickstarter-announcement/index.html @@ -365,13 +365,13 @@ -
Kickstarting Django REST framework 3
+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
+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.
@@ -388,10 +388,10 @@Many thanks to everyone for your support so far,
Tom Christie :)
-Sponsors
+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
+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.
- Eventbrite
@@ -413,7 +413,7 @@
-Gold sponsors
+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.
- LaterPay
@@ -447,7 +447,7 @@
-Silver sponsors
+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 choosen to privately support the project at this level.
- IMT Computer Services
@@ -491,12 +491,12 @@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
+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
+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!
diff --git a/topics/project-management/index.html b/topics/project-management/index.html index 40871c3e8..3f9046998 100644 --- a/topics/project-management/index.html +++ b/topics/project-management/index.html @@ -377,7 +377,7 @@ -Project management
+Project management
"No one can whistle a symphony; it takes a whole orchestra to play it"
— Halford E. Luccock
@@ -386,9 +386,9 @@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
+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
+Current team
The maintenance team for Q1 2015:
-
- @tomchristie
@@ -397,7 +397,7 @@- @kevin-brown
- @jpadilla
Maintenance cycles
+Maintenance cycles
Each maintenance cycle is initiated by an issue being opened with the
Processlabel.
- To be considered for a maintainer role simply comment against the issue.
@@ -430,7 +430,7 @@ If you wish to be considered for this or a future date, please comment against t To modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.Responsibilities of team members
+Responsibilities of team members
Team members have the following responsibilities.
- Close invalid or resolved tickets.
@@ -448,7 +448,7 @@ To modify this process for future maintenance cycles make a pull request to theIt 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
+Release process
The release manager is selected on every quarterly maintenance cycle.
- The manager should be selected by
@@ -484,9 +484,9 @@ To modify this process for future releases make a pull request to the [project m@tomchristie.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
+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
+Managing Transifex
The official Transifex client is used to upload and download translations to Transifex. The client is installed using pip:
@@ -497,7 +497,7 @@ token = *** password = *** hostname = https://www.transifex.com -pip install transifex-clientUpload new source files
+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 @@ -513,7 +513,7 @@ tx push -s- 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
+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 @@ -522,14 +522,14 @@ cd rest_framework django-admin.py compilemessages
-Project requirements
+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
requirementsdirectory. The requirements files are referenced from thetox.iniconfiguration 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
+Project ownership
The PyPI package is owned by
@tomchristie. As a backup@j4miealso has ownership of the package.If
-@tomchristieceases to participate in the project then@j4miehas responsibility for handing over ownership duties.Outstanding management & ownership issues
+Outstanding management & ownership issues
The following issues still need to be addressed:
- Consider moving the repo into a proper GitHub organization.
diff --git a/topics/release-notes/index.html b/topics/release-notes/index.html index 87ea5ee88..1d44fb507 100644 --- a/topics/release-notes/index.html +++ b/topics/release-notes/index.html @@ -385,16 +385,16 @@ -Release Notes
+Release Notes
-Release Early, Release Often
— Eric S. Raymond, The Cathedral and the Bazaar.
Versioning
+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
+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:
@@ -409,7 +409,7 @@
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
+Upgrading
To upgrade Django REST framework to the latest version, use pip:
@@ -417,8 +417,17 @@pip install -U djangorestframeworkpip freeze | grep djangorestframework
-3.3.x series
-3.3.0
+3.3.x series
+3.3.1
+Date: 4th November 2015.
++
+- Resolve parsing bug when accessing
+request.POST(#3592)- Correctly deal with
+to_fieldreferring to primary key. (#3593)- Allow filter HTML to render when no
+filter_classis 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)
@@ -433,13 +442,13 @@- Removed support for Django 1.5 & 1.6. (#3421, #3429)
- Removed 'south' migrations. (#3495)
3.2.x series
-3.2.5
+3.2.x series
+3.2.5
Date: 27th October 2015.
-
- Escape
usernamein optional logout tag. (#3550)3.2.4
+3.2.4
Date: 21th September 2015.
-
- Don't error on missing
@@ -448,7 +457,7 @@ViewSet.search_fieldsattribute. (#3324, #3323)- Multi-level dictionaries not supported in multipart requests. (#3314)
- Fix
ListFieldtruncation on HTTP PATCH (#3415, #2761)3.2.3
+3.2.3
Date: 24th August 2015.
-
- Added
@@ -459,7 +468,7 @@html_cutoffandhtml_cutoff_textfor limiting select dropdowns. (#3313)- Fix to ensure admin renderer continues to work when pagination is disabled. (#3275)
- Resolve error with
LimitOffsetPaginationwhen count=0, offset=0. (#3303)3.2.2
+3.2.2
Date: 13th August 2015.
-
- Add
@@ -469,7 +478,7 @@display_value()method for use when displaying relational field select inputs. (#3254)- 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
+3.2.1
Date: 7th August 2015.
-
- Fix for relational select widgets rendering without any choices. (#3237)
@@ -477,7 +486,7 @@- Fix for ListFields with single value in HTML form input. (#3238)
- Allow
request.FILESfor compat with Django'sHTTPRequestclass. (#3239)3.2.0
+3.2.0
Date: 6th August 2015.
- Add
@@ -511,8 +520,8 @@AdminRenderer. (#2926)- Numerous other cleanups, improvements to error messaging, private API & minor fixes.
-3.1.x series
-3.1.3
+3.1.x series
+3.1.3
Date: 4th June 2015.
-
- Add
@@ -528,7 +537,7 @@DurationField. (#2481, #2989)IPAddressFieldimprovements. (#2747, #2618, #3008)- Improve
DecimalFieldfor easier subclassing. (#2695)3.1.2
+3.1.2
Date: 13rd May 2015.
-
- @@ -547,7 +556,7 @@
DateField.to_representationcan handle str and empty values. (#2656, #2687, #2869)- Check
AcceptHeaderVersioningwith content negotiation in place. (#2868)- Allow
DjangoObjectPermissionsto use views that defineget_queryset. (#2905)3.1.1
+3.1.1
Date: 23rd March 2015.
-
- Security fix: Escape tab switching cookie name in browsable API.
@@ -562,12 +571,12 @@- Support serializing unsaved models with related fields. (#2637, #2641)
- Allow blank/null on radio.html choices. (#2631)
3.1.0
+3.1.0
Date: 5th March 2015.
For full details see the 3.1 release announcement.
-3.0.x series
-3.0.5
+3.0.x series
+3.0.5
Date: 10th February 2015.
-
- Fix a bug where
@@ -579,7 +588,7 @@_closable_objectsbreaks pickling. (#1850, #2492)- Fix
detail_routeandlist_routemutable argument. (#2518)- Prefetching the user object when getting the token in
TokenAuthentication. (#2519)3.0.4
+3.0.4
Date: 28th January 2015.
-
- Django 1.8a1 support. (#2425, #2446, #2441)
@@ -596,7 +605,7 @@- Fix the serializer inheritance. (#2388)
- Fix caching issues with
ReturnDict. (#2360)3.0.3
+3.0.3
Date: 8th January 2015.
-
- Fix
@@ -615,7 +624,7 @@MinValueValidatoronmodels.DateField. (#2369)- Ability to customize router URLs for custom actions, using
url_path. (#2010)- Don't install Django REST Framework as egg. (#2386)
3.0.2
+3.0.2
Date: 17th December 2014.
-
- Ensure
@@ -626,7 +635,7 @@request.useris made available to response middleware. (#2155)- Fix empty HTML values when a default is provided. (#2280, #2294)
- Fix
SlugRelatedFieldraisingUnicodeEncodeErrorwhen used as a multiple choice input. (#2290)3.0.1
+3.0.1
Date: 11th December 2014.
-
- More helpful error message when the default Serializer
@@ -650,7 +659,7 @@create()fails. (#2013)- Improve field lookup behavior for dicts/mappings. (#2244, #2243)
- Optimized hyperlinked PK. (#2242)
3.0.0
+3.0.0
Date: 1st December 2014
For full details see the 3.0 release announcement.
@@ -677,6 +686,8 @@ + + diff --git a/topics/rest-hypermedia-hateoas/index.html b/topics/rest-hypermedia-hateoas/index.html index b083bbdb4..8cbaf6dd6 100644 --- a/topics/rest-hypermedia-hateoas/index.html +++ b/topics/rest-hypermedia-hateoas/index.html @@ -369,7 +369,7 @@ -REST, Hypermedia & HATEOAS
+REST, Hypermedia & HATEOAS
You keep using that word "REST". I do not think it means what you think it means.
— Mike Amundsen, REST fest 2012 keynote.
@@ -387,12 +387,12 @@ the Design of Network-based Software Architectures.- The Richardson Maturity Model.
For a more thorough background, check out Klabnik's Hypermedia API reading list.
-Building Hypermedia APIs with REST framework
+Building Hypermedia APIs with REST framework
REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.
-What REST framework provides.
+What REST framework provides.
It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.
-What REST framework doesn't provide.
+What REST framework doesn't provide.
What REST framework doesn't do is give you machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html index 48782c454..44b6076e5 100644 --- a/topics/third-party-resources/index.html +++ b/topics/third-party-resources/index.html @@ -373,21 +373,21 @@ -Third Party Resources
+Third Party Resources
-Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.
— Jan Bosch.
About Third Party Packages
+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
+How to create a Third Party Package
+Creating your package
You can use this cookiecutter template for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
Note: Let us know if you have an alternate cookiecuter package so we can also link to it.
-Running the initial cookiecutter command
+Running the initial cookiecutter command
To run the initial cookiecutter command, you'll first need to install the Python
cookiecutterpackage.@@ -405,13 +405,13 @@ project_short_description (default is "Your project description goes here")? year (default is "2014")? version (default is "0.1.0")?$ pip install cookiecutterGetting it onto GitHub
+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
+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.ymlfile which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.Uploading to PyPI
+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.
@@ -430,10 +430,10 @@ You probably want to also tag the version now: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
+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, andsetup.pyto match the set of versions you wish to support.Tests
+Tests
The cookiecutter template includes a
runtests.pywhich uses thepytestpackage as a test runner.Before running, you'll need to install a couple test requirements.
$ pip install -r requirements.txt @@ -475,22 +475,22 @@ You probably want to also tag the version now:
envlistis a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:-$ tox -lVersion compatibility
+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.pymodule, 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 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
+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
+Adding to the Django REST framework docs
Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions. You can also link your package under the Third Party Resources section.
-Announce on the discussion group.
+Announce on the discussion group.
You can also let others know about your package through the discussion group.
-Existing Third Party Packages
+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
+Authentication
-
- djangorestframework-digestauth - Provides Digest Access Authentication support.
- django-oauth-toolkit - Provides OAuth 2.0 support.
@@ -501,52 +501,52 @@ You probably want to also tag the version now:- 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.
Permissions
+Permissions
-
- drf-any-permissions - Provides alternative permission handling.
- djangorestframework-composed-permissions - Provides a simple way to define complex permissions.
- rest_condition - Another extension for building complex permissions in a simple and convenient way.
- dry-rest-permissions - Provides a simple way to define permissions for individual api actions.
Serializers
+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.
Serializer 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
ImageFieldthat makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.Views
+Views
-
- djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
- django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
Routers
+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
+Parsers
-
- djangorestframework-msgpack - Provides MessagePack renderer and parser support.
- djangorestframework-camel-case - Provides camel case JSON renderers and parsers.
Renderers
+Renderers
-
- djangorestframework-csv - Provides CSV renderer support.
- drf_ujson - Implements JSON rendering using the UJSON package.
- rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
Filtering
+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.
Misc
+Misc
-
- cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.
- djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
@@ -559,9 +559,10 @@ You probably want to also tag the version now:- drf-tracking - Utilities to track requests to DRF API views.
- django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm, which are adapters between DRF serializers and Django forms.
- drf-haystack - Haystack search for Django Rest Framework
+- django-rest-framework-version-transforms - Enables the use of delta transformations for versioning of DRF resource representations.
Other Resources
-Tutorials
+Other Resources
+Tutorials
-
- Beginner's Guide to the Django Rest Framework
- Getting Started with Django Rest Framework and AngularJS
@@ -572,19 +573,19 @@ You probably want to also tag the version now:- Django Rest Framework User Endpoint
- Check credentials using Django Rest Framework
Videos
+Videos
-
- Ember and Django Part 1 (Video)
- Django Rest Framework Part 1 (Video)
- Pyowa July 2013 - Django Rest Framework (Video)
- django-rest-framework and angularjs (Video)
Articles
+Articles
-
- Web API performance: profiling Django REST framework
- API Development with Django and Django REST Framework
Documentations
+Documentations
diff --git a/tutorial/1-serialization/index.html b/tutorial/1-serialization/index.html index 270bed600..7e4a12512 100644 --- a/tutorial/1-serialization/index.html +++ b/tutorial/1-serialization/index.html @@ -397,14 +397,14 @@ -Tutorial 1: Serialization
-Introduction
+Tutorial 1: Serialization
+Introduction
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the quickstart documentation instead.
Note: The code for this tutorial is available in the tomchristie/rest-framework-tutorial repository on GitHub. The completed implementation is also online as a sandbox version for testing, available here.
-Setting up a new environment
+Setting up a new environment
Before we do anything else we'll create a new virtual environment, using virtualenv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
virtualenv env source env/bin/activate @@ -415,7 +415,7 @@ pip install djangorestframework pip install pygments # We'll be using this for the code highlightingNote: To exit the virtualenv environment at any time, just type
-deactivate. For more information see the virtualenv documentation.Getting started
+Getting started
Okay, we're ready to get coding. To get started, let's create a new project to work with.
cd ~ @@ -438,7 +438,7 @@ cd tutorial ]Okay, we're ready to roll.
-Creating a model to work with
+Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple
Snippetmodel that is used to store code snippets. Go ahead and edit thesnippets/models.pyfile. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.from django.db import models from pygments.lexers import get_all_lexers @@ -464,7 +464,7 @@ class Snippet(models.Model):-python manage.py makemigrations snippets python manage.py migrateCreating a Serializer class
+Creating a Serializer class
The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as
json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in thesnippetsdirectory namedserializers.pyand add the following.-from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES @@ -500,7 +500,7 @@ class SnippetSerializer(serializers.Serializer):A serializer class is very similar to a Django
Formclass, and includes similar validation flags on the various fields, such asrequired,max_lengthanddefault.The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The
{'base_template': 'textarea.html'}flag above is equivalent to usingwidget=widgets.Textareaon a DjangoFormclass. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.We can actually also save ourselves some time by using the
-ModelSerializerclass, as we'll see later, but for now we'll keep our serializer definition explicit.Working with Serializers
+Working with Serializers
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
@@ -547,7 +547,7 @@ serializer.save() serializer.data # [OrderedDict([('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]python manage.py shellUsing ModelSerializers
+Using ModelSerializers
Our
SnippetSerializerclass is replicating a lot of information that's also contained in theSnippetmodel. It would be nice if we could keep our code a bit more concise.In the same way that Django provides both
Formclasses andModelFormclasses, REST framework includes bothSerializerclasses, andModelSerializerclasses.Let's look at refactoring our serializer using the
ModelSerializerclass. @@ -574,7 +574,7 @@ SnippetSerializer():- An automatically determined set of fields.
- Simple default implementations for the
-create()andupdate()methods.Writing regular Django views using our Serializer
+Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class. For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into
@@ -652,7 +652,7 @@ urlpatterns = [ ]json.It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed
-json, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.Testing our first attempt at a Web API
+Testing our first attempt at a Web API
Now we can start up a sample server that serves our snippets.
Quit out of the shell...
quit() @@ -711,7 +711,7 @@ HTTP/1.1 200 OK }Similarly, you can have the same json displayed by visiting these URLs in a web browser.
-Where are we now
+Where are we now
We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
Our API views don't do anything particularly special at the moment, beyond serving
jsonresponses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.We'll see how we can start to improve things in part 2 of the tutorial.
diff --git a/tutorial/2-requests-and-responses/index.html b/tutorial/2-requests-and-responses/index.html index a32aab8fe..cf0a40a9f 100644 --- a/tutorial/2-requests-and-responses/index.html +++ b/tutorial/2-requests-and-responses/index.html @@ -389,21 +389,21 @@ -Tutorial 2: Requests and Responses
+Tutorial 2: Requests and Responses
From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks.
-Request objects
+Request objects
REST framework introduces a
Requestobject that extends the regularHttpRequest, and provides more flexible request parsing. The core functionality of theRequestobject is therequest.dataattribute, which is similar torequest.POST, but more useful for working with Web APIs.-request.POST # Only handles form data. Only works for 'POST' method. request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.Response objects
+Response objects
REST framework also introduces a
Responseobject, which is a type ofTemplateResponsethat takes unrendered content and uses content negotiation to determine the correct content type to return to the client.-return Response(data) # Renders to content type as requested by the client.Status codes
+Status codes
Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as
-HTTP_400_BAD_REQUESTin thestatusmodule. It's a good idea to use these throughout rather than using numeric identifiers.Wrapping API views
+Wrapping API views
REST framework provides two wrappers you can use to write API views.
- The
@@ -411,7 +411,7 @@ request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' met@api_viewdecorator for working with function based views.These wrappers provide a few bits of functionality such as making sure you receive
Requestinstances in your view, and adding context toResponseobjects so that content negotiation can be performed.The wrappers also provide behaviour such as returning
-405 Method Not Allowedresponses when appropriate, and handling anyParseErrorexception that occurs when accessingrequest.datawith malformed input.Pulling it all together
+Pulling it all together
Okay, let's go ahead and start using these new components to write a few views.
We don't need our
JSONResponseclass inviews.pyanymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.from rest_framework import status @@ -467,7 +467,7 @@ def snippet_detail(request, pk):This should all feel very familiar - it is not a lot different from working with regular Django views.
Notice that we're no longer explicitly tying our requests or responses to a given content type.
-request.datacan handle incomingjsonrequests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.Adding optional format suffixes to our URLs
+Adding optional format suffixes to our URLs
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4/.json.
Start by adding a
formatkeyword argument to both of the views, like so.def snippet_list(request, format=None): @@ -488,7 +488,7 @@ urlpatterns = [ urlpatterns = format_suffix_patterns(urlpatterns)We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
-How's it looking?
+How's it looking?
Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
We can get a list of all of the snippets, as before.
http http://127.0.0.1:8000/snippets/ @@ -548,11 +548,11 @@ http --json POST http://127.0.0.1:8000/snippets/ code="print 456" }Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.
-Browsability
+Browsability
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
See the browsable api topic for more information about the browsable API feature and how to customize it.
-What's next?
+What's next?
In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.
diff --git a/tutorial/3-class-based-views/index.html b/tutorial/3-class-based-views/index.html index 066d9557c..05251faba 100644 --- a/tutorial/3-class-based-views/index.html +++ b/tutorial/3-class-based-views/index.html @@ -369,9 +369,9 @@ -Tutorial 3: Class Based Views
+Tutorial 3: Class Based Views
We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.
-Rewriting our API using class based views
+Rewriting our API using class based views
We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring of
views.py.from snippets.models import Snippet from snippets.serializers import SnippetSerializer @@ -440,7 +440,7 @@ urlpatterns = [ urlpatterns = format_suffix_patterns(urlpatterns)Okay, we're done. If you run the development server everything should be working just as before.
-Using mixins
+Using mixins
One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our
@@ -480,7 +480,7 @@ class SnippetList(mixins.ListModelMixin, return self.destroy(request, *args, **kwargs)views.pymodule again.Pretty similar. Again we're using the
-GenericAPIViewclass to provide the core functionality, and adding in mixins to provide the.retrieve(),.update()and.destroy()actions.Using generic class based views
+Using generic class based views
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our
views.pymodule even more.-from snippets.models import Snippet from snippets.serializers import SnippetSerializer diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html index c993a7262..086a80a33 100644 --- a/tutorial/4-authentication-and-permissions/index.html +++ b/tutorial/4-authentication-and-permissions/index.html @@ -393,7 +393,7 @@ -Tutorial 4: Authentication & Permissions
+Tutorial 4: Authentication & Permissions
Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
-
- Code snippets are always associated with a creator.
@@ -401,7 +401,7 @@- Only the creator of a snippet may update or delete it.
- Unauthenticated requests should have full read-only access.
Adding information to our model
+Adding information to our model
We're going to make a couple of changes to our
Snippetmodel class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.Add the following two fields to the
@@ -438,7 +438,7 @@ python manage.py migrateSnippetmodel inmodels.py.You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the
createsuperusercommand.-python manage.py createsuperuserAdding endpoints for our User models
+Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In
serializers.pyadd:from django.contrib.auth.models import User @@ -470,7 +470,7 @@ class UserDetail(generics.RetrieveAPIView):-url(r'^users/$', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),Associating Snippets with Users
+Associating Snippets with Users
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
The way we deal with that is by overriding a
.perform_create()method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.On the
@@ -478,14 +478,14 @@ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), serializer.save(owner=self.request.user)SnippetListview class, add the following method:The
-create()method of our serializer will now be passed an additional'owner'field, along with the validated data from the request.Updating our serializer
+Updating our serializer
Now that snippets are associated with the user that created them, let's update our
SnippetSerializerto reflect that. Add the following field to the serializer definition inserializers.py:owner = serializers.ReadOnlyField(source='owner.username')Note: Make sure you also add
'owner',to the list of fields in the innerMetaclass.This field is doing something quite interesting. The
sourceargument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.The field we've added is the untyped
-ReadOnlyFieldclass, in contrast to the other typed fields, such asCharField,BooleanFieldetc... The untypedReadOnlyFieldis always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also usedCharField(read_only=True)here.Adding required permissions to views
+Adding required permissions to views
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is
IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.First add the following import in the views module
@@ -494,7 +494,7 @@ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),Then, add the following property to both the
SnippetListandSnippetDetailview classes.-permission_classes = (permissions.IsAuthenticatedOrReadOnly,)Adding login to the Browsable API
+Adding login to the Browsable API
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
We can add a login view for use with the browsable API, by editing the URLconf in our project-level
urls.pyfile.Add the following import at the top of the file:
@@ -509,7 +509,7 @@ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),The
r'^api-auth/'part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the'rest_framework'namespace.Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.
-Object level permissions
+Object level permissions
Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
In the snippets app, create a new file,
@@ -538,7 +538,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):permissions.pyfrom snippets.permissions import IsOwnerOrReadOnlyNow, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
-Authenticating with the API
+Authenticating with the API
Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are
SessionAuthenticationandBasicAuthentication.When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
@@ -562,7 +562,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission): "style": "friendly" }Summary
+Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html index 24e3fa5c9..8d137e728 100644 --- a/tutorial/5-relationships-and-hyperlinked-apis/index.html +++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html @@ -381,9 +381,9 @@ -Tutorial 5: Relationships & Hyperlinked APIs
+Tutorial 5: Relationships & Hyperlinked APIs
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
-Creating an endpoint for the root of our API
+Creating an endpoint for the root of our API
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the
@api_viewdecorator we introduced earlier. In yoursnippets/views.pyadd:from rest_framework.decorators import api_view from rest_framework.response import Response @@ -398,7 +398,7 @@ def api_root(request, format=None): })Two things should be noticed here. First, we're using REST framework's
-reversefunction in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in oursnippets/urls.py.Creating an endpoint for the highlighted snippets
+Creating an endpoint for the highlighted snippets
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
@@ -421,7 +421,7 @@ We'll add a url pattern for our new API root insnippets/urls.py:And then add a url pattern for the snippet highlights:
-url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),Hyperlinking our API
+Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
- Using primary keys.
@@ -460,7 +460,7 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):Notice that we've also added a new
'highlight'field. This field is of the same type as theurlfield, except that it points to the'snippet-highlight'url pattern, instead of the'snippet-detail'url pattern.Because we've included format suffixed URLs such as
-'.json', we also need to indicate on thehighlightfield that any format suffixed hyperlinks it returns should use the'.html'suffix.Making sure our URL patterns are named
+Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
- The root of our API refers to
@@ -499,7 +499,7 @@ urlpatterns += [ namespace='rest_framework')), ] -'user-list'and'snippet-list'.Adding pagination
+Adding pagination
The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our
tutorial/settings.pyfile slightly. Add the following setting:REST_FRAMEWORK = { @@ -508,7 +508,7 @@ urlpatterns += [Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
-Browsing the API
+Browsing the API
If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html index 838854c6e..7f4482de3 100644 --- a/tutorial/6-viewsets-and-routers/index.html +++ b/tutorial/6-viewsets-and-routers/index.html @@ -381,11 +381,11 @@ -Tutorial 6: ViewSets & Routers
+Tutorial 6: ViewSets & Routers
REST framework includes an abstraction for dealing with
ViewSets, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
ViewSetclasses are almost the same thing asViewclasses, except that they provide operations such asread, orupdate, and not method handlers such asgetorput.A
-ViewSetclass is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using aRouterclass which handles the complexities of defining the URL conf for you.Refactoring to use ViewSets
+Refactoring to use ViewSets
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our
UserListandUserDetailviews into a singleUserViewSet. We can remove the two views, and replace them with a single class:-from rest_framework import viewsets @@ -425,7 +425,7 @@ class SnippetViewSet(viewsets.ModelViewSet):Notice that we've also used the
@detail_routedecorator to create a custom action, namedhighlight. This decorator can be used to add any custom endpoints that don't fit into the standardcreate/update/deletestyle.Custom actions which use the
@detail_routedecorator will respond toGETrequests. We can use themethodsargument if we wanted an action that responded toPOSTrequests.The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.
-Binding ViewSets to URLs explicitly
+Binding ViewSets to URLs explicitly
The handler methods only get bound to the actions when we define the URLConf. To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
In the
@@ -463,7 +463,7 @@ user_detail = UserViewSet.as_view({ url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail') ])urls.pyfile we bind ourViewSetclasses into a set of concrete views.Using Routers
+Using Routers
Because we're using
ViewSetclasses rather thanViewclasses, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using aRouterclass. All we need to do is register the appropriate view sets with a router, and let it do the rest.Here's our re-wired
urls.pyfile.from django.conf.urls import url, include @@ -484,14 +484,14 @@ urlpatterns = [Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
The
-DefaultRouterclass we're using also automatically creates the API root view for us, so we can now delete theapi_rootmethod from ourviewsmodule.Trade-offs between views vs viewsets
+Trade-offs between views vs viewsets
Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
-Reviewing our work
+Reviewing our work
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
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
+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:
- Contribute on GitHub by reviewing and submitting issues, and making pull requests.
diff --git a/tutorial/quickstart/index.html b/tutorial/quickstart/index.html index 252a24233..b7e7b963b 100644 --- a/tutorial/quickstart/index.html +++ b/tutorial/quickstart/index.html @@ -381,9 +381,9 @@ -Quickstart
+Quickstart
We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
-Project setup
+Project setup
Create a new Django project named
tutorial, then start a new app calledquickstart.# Create the project directory mkdir tutorial @@ -410,7 +410,7 @@ cd ..python manage.py createsuperuserOnce you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...
-Serializers
+Serializers
First up we're going to define some serializers. Let's create a new module named
tutorial/quickstart/serializers.pythat we'll use for our data representations.from django.contrib.auth.models import User, Group from rest_framework import serializers @@ -428,7 +428,7 @@ class GroupSerializer(serializers.HyperlinkedModelSerializer): fields = ('url', 'name')Notice that we're using hyperlinked relations in this case, with
-HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.Views
+Views
Right, we'd better write some views then. Open
tutorial/quickstart/views.pyand get typing.from django.contrib.auth.models import User, Group from rest_framework import viewsets @@ -452,7 +452,7 @@ class GroupViewSet(viewsets.ModelViewSet):Rather than write multiple views we're grouping together all the common behavior into classes called
ViewSets.We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
-URLs
+URLs
Okay, now let's wire up the API URLs. On to
tutorial/urls.py...from django.conf.urls import url, include from rest_framework import routers @@ -472,7 +472,7 @@ urlpatterns = [Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
-Settings
+Settings
We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in
tutorial/settings.pyINSTALLED_APPS = ( ... @@ -486,7 +486,7 @@ REST_FRAMEWORK = {Okay, we're done.
-Testing our API
+Testing our API
We're now ready to test the API we've built. Let's fire up the server from the command line.
python ./manage.py runserver