aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api-guide')
-rw-r--r--docs/api-guide/authentication.md41
-rw-r--r--docs/api-guide/fields.md41
-rw-r--r--docs/api-guide/format-suffixes.md21
-rw-r--r--docs/api-guide/renderers.md4
-rw-r--r--docs/api-guide/settings.md106
5 files changed, 171 insertions, 42 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index d7918e10..740f1035 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -10,7 +10,7 @@ Authentication is the mechanism of associating an incoming request with a set of
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
-Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
+Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
@@ -113,7 +113,12 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
-To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
+To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
+
+ INSTALLED_APPS = (
+ ...
+ 'rest_framework.authtoken'
+ )
You'll also need to create tokens for your users.
@@ -135,10 +140,14 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
WWW-Authenticate: Token
+---
+
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
---
+#### Generating Tokens
+
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@receiver(post_save, sender=User)
@@ -154,8 +163,7 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)
-When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password.
-REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
+When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
@@ -169,6 +177,23 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
+#### Custom user models
+
+The `rest_framework.authtoken` app includes a south migration that will create the authtoken table. If you're using a [custom user model][custom-user-model] you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.
+
+You can do so by inserting a `needed_by` attribute in your user migration:
+
+ class Migration:
+
+ needed_by = (
+ ('authtoken', '0001_initial'),
+ )
+
+ def forwards(self):
+ ...
+
+For more details, see the [south documentation on dependencies][south-dependencies].
+
## 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.
@@ -205,7 +230,7 @@ In some circumstances instead of returning `None`, you may want to raise an `Aut
Typically the approach you should take is:
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
-* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, without checking any other authentication schemes.
+* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
@@ -216,7 +241,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
class ExampleAuthentication(authentication.BaseAuthentication):
- def has_permission(self, request, view, obj=None):
+ def authenticate(self, request):
username = request.META.get('X_USERNAME')
if not username:
return None
@@ -247,6 +272,8 @@ HTTP digest authentication is a widely implemented scheme that was intended to r
[throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
+[custom-user-model]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model
+[south-dependencies]: http://south.readthedocs.org/en/latest/dependencies.html
[juanriaza]: https://github.com/juanriaza
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
-[rfc5849] : http://tools.ietf.org/html/rfc5849 \ No newline at end of file
+[rfc5849] : http://tools.ietf.org/html/rfc5849
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 8c28273b..9a745cf1 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,7 +2,7 @@
# 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.
+> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
>
> — [Django documentation][cite]
@@ -102,7 +102,7 @@ You can customize this behavior by overriding the `.to_native(self, value)` met
## WritableField
-A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
+A field that supports both read and write operations. By itself `WritableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
## ModelField
@@ -181,12 +181,6 @@ Corresponds to `django.forms.fields.RegexField`
**Signature:** `RegexField(regex, max_length=None, min_length=None)`
-## DateField
-
-A date representation.
-
-Corresponds to `django.db.models.fields.DateField`
-
## DateTimeField
A date and time representation.
@@ -203,12 +197,41 @@ If you want to override this behavior, you'll need to declare the `DateTimeField
class Meta:
model = Comment
+**Signature:** `DateTimeField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, the `DATETIME_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
+
+DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000'`)
+
+## DateField
+
+A date representation.
+
+Corresponds to `django.db.models.fields.DateField`
+
+**Signature:** `DateField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, the `DATE_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
+
+Date format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
+
## TimeField
A time representation.
+Optionally takes `format` as parameter to replace the matching pattern.
+
Corresponds to `django.db.models.fields.TimeField`
+**Signature:** `TimeField(format=None, input_formats=None)`
+
+* `format` - A string representing the output format. If not specified, the `TIME_FORMAT` setting will be used, which defaults to `'iso-8601'`.
+* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
+
+Time format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
+
## IntegerField
An integer representation.
@@ -252,3 +275,5 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
+[strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
+[iso8601]: http://www.w3.org/TR/NOTE-datetime
diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md
index 6d5feba4..dae3dea3 100644
--- a/docs/api-guide/format-suffixes.md
+++ b/docs/api-guide/format-suffixes.md
@@ -29,18 +29,27 @@ Example:
urlpatterns = patterns('blog.views',
url(r'^/$', 'api_root'),
- url(r'^comment/$', 'comment_root'),
- url(r'^comment/(?P<pk>[0-9]+)/$', 'comment_instance')
+ url(r'^comments/$', 'comment_list'),
+ url(r'^comments/(?P<pk>[0-9]+)/$', 'comment_detail')
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
-When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example.
+When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example:
- @api_view(('GET',))
- def api_root(request, format=None):
+ @api_view(('GET', 'POST'))
+ def comment_list(request, format=None):
# do stuff...
+Or with class based views:
+
+ class CommentList(APIView):
+ def get(self, request, format=None):
+ # do stuff...
+
+ def post(self, request, format=None):
+ # do stuff...
+
The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting.
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
@@ -58,4 +67,4 @@ It is actually a misconception. For example, take the following quote from Roy
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
-[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844 \ No newline at end of file
+[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 5de1491b..3c8396aa 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -123,7 +123,7 @@ The template name is determined by (in order of preference):
An example of a view that uses `TemplateHTMLRenderer`:
- class UserInstance(generics.RetrieveUserAPIView):
+ class UserDetail(generics.RetrieveUserAPIView):
"""
A view that returns a templated HTML representations of a given user.
"""
@@ -301,4 +301,4 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[juanriaza]: https://github.com/juanriaza
[mjumbewu]: https://github.com/mjumbewu
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
-[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv \ No newline at end of file
+[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index e103fbab..11638696 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -34,7 +34,11 @@ The `api_settings` object will check for any user-defined settings, and otherwis
# API Reference
-## DEFAULT_RENDERER_CLASSES
+## API policy settings
+
+*The following settings control the basic API policies, and are applied to every `APIView` class based view, or `@api_view` function based view.*
+
+#### DEFAULT_RENDERER_CLASSES
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
@@ -45,7 +49,7 @@ Default:
'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.DATA` property.
@@ -57,7 +61,7 @@ Default:
'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.user` or `request.auth` properties.
@@ -68,7 +72,7 @@ Default:
'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.
@@ -78,59 +82,77 @@ 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'`
-## DEFAULT_MODEL_SERIALIZER_CLASS
+---
+
+## Generic view settings
+
+*The following settings control the behavior of the generic class based views.*
+
+#### DEFAULT_MODEL_SERIALIZER_CLASS
A class that determines the default type of model serializer that should be used by a generic view if `model` is specified, but `serializer_class` is not provided.
Default: `'rest_framework.serializers.ModelSerializer'`
-## DEFAULT_PAGINATION_SERIALIZER_CLASS
+#### DEFAULT_PAGINATION_SERIALIZER_CLASS
A class the determines the default serialization style for paginated responses.
Default: `rest_framework.pagination.PaginationSerializer`
-## FILTER_BACKEND
+#### FILTER_BACKEND
The filter backend class that should be used for generic filtering. If set to `None` then 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: `None`
-## PAGINATE_BY_PARAM
+#### PAGINATE_BY_PARAM
The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size.
Default: `None`
-## UNAUTHENTICATED_USER
+---
+
+## Authentication settings
+
+*The following settings control the behavior of unauthenticated requests.*
+
+#### UNAUTHENTICATED_USER
The class that should be used to initialize `request.user` for unauthenticated requests.
Default: `django.contrib.auth.models.AnonymousUser`
-## UNAUTHENTICATED_TOKEN
+#### UNAUTHENTICATED_TOKEN
The class that should be used to initialize `request.auth` for unauthenticated requests.
Default: `None`
-## FORM_METHOD_OVERRIDE
+---
+
+## Browser overrides
+
+*The following settings provide URL or form-based overrides of the default browser behavior.*
+
+#### FORM_METHOD_OVERRIDE
The name of a form field that may be used to override the HTTP method of the form.
@@ -138,7 +160,7 @@ If the value of this setting is `None` then form method overloading will be disa
Default: `'_method'`
-## FORM_CONTENT_OVERRIDE
+#### FORM_CONTENT_OVERRIDE
The name of a form field that may be used to override the content of the form payload. Must be used together with `FORM_CONTENTTYPE_OVERRIDE`.
@@ -146,7 +168,7 @@ If either setting is `None` then form content overloading will be disabled.
Default: `'_content'`
-## FORM_CONTENTTYPE_OVERRIDE
+#### FORM_CONTENTTYPE_OVERRIDE
The name of a form field that may be used to override the content type of the form payload. Must be used together with `FORM_CONTENT_OVERRIDE`.
@@ -154,7 +176,7 @@ If either setting is `None` then form content overloading will be disabled.
Default: `'_content_type'`
-## URL_ACCEPT_OVERRIDE
+#### URL_ACCEPT_OVERRIDE
The name of a URL parameter that may be used to override the HTTP `Accept` header.
@@ -162,13 +184,59 @@ If the value of this setting is `None` then URL accept overloading will be disab
Default: `'accept'`
-## URL_FORMAT_OVERRIDE
+#### URL_FORMAT_OVERRIDE
The name of a URL parameter that may be used to override the default `Accept` header based content negotiation.
Default: `'format'`
-## FORMAT_SUFFIX_KWARG
+---
+
+## Date/Time formatting
+
+*The following settings are used to control how date and time representations may be parsed and rendered.*
+
+#### DATETIME_FORMAT
+
+A format string that should be used by default for rendering the output of `DateTimeField` serializer fields.
+
+Default: `'iso-8601'`
+
+#### DATETIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
+
+Default: `['iso-8601']`
+
+#### DATE_FORMAT
+
+A format string that should be used by default for rendering the output of `DateField` serializer fields.
+
+Default: `'iso-8601'`
+
+#### DATE_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
+
+Default: `['iso-8601']`
+
+#### TIME_FORMAT
+
+A format string that should be used by default for rendering the output of `TimeField` serializer fields.
+
+Default: `'iso-8601'`
+
+#### TIME_INPUT_FORMATS
+
+A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
+
+Default: `['iso-8601']`
+
+---
+
+## Miscellaneous settings
+
+#### FORMAT_SUFFIX_KWARG
The name of a parameter in the URL conf that may be used to provide a format suffix.