aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
authorPhilip Douglas2013-07-31 07:45:05 -0700
committerPhilip Douglas2013-07-31 07:45:05 -0700
commitc058ab36b13a6979c57760d9af2eb21ec3165e7d (patch)
tree9c352f0ebaddf18b03e45de9bf4ee3ad53377e17 /docs
parentbf8e71c455a47a53898f8239ac7dad47e5f1d53a (diff)
parent43a5f8183c90f1056bbf33bb1402e76883aeb1fd (diff)
downloaddjango-rest-framework-c058ab36b13a6979c57760d9af2eb21ec3165e7d.tar.bz2
Merge pull request #2 from tomchristie/master
Update to latest
Diffstat (limited to 'docs')
-rwxr-xr-xdocs/api-guide/authentication.md14
-rw-r--r--docs/api-guide/content-negotiation.md29
-rw-r--r--docs/api-guide/renderers.md19
-rw-r--r--docs/api-guide/serializers.md51
-rw-r--r--docs/api-guide/settings.md27
-rw-r--r--docs/api-guide/testing.md257
-rw-r--r--docs/api-guide/throttling.md20
-rw-r--r--docs/api-guide/views.md4
-rw-r--r--docs/api-guide/viewsets.md12
-rw-r--r--docs/img/autocomplete.pngbin0 -> 58140 bytes
-rw-r--r--docs/topics/ajax-csrf-cors.md2
-rw-r--r--docs/topics/browsable-api.md45
-rw-r--r--docs/topics/credits.md14
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md2
14 files changed, 466 insertions, 30 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/renderers.md b/docs/api-guide/renderers.md
index b627c930..b434efe9 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -217,6 +217,24 @@ 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
@@ -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/serializers.md b/docs/api-guide/serializers.md
index f8761cb2..a1f0853e 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`.
@@ -423,6 +429,49 @@ 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
+
+Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
+
+Modifying the `fields` argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.
+
+### Example
+
+For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:
+
+ class DynamicFieldsModelSerializer(serializers.ModelSerializer):
+ """
+ A ModelSerializer that takes an additional `fields` argument that
+ controls which fields should be displayed.
+ """
+
+ def __init__(self, *args, **kwargs):
+ # Don't pass the 'fields' arg up to the superclass
+ fields = kwargs.pop('fields', None)
+
+ # Instatiate the superclass normally
+ super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
+
+ if fields:
+ # Drop any fields that are not specified in the `fields` argument.
+ allowed = set(fields)
+ existing = set(self.fields.keys())
+ for field_name in existing - allowed:
+ self.fields.pop(field_name)
+
+This would then allow you to do the following:
+
+ >>> class UserSerializer(DynamicFieldsModelSerializer):
+ >>> class Meta:
+ >>> model = User
+ >>> fields = ('id', 'username', 'email')
+ >>>
+ >>> print UserSerializer(user)
+ {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
+ >>>
+ >>> print UserSerializer(user, fields=('id', 'email'))
+ {'id': 2, 'email': 'jon@example.com'}
+
## Customising the default fields
The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
@@ -457,7 +506,7 @@ Note that the `model_field` argument will be `None` for reverse relationships.
Returns the field instance that should be used for non-relational, non-pk fields.
-## Example
+### Example
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 4a5164c9..7b114983 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -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 contructing 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.*
diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md
new file mode 100644
index 00000000..40b07763
--- /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 explictly 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..683222d1 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -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.
diff --git a/docs/img/autocomplete.png b/docs/img/autocomplete.png
new file mode 100644
index 00000000..29075b25
--- /dev/null
+++ b/docs/img/autocomplete.png
Binary files differ
diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md
index 4566f38b..0555b84d 100644
--- a/docs/topics/ajax-csrf-cors.md
+++ b/docs/topics/ajax-csrf-cors.md
@@ -23,7 +23,7 @@ To guard against these type of attacks, you need to do two things:
If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
-The Django documentation describes how to [include CSRF tokens in AJAX requests][csrf-ajax].
+In order to make AJAX requests, you need to include CSRF token in the HTTP header, as [described in the Django documentation][csrf-ajax].
## CORS
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
index 85f1faff..b2c78f3c 100644
--- a/docs/topics/browsable-api.md
+++ b/docs/topics/browsable-api.md
@@ -24,8 +24,8 @@ To customize the default style, create a template called `rest_framework/api.htm
**templates/rest_framework/api.html**
{% extends "rest_framework/base.html" %}
-
- ... # Override blocks with required customizations
+
+ ... # Override blocks with required customizations
### Overriding the default theme
@@ -75,6 +75,7 @@ All of the blocks available in the browsable API base template that can be used
* `branding` - Branding section of the navbar, see [Bootstrap components][bcomponentsnav].
* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
* `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned).
+* `script` - JavaScript files for the page.
* `style` - CSS stylesheets for the page.
* `title` - Title of the page.
* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use `{{ block.super }}` to preserve the authentication links.
@@ -89,14 +90,14 @@ The browsable API makes use of the Bootstrap tooltips component. Any element wi
### Login Template
-To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/base_login.html`.
+To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/login_base.html`.
You can add your site name or branding by including the branding block:
{% block branding %}
<h3 style="margin: 0 0 20px;">My Site Name</h3>
{% endblock %}
-
+
You can also customize the style by adding the `bootstrap_theme` or `style` block similar to `api.html`.
### Advanced Customization
@@ -125,6 +126,37 @@ The context that's available to the template:
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
+#### Autocompletion
+
+When a `ChoiceField` has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.
+
+There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light]. To setup `django-autocomplete-light`, follow the [installation documentation][django-autocomplete-light-install], add the the following to the `api.html` template:
+
+ {% block script %}
+ {{ block.super }}
+ {% include 'autocomplete_light/static.html' %}
+ {% endblock %}
+
+You can now add the `autocomplete_light.ChoiceWidget` widget to the serializer field.
+
+ import autocomplete_light
+
+ class BookSerializer(serializers.ModelSerializer):
+ author = serializers.ChoiceField(
+ widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
+ )
+
+ class Meta:
+ model = Book
+
+---
+
+![Autocomplete][autocomplete-image]
+
+*Screenshot of the autocomplete-light widget*
+
+---
+
[cite]: http://en.wikiquote.org/wiki/Alfred_North_Whitehead
[drfreverse]: ../api-guide/reverse.md
[ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/
@@ -136,4 +168,7 @@ For more advanced customization, such as not having a Bootstrap basis or tighter
[bswatch]: http://bootswatch.com/
[bcomponents]: http://twitter.github.com/bootstrap/components.html
[bcomponentsnav]: http://twitter.github.com/bootstrap/components.html#navbar
-
+[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
+[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
+[django-autocomplete-light-install]: http://django-autocomplete-light.readthedocs.org/en/latest/#install
+[autocomplete-image]: ../img/autocomplete.png
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index e6fb9134..4cc7f34b 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -145,6 +145,13 @@ The following people have helped make REST framework great.
* Philip Douglas - [freakydug]
* Igor Kalat - [trwired]
* Rudolf Olah - [omouse]
+* Gertjan Oude Lohuis - [gertjanol]
+* Matthias Jacob - [cyroxx]
+* Pavel Zinovkin - [pzinovkin]
+* Will Kahn-Greene - [willkg]
+* Kevin Brown - [kevin-brown]
+* Rodrigo Martell - [coderigo]
+* James Rutherford - [jimr]
Many thanks to everyone who's contributed to the project.
@@ -326,3 +333,10 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[freakydug]: https://github.com/freakydug
[trwired]: https://github.com/trwired
[omouse]: https://github.com/omouse
+[gertjanol]: https://github.com/gertjanol
+[cyroxx]: https://github.com/cyroxx
+[pzinovkin]: https://github.com/pzinovkin
+[coderigo]: https://github.com/coderigo
+[willkg]: https://github.com/willkg
+[kevin-brown]: https://github.com/kevin-brown
+[jimr]: https://github.com/jimr
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 2e013a94..2cf44bf9 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -80,7 +80,7 @@ We can easily re-write our existing serializers to use hyperlinking.
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
- model = models.Snippet
+ model = Snippet
fields = ('url', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style')