aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api-guide')
-rwxr-xr-xdocs/api-guide/authentication.md14
-rw-r--r--docs/api-guide/content-negotiation.md29
-rwxr-xr-xdocs/api-guide/generic-views.md2
-rw-r--r--docs/api-guide/permissions.md13
-rw-r--r--docs/api-guide/relations.md8
-rw-r--r--docs/api-guide/renderers.md21
-rw-r--r--docs/api-guide/responses.md4
-rw-r--r--docs/api-guide/reverse.md2
-rw-r--r--docs/api-guide/routers.md10
-rw-r--r--docs/api-guide/serializers.md12
-rw-r--r--docs/api-guide/settings.md63
-rw-r--r--docs/api-guide/testing.md257
-rw-r--r--docs/api-guide/throttling.md20
-rw-r--r--docs/api-guide/views.md6
-rw-r--r--docs/api-guide/viewsets.md12
15 files changed, 431 insertions, 42 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 5d6e0d91..b1ab4622 100755
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -121,7 +121,7 @@ To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in y
'rest_framework.authtoken'
)
-Make sure to run `manage.py syncdb` after changing your settings.
+Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below).
You'll also need to create tokens for your users.
@@ -184,9 +184,11 @@ 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
+#### Schema migrations
-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.
+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:
@@ -201,6 +203,12 @@ You can do so by inserting a `needed_by` attribute in your user migration:
For more details, see the [south documentation on dependencies][south-dependencies].
+Also note that if you're using a `post_save` signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example:
+
+ python manage.py syncdb --noinput # Won't create a superuser just yet, due to `--noinput`.
+ python manage.py migrate
+ python manage.py createsuperuser
+
## 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.
diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md
index 10288c94..2a774278 100644
--- a/docs/api-guide/content-negotiation.md
+++ b/docs/api-guide/content-negotiation.md
@@ -43,7 +43,11 @@ This is a valid approach as the HTTP spec deliberately underspecifies how a serv
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.
+REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods.
+
+The `select_parser()` method should return one of the parser instances from the list of available parsers, or `None` if none of the parsers can handle the incoming request.
+
+The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception.
## Example
@@ -61,6 +65,27 @@ request when selecting the appropriate parser or renderer.
"""
Select the first renderer in the `.renderer_classes` list.
"""
- return renderers[0]
+ return (renderers[0], renderers[0].media_type)
+
+## Setting the content negotiation
+
+The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class.
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
+ }
+
+You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class based views.
+
+ class NoNegotiationView(APIView):
+ """
+ An example view that does not perform content negotiation.
+ """
+ content_negotiation_class = IgnoreClientContentNegotiation
+
+ def get(self, request, format=None):
+ return Response({
+ 'accepted media type': request.accepted_renderer.media_type
+ })
[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 67853ed0..32a4feef 100755
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -40,7 +40,7 @@ For more complex cases you might also want to override various methods on the vi
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
- url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list')
+ url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
---
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 2c0a055c..c6372f98 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -147,7 +147,7 @@ If you need to test if a request is a read operation or a write operation, you s
**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
-As of version 2.2 this signature has now been replaced with two separate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
+As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
For more details see the [2.2 release announcement][2.2-announcement].
@@ -188,6 +188,16 @@ Note that the generic views will check the appropriate object level permissions,
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][filtering] for more details.
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## DRF Any Permissions
+
+The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.
+
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
[throttling]: throttling.md
@@ -197,3 +207,4 @@ Also note that the generic views will only check the object-level permissions fo
[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
[2.2-announcement]: ../topics/2.2-announcement.md
[filtering]: filtering.md
+[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
index 50c9bc54..829a3c54 100644
--- a/docs/api-guide/relations.md
+++ b/docs/api-guide/relations.md
@@ -39,7 +39,7 @@ In order to explain the various types of relational fields, we'll use a couple o
## RelatedField
-`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method.
+`RelatedField` may be used to represent the target of the relationship using its `__unicode__` method.
For example, the following serializer.
@@ -71,7 +71,7 @@ This field is read only.
## PrimaryKeyRelatedField
-`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key.
+`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
For example, the following serializer:
@@ -252,7 +252,7 @@ If you want to implement a read-write relational field, you must also implement
## Example
-For, example, we could define a relational field, to serialize a track to a custom string representation, using it's ordering, title, and duration.
+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
@@ -386,7 +386,7 @@ For more information see [the Django documentation on generic relations][generic
By default, relational fields that target a ``ManyToManyField`` with a
``through`` model specified are set to read-only.
-If you exlicitly specify a relational field pointing to a
+If you explicitly specify a relational field pointing to a
``ManyToManyField`` with a through model, be sure to set ``read_only``
to ``True``.
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index b627c930..bb3d2015 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -217,13 +217,31 @@ Renders data into HTML for the Browsable API. This renderer will determine whic
**.charset**: `utf-8`
+#### Customizing BrowsableAPIRenderer
+
+By default the response content will be rendered with the highest priority renderer apart from `BrowseableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example:
+
+ class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
+ def get_default_renderer(self, view):
+ return JSONRenderer()
+
+## MultiPartRenderer
+
+This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
+
+**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
+
+**.format**: `'.multipart'`
+
+**.charset**: `utf-8`
+
---
# Custom renderers
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
-The method should return a bytestring, which wil be used as the body of the HTTP response.
+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:
@@ -373,6 +391,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
[cors]: http://www.w3.org/TR/cors/
[cors-docs]: ../topics/ajax-csrf-cors.md
+[testing]: testing.md
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md
index 399b7c23..5a42aa92 100644
--- a/docs/api-guide/responses.md
+++ b/docs/api-guide/responses.md
@@ -24,7 +24,7 @@ Unless you want to heavily customize REST framework for some reason, you should
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.
-The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object.
+The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object.
You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization.
@@ -54,7 +54,7 @@ The rendered content of the response. The `.render()` method must have been cal
## .template_name
-The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the reponse.
+The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response.
## .accepted_renderer
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 19930dc3..94262366 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -17,7 +17,7 @@ The advantages of doing so are:
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 it's output for you, which makes browsing the API much easier.
+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
diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md
index 86582905..072a2e79 100644
--- a/docs/api-guide/routers.md
+++ b/docs/api-guide/routers.md
@@ -38,7 +38,7 @@ The example above would generate the following URL patterns:
### Extra link and actions
Any methods on the viewset decorated with `@link` or `@action` will also be routed.
-For example, a given method like this on the `UserViewSet` class:
+For example, given a method like this on the `UserViewSet` class:
@action(permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
@@ -66,7 +66,7 @@ This router includes routes for the standard set of `list`, `create`, `retrieve`
<tr><td>POST</td><td>@action decorated method</td></tr>
</table>
-By default the URLs created by `SimpleRouter` are appending with a trailing slash.
+By default the URLs created by `SimpleRouter` are appended with a trailing slash.
This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
router = SimpleRouter(trailing_slash=False)
@@ -90,13 +90,13 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
<tr><td>POST</td><td>@action decorated method</td></tr>
</table>
-As with `SimpleRouter` the trailing slashs on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
+As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
router = DefaultRouter(trailing_slash=False)
# Custom Routers
-Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are strutured. 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.
+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 `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples.
@@ -139,7 +139,7 @@ The `SimpleRouter` class provides another example of setting the `.routes` attri
## Advanced custom routers
-If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
+If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 8e9de10e..bbc8d019 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -308,6 +308,12 @@ By default, all the model fields on the class will be mapped to corresponding se
Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Other models fields will be mapped to a corresponding serializer field.
+---
+
+**Note**: When validation is applied to a `ModelSerializer`, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set `blank=True` on the model field, as well as setting `required=False` on the serializer field.
+
+---
+
## Specifying which fields should be included
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
@@ -397,7 +403,7 @@ You can change the field that is used for object lookups by setting the `lookup_
Not that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships.
-For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
+For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
@@ -423,7 +429,7 @@ You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSe
Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.
-## Dynamically modifiying 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 `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
@@ -443,7 +449,7 @@ For example, if you wanted to be able to set which fields should be used by a se
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
- # Instatiate the superclass normally
+ # Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields:
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 4a5164c9..fe7925a5 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -28,7 +28,7 @@ you should use the `api_settings` object. For example.
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
-The `api_settings` object will check for any user-defined settings, and otherwise fallback 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.
+The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
---
@@ -149,6 +149,33 @@ Default: `None`
---
+## Test settings
+
+*The following settings control the behavior of APIRequestFactory and APIClient*
+
+#### TEST_REQUEST_DEFAULT_FORMAT
+
+The default format that should be used when making test requests.
+
+This should match up with the format of one of the renderer classes in the `TEST_REQUEST_RENDERER_CLASSES` setting.
+
+Default: `'multipart'`
+
+#### TEST_REQUEST_RENDERER_CLASSES
+
+The renderer classes that are supported when building test requests.
+
+The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')`
+
+Default:
+
+ (
+ 'rest_framework.renderers.MultiPartRenderer',
+ 'rest_framework.renderers.JSONRenderer'
+ )
+
+---
+
## Browser overrides
*The following settings provide URL or form-based overrides of the default browser behavior.*
@@ -247,6 +274,40 @@ Default: `['iso-8601']`
---
+## View names and descriptions
+
+**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.**
+
+#### VIEW_NAME_FUNCTION
+
+A string representing the function that should be used when generating view names.
+
+This should be a function with the following signature:
+
+ view_name(cls, suffix=None)
+
+* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
+* `suffix`: The optional suffix used when differentiating individual views in a viewset.
+
+Default: `'rest_framework.views.get_view_name'`
+
+#### VIEW_DESCRIPTION_FUNCTION
+
+A string representing the function that should be used when generating view descriptions.
+
+This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API.
+
+This should be a function with the following signature:
+
+ view_description(cls, html=False)
+
+* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
+* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
+
+Default: `'rest_framework.views.get_view_description'`
+
+---
+
## Miscellaneous settings
#### FORMAT_SUFFIX_KWARG
diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md
new file mode 100644
index 00000000..92f8d54a
--- /dev/null
+++ b/docs/api-guide/testing.md
@@ -0,0 +1,257 @@
+<a class="github" href="test.py"></a>
+
+# Testing
+
+> Code without tests is broken as designed
+>
+> &mdash; [Jacob Kaplan-Moss][cite]
+
+REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
+
+# APIRequestFactory
+
+Extends [Django's existing `RequestFactory` class][requestfactory].
+
+## Creating test requests
+
+The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available.
+
+ # Using the standard RequestFactory API to create a form POST request
+ factory = APIRequestFactory()
+ request = factory.post('/notes/', {'title': 'new idea'})
+
+#### Using the `format` argument
+
+Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example:
+
+ # Create a JSON POST request
+ factory = APIRequestFactory()
+ request = factory.post('/notes/', {'title': 'new idea'}, format='json')
+
+By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`.
+
+To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
+
+#### Explicitly encoding the request body
+
+If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
+
+ request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
+
+#### PUT and PATCH with form data
+
+One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`.
+
+For example, using `APIRequestFactory`, you can make a form PUT request like so:
+
+ factory = APIRequestFactory()
+ request = factory.put('/notes/547/', {'title': 'remember to email dave'})
+
+Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself:
+
+ factory = RequestFactory()
+ data = {'title': 'remember to email dave'}
+ content = encode_multipart('BoUnDaRyStRiNg', data)
+ content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
+ request = factory.put('/notes/547/', content, content_type=content_type)
+
+## Forcing authentication
+
+When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
+
+To forcibly authenticate a request, use the `force_authenticate()` method.
+
+ factory = APIRequestFactory()
+ user = User.objects.get(username='olivia')
+ view = AccountDetail.as_view()
+
+ # Make an authenticated request to the view...
+ request = factory.get('/accounts/django-superstars/')
+ force_authenticate(request, user=user)
+ response = view(request)
+
+The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set.
+
+---
+
+**Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
+
+This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
+
+ # Request will only authenticate if `SessionAuthentication` is in use.
+ request = factory.get('/accounts/django-superstars/')
+ request.user = user
+ response = view(request)
+
+---
+
+## Forcing CSRF validation
+
+By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory.
+
+ factory = APIRequestFactory(enforce_csrf_checks=True)
+
+---
+
+**Note**: It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
+
+---
+
+# APIClient
+
+Extends [Django's existing `Client` class][client].
+
+## Making requests
+
+The `APIClient` class supports the same request interface as `APIRequestFactory`. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
+
+ 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][configuration].
+
+## Authenticating
+
+#### .login(**kwargs)
+
+The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`.
+
+ # Make all requests in the context of a logged in session.
+ client = APIClient()
+ client.login(username='lauren', password='secret')
+
+To logout, call the `logout` method as usual.
+
+ # Log out
+ client.logout()
+
+The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
+
+#### .credentials(**kwargs)
+
+The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client.
+
+ # Include an appropriate `Authorization:` header on all requests.
+ token = Token.objects.get(username='lauren')
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
+
+Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
+
+ # Stop including any credentials
+ client.credentials()
+
+The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
+
+#### .force_authenticate(user=None, token=None)
+
+Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.
+
+This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
+
+ user = User.objects.get(username='lauren')
+ client = APIClient()
+ client.force_authenticate(user=user)
+
+To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
+
+ client.force_authenticate(user=None)
+
+## CSRF validation
+
+By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client.
+
+ client = APIClient(enforce_csrf_checks=True)
+
+As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`.
+
+---
+
+# Test cases
+
+REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
+
+* `APISimpleTestCase`
+* `APITransactionTestCase`
+* `APITestCase`
+* `APILiveServerTestCase`
+
+## Example
+
+You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance.
+
+ from django.core.urlresolvers import reverse
+ from rest_framework import status
+ from rest_framework.test import APITestCase
+
+ class AccountTests(APITestCase):
+ def test_create_account(self):
+ """
+ Ensure we can create a new account object.
+ """
+ url = reverse('account-list')
+ data = {'name': 'DabApps'}
+ response = self.client.post(url, data, format='json')
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.data, data)
+
+---
+
+# Testing responses
+
+## Checking the response data
+
+When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
+
+For example, it's easier to inspect `request.data`:
+
+ response = self.client.get('/users/4/')
+ self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
+
+Instead of inspecting the result of parsing `request.content`:
+
+ response = self.client.get('/users/4/')
+ self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
+
+## Rendering responses
+
+If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response.
+
+ view = UserDetail.as_view()
+ request = factory.get('/users/4')
+ response = view(request, pk='4')
+ response.render() # Cannot access `response.content` without this.
+ self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
+
+---
+
+# Configuration
+
+## Setting the default format
+
+The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file:
+
+ REST_FRAMEWORK = {
+ ...
+ 'TEST_REQUEST_DEFAULT_FORMAT': 'json'
+ }
+
+## Setting the available formats
+
+If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting.
+
+For example, to add support for using `format='yaml'` in test requests, you might have something like this in your `settings.py` file.
+
+ REST_FRAMEWORK = {
+ ...
+ 'TEST_REQUEST_RENDERER_CLASSES': (
+ 'rest_framework.renderers.MultiPartRenderer',
+ 'rest_framework.renderers.JSONRenderer',
+ 'rest_framework.renderers.YAMLRenderer'
+ )
+ }
+
+[cite]: http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
+[client]: https://docs.djangoproject.com/en/dev/topics/testing/overview/#module-django.test.client
+[requestfactory]: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory
+[configuration]: #configuration
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index d6de85ba..56f32f58 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -12,7 +12,7 @@ As with permissions, multiple throttles may be used. Your API might have a rest
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.
+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.
@@ -44,7 +44,7 @@ You can also set the throttling policy on a per-view or per-viewset basis,
using the `APIView` class based views.
class ExampleView(APIView):
- throttle_classes = (UserThrottle,)
+ throttle_classes = (UserRateThrottle,)
def get(self, request, format=None):
content = {
@@ -55,7 +55,7 @@ using the `APIView` class based views.
Or, if you're using the `@api_view` decorator with function based views.
@api_view('GET')
- @throttle_classes(UserThrottle)
+ @throttle_classes(UserRateThrottle)
def example_view(request, format=None):
content = {
'status': 'request was permitted'
@@ -72,22 +72,22 @@ The throttle classes provided by REST framework use Django's cache backend. You
## AnonRateThrottle
-The `AnonThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
+The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
-* The `rate` property on the class, which may be provided by overriding `AnonThrottle` and setting the property.
+* The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property.
* The `DEFAULT_THROTTLE_RATES['anon']` setting.
-`AnonThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
+`AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
## UserRateThrottle
-The `UserThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
+The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
-* The `rate` property on the class, which may be provided by overriding `UserThrottle` and setting the property.
+* The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property.
* The `DEFAULT_THROTTLE_RATES['user']` setting.
An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class.
@@ -113,11 +113,11 @@ For example, multiple user throttle rates could be implemented by using the foll
}
}
-`UserThrottle` is suitable if you want simple global rate restrictions per-user.
+`UserRateThrottle` is suitable if you want simple global rate restrictions per-user.
## ScopedRateThrottle
-The `ScopedThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
+The `ScopedRateThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope".
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 37ebd55f..15581e09 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -110,7 +110,7 @@ You won't typically need to override this method.
### .finalize_response(self, request, response, \*args, **kwargs)
-Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotation.
+Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
You won't typically need to override this method.
@@ -137,11 +137,11 @@ The core of this functionality is the `api_view` decorator, which takes a list o
return Response({"message": "Hello, world!"})
-This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
+This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
## API policy decorators
-To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
+To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle
diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md
index 25d11bfb..0c68afb0 100644
--- a/docs/api-guide/viewsets.md
+++ b/docs/api-guide/viewsets.md
@@ -98,8 +98,10 @@ For example:
from django.contrib.auth.models import User
from rest_framework import viewsets
+ from rest_framework import status
from rest_framework.decorators import action
- from myapp.serializers import UserSerializer
+ from rest_framework.response import Response
+ from myapp.serializers import UserSerializer, PasswordSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
@@ -176,7 +178,7 @@ Note that you can use any of the standard attributes or method overrides provide
permission_classes = [IsAccountAdminOrReadOnly]
def get_queryset(self):
- return request.user.accounts.all()
+ return self.request.user.accounts.all()
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
@@ -205,9 +207,9 @@ You may need to provide custom `ViewSet` classes that do not have the full set o
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
- class CreateListRetrieveViewSet(mixins.CreateMixin,
- mixins.ListMixin,
- mixins.RetrieveMixin,
+ class CreateListRetrieveViewSet(mixins.CreateModelMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
"""
A viewset that provides `retrieve`, `update`, and `list` actions.