diff --git a/.travis.yml b/.travis.yml index 5f0724108..205feef92 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,8 +14,11 @@ env: install: - pip install $DJANGO - pip install defusedxml==0.3 - - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-filter==0.5.4 --use-mirrors; fi" - - "if [[ ${TRAVIS_PYTHON_VERSION::1} == '3' ]]; then pip install https://github.com/alex/django-filter/tarball/master; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install oauth2==1.5.211 --use-mirrors; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth-plus==2.0 --use-mirrors; fi" + - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth2-provider==0.2.3 --use-mirrors; fi" + - "if [[ ${DJANGO::11} == 'django==1.3' ]]; then pip install django-filter==0.5.4 --use-mirrors; fi" + - "if [[ ${DJANGO::11} != 'django==1.3' ]]; then pip install django-filter==0.6a1 --use-mirrors; fi" - export PYTHONPATH=. script: diff --git a/MANIFEST.in b/MANIFEST.in index 00e450866..15c4d0b08 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,2 @@ recursive-include rest_framework/static *.js *.css *.png -recursive-include rest_framework/templates *.txt *.html +recursive-include rest_framework/templates *.html diff --git a/README.md b/README.md index afe3132df..5d1631d49 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,39 @@ # Django REST framework -**A toolkit for building well-connected, self-describing web APIs.** - -**Author:** Tom Christie. [Follow me on Twitter][twitter]. - -**Support:** [REST framework group][group], or `#restframework` on freenode IRC. +**Awesome web-browseable Web APIs.** [![build-status-image]][travis] ---- - -**Full documentation for REST framework is available on [http://django-rest-framework.org][docs].** - ---- +**Note**: Full documentation for the project is available at [http://django-rest-framework.org][docs]. # Overview -Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. +Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs. -Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. +Some reasons you might want to use REST framework: -If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. +* The Web browseable API is a huge useability win for your developers. +* Authentication policies including OAuth1a and OAuth2 out of the box. +* Serialization that supports both ORM and non-ORM data sources. +* Customizable all the way down - just use regular function-based views if you don't need the more powerful features. +* Extensive documentation, and great community support. -There is also a sandbox API you can use for testing purposes, [available here][sandbox]. +There is a live example API for testing purposes, [available here][sandbox]. + +**Below**: *Screenshot from the browseable API* + +![Screenshot][image] # Requirements * Python (2.6.5+, 2.7, 3.2, 3.3) * Django (1.3, 1.4, 1.5) -**Optional:** - -* [Markdown][markdown] - Markdown support for the self describing API. -* [PyYAML][pyyaml] - YAML content type support. -* [defusedxml][defusedxml] - XML content-type support. -* [django-filter][django-filter] - Filtering support. - # Installation -Install using `pip`, including any optional packages you want... +Install using `pip`... pip install djangorestframework - pip install markdown # Markdown support for the browseable API. - pip install pyyaml # YAML content-type support. - pip install defusedxml # XML content-type support. - pip install django-filter # Filtering support - -...or clone the project from github. - - git clone git@github.com:tomchristie/django-rest-framework.git - cd django-rest-framework - pip install -r requirements.txt - pip install -r optionals.txt Add `'rest_framework'` to your `INSTALLED_APPS` setting. @@ -60,24 +42,65 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting. 'rest_framework', ) -If you're intending to use the browseable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. +# Example +Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups. + +Here's our project's root `urls.py` module: + + from django.conf.urls.defaults import url, patterns, include + from django.contrib.auth.models import User, Group + from rest_framework import viewsets, routers + + # ViewSets define the view behavior. + class UserViewSet(viewsets.ModelViewSet): + model = User + + class GroupViewSet(viewsets.ModelViewSet): + model = Group + + + # Routers provide an easy way of automatically determining the URL conf + router = routers.DefaultRouter() + router.register(r'users', UserViewSet) + router.register(r'groups', GroupViewSet) + + + # Wire up our API using automatic URL routing. + # Additionally, we include login URLs for the browseable API. urlpatterns = patterns('', - ... + url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) -Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. +We'd also like to configure a couple of settings for our API. -# Development +Add the following to your `settings.py` module: -To build the docs. + REST_FRAMEWORK = { + # Use hyperlinked styles by default. + # Only used if the `serializer_class` attribute is not set on a view. + 'DEFAULT_MODEL_SERIALIZER_CLASS': + 'rest_framework.serializers.HyperlinkedModelSerializer', - ./mkdocs.py + # Use Django's standard `django.contrib.auth` permissions, + # or allow read-only access for unauthenticated users. + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' + ] + } -To run the tests. +Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS` setting. - ./rest_framework/runtests/runtests.py +That's it, we're done! + +# Documentation & Support + +Full documentation for the project is available at [http://django-rest-framework.org][docs]. + +For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC. + +You may also want to [follow the author on Twitter][twitter]. # License @@ -112,6 +135,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [sandbox]: http://restframework.herokuapp.com/ [rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion +[image]: http://django-rest-framework.org/img/quickstart.png + +[tox]: http://testrun.org/tox/latest/ + +[tehjones]: https://twitter.com/tehjones/status/294986071979196416 +[wlonk]: https://twitter.com/wlonk/status/261689665952833536 +[laserllama]: https://twitter.com/laserllama/status/328688333750407168 [docs]: http://django-rest-framework.org/ [urlobject]: https://github.com/zacharyvoase/urlobject diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md old mode 100644 new mode 100755 index fae86386d..c2f739018 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -43,7 +43,8 @@ The default authentication schemes may be set globally, using the `DEFAULT_AUTHE ) } -You can also set the authentication scheme on a per-view basis, using the `APIView` class based views. +You can also set the authentication scheme on a per-view or per-viewset basis, +using the `APIView` class based views. class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) @@ -107,13 +108,20 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 WWW-Authenticate: Basic realm="api" -**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. +**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. ## TokenAuthentication -This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. +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' + ) + +Make sure to run `manage.py syncdb` after changing your settings. You'll also need to create tokens for your users. @@ -135,10 +143,18 @@ 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. +The `curl` command line tool may be useful for testing token authenticated APIs. For example: + + curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' --- +**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`. + +--- + +#### Generating Tokens + 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 +170,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 +184,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. @@ -182,6 +214,97 @@ Unauthenticated responses that are denied permission will result in an `HTTP 403 If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details. +## OAuthAuthentication + +This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests. + +This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`: + + INSTALLED_APPS = ( + ... + `oauth_provider`, + ) + +Don't forget to run `syncdb` once you've added the package. + + python manage.py syncdb + +#### Getting started with django-oauth-plus + +The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens. + +The `django-oauth-plus` package provides simple foundation for classic 'three-legged' oauth flow. Please refer to [the documentation][django-oauth-plus] for more details. + +## OAuth2Authentication + +This authentication uses [OAuth 2.0][rfc6749] authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection. + +This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`: + + INSTALLED_APPS = ( + ... + 'provider', + 'provider.oauth2', + ) + +You must also include the following in your root `urls.py` module: + + url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')), + +Note that the `namespace='oauth2'` argument is required. + +Finally, sync your database. + + python manage.py syncdb + python manage.py migrate + +--- + +**Note:** If you use `OAuth2Authentication` in production you must ensure that your API is only available over `https`. + +--- + +#### Getting started with django-oauth2-provider + +The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients. + +The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs]. + +To get started: + +##### 1. Create a client + +You can create a client, either through the shell, or by using the Django admin. + +Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you. + +##### 2. Request an access token + +To request an access token, submit a `POST` request to the url `/oauth2/access_token` with the following fields: + +* `client_id` the client id you've just configured at the previous step. +* `client_secret` again configured at the previous step. +* `username` the username with which you want to log in. +* `password` well, that speaks for itself. + +You can use the command line to test that your local configuration is working: + + curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/ + +You should get a response that looks something like this: + + {"access_token": "", "scope": "read", "expires_in": 86399, "refresh_token": ""} + +##### 3. Access the API + +The only thing needed to make the `OAuth2Authentication` class work is to insert the `access_token` you've received in the `Authorization` request header. + +The command line to test the authentication looks like: + + curl -H "Authorization: Bearer " http://localhost:8000/api/ + +--- + # Custom authentication To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. @@ -233,5 +356,12 @@ 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 +[oauth-1.0a]: http://oauth.net/core/1.0a +[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus +[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider +[django-oauth2-provider-docs]: https://django-oauth2-provider.readthedocs.org/en/latest/ +[rfc6749]: http://tools.ietf.org/html/rfc6749 diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index d7f9197f1..e117c370c 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] @@ -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,45 @@ If you want to override this behavior, you'll need to declare the `DateTimeField class Meta: model = Comment +Note that by default, datetime representations are deteremined by the renderer in use, although this can be explicitly overridden as detailed below. + +In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`. + +**Signature:** `DateTimeField(format=None, input_formats=None)` + +* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `datetime` objects should be returned by `to_native`. In this case the datetime encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. + +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.000000Z'`) + +## 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, this defaults to `None`, which indicates that python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. + +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, this defaults to `None`, which indicates that python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. + +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. @@ -221,6 +248,12 @@ A floating point representation. Corresponds to `django.db.models.fields.FloatField`. +## DecimalField + +A decimal representation. + +Corresponds to `django.db.models.fields.DecimalField`. + ## FileField A file representation. Performs Django's standard FileField validation. @@ -250,5 +283,51 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. --- +# Custom fields + +If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects. + +The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation. + +## Examples + +Let's look at an example of serializing a class that represents an RGB color value: + + class Color(object): + """ + A color represented in the RGB colorspace. + """ + def __init__(self, red, green, blue): + assert(red >= 0 and green >= 0 and blue >= 0) + assert(red < 256 and green < 256 and blue < 256) + self.red, self.green, self.blue = red, green, blue + + class ColourField(serializers.WritableField): + """ + Color objects are serialized into "rgb(#, #, #)" notation. + """ + def to_native(self, obj): + return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) + + def from_native(self, data): + data = data.strip('rgb(').rstrip(')') + red, green, blue = [int(col) for col in data.split(',')] + return Color(red, green, blue) + + +By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`. + +As an example, let's create a field that can be used represent the class name of the object being serialized: + + class ClassNameField(serializers.Field): + def field_to_native(self, obj, field_name): + """ + Serialize the object's class name. + """ + return obj.__class__ + [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 +[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 +[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/filtering.md b/docs/api-guide/filtering.md index 53ea7cbcc..a710ad7dd 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -8,7 +8,7 @@ The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. -The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method. +The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways. @@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`. For example: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -44,7 +43,6 @@ For example if your URL config contained an entry like this: You could then write a view that returned a purchase queryset filtered by the username portion of the URL: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -62,7 +60,6 @@ A final example of filtering the initial queryset would be to determine the init We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -80,65 +77,31 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ # Generic Filtering -As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters. +As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters. -REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package. +## Setting filter backends -To use REST framework's filtering backend, first install `django-filter`. - - pip install django-filter - -You must also set the filter backend to `DjangoFilterBackend` in your settings: +The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example. REST_FRAMEWORK = { - 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend' + 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) } +You can also set the authentication policy on a per-view, or per-viewset basis, +using the `GenericAPIView` class based views. -## Specifying filter fields + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.DjangoFilterBackend,) -If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against. +## Filtering and object lookups - class ProductList(generics.ListAPIView): - model = Product - serializer_class = ProductSerializer - filter_fields = ('category', 'in_stock') +Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. -This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as: +For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: - http://example.com/api/products?category=clothing&in_stock=True - -## Specifying a FilterSet - -For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example: - - class ProductFilter(django_filters.FilterSet): - min_price = django_filters.NumberFilter(lookup_type='gte') - max_price = django_filters.NumberFilter(lookup_type='lte') - class Meta: - model = Product - fields = ['category', 'in_stock', 'min_price', 'max_price'] - - class ProductList(generics.ListAPIView): - model = Product - serializer_class = ProductSerializer - filter_class = ProductFilter - -Which will allow you to make requests such as: - - http://example.com/api/products?category=clothing&max_price=10.00 - -For more details on using filter sets see the [django-filter documentation][django-filter-docs]. - ---- - -**Hints & Tips** - -* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting. -* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) -* `django-filter` supports filtering across relationships, using Django's double-underscore syntax. - ---- + http://example.com/api/products/4675/?category=clothing&max_price=10.00 ## Overriding the initial queryset @@ -156,6 +119,127 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering def get_queryset(self): user = self.request.user return user.purchase_set.all() + +--- + +# API Guide + +## DjangoFilterBackend + +The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter]. + +To use REST framework's `DjangoFilterBackend`, first install `django-filter`. + + pip install django-filter + + +#### Specifying filter fields + +If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against. + + class ProductList(generics.ListAPIView): + queryset = Product.objects.all() + serializer_class = ProductSerializer + filter_fields = ('category', 'in_stock') + +This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as: + + http://example.com/api/products?category=clothing&in_stock=True + +#### Specifying a FilterSet + +For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example: + + class ProductFilter(django_filters.FilterSet): + min_price = django_filters.NumberFilter(lookup_type='gte') + max_price = django_filters.NumberFilter(lookup_type='lte') + class Meta: + model = Product + fields = ['category', 'in_stock', 'min_price', 'max_price'] + + class ProductList(generics.ListAPIView): + queryset = Product.objects.all() + serializer_class = ProductSerializer + filter_class = ProductFilter + +Which will allow you to make requests such as: + + http://example.com/api/products?category=clothing&max_price=10.00 + +For more details on using filter sets see the [django-filter documentation][django-filter-docs]. + +--- + +**Hints & Tips** + +* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting. +* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) +* `django-filter` supports filtering across relationships, using Django's double-underscore syntax. + +--- + +## SearchFilter + +The `SearchFilterBackend` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin]. + +The `SearchFilterBackend` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`. + + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.SearchFilter,) + search_fields = ('username', 'email') + +This will allow the client to filter the items in the list by making queries such as: + + http://example.com/api/users?search=russell + +You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: + + search_fields = ('username', 'email', 'profile__profession') + +By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. + +The search behavior may be restricted by prepending various characters to the `search_fields`. + +* '^' Starts-with search. +* '=' Exact matches. +* '@' Full-text search. (Currently only supported Django's MySQL backend.) + +For example: + + search_fields = ('=username', '=email') + +For more details, see the [Django documentation][search-django-admin]. + +--- + +## OrderingFilter + +The `OrderingFilter` class supports simple query parameter controlled ordering of results. To specify the result order, set a query parameter named `'order'` to the required field name. For example: + + http://example.com/api/users?ordering=username + +The client may also specify reverse orderings by prefixing the field name with '-', like so: + + http://example.com/api/users?ordering=-username + +Multiple orderings may also be specified: + + http://example.com/api/users?ordering=account,username + +If an `ordering` attribute is set on the view, this will be used as the default ordering. + +Typicaly you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. + + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.OrderingFilter,) + ordering = ('username',) + +The `ordering` attribute may be either a string or a list/tuple of strings. + --- # Custom generic filtering @@ -164,15 +248,23 @@ You can also provide your own generic filtering backend, or write an installable To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. -To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. +As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user. -For example: +## Example - REST_FRAMEWORK = { - 'FILTER_BACKEND': 'custom_filters.CustomFilterBackend' - } +For example, you might need to restrict users to only being able to see objects they created. + + class IsOwnerFilterBackend(filters.BaseFilterBackend): + """ + Filter that only allows users to see their own objects. + """ + def filter_queryset(self, request, queryset, view): + return queryset.filter(owner=request.user) + +We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API. [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter [django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html -[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py \ No newline at end of file +[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py +[search-django-admin]: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md old mode 100644 new mode 100755 index 20f1be63a..1a060a324 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -18,7 +18,7 @@ If the generic views don't suit the needs of your API, you can drop down to usin Typically when using the generic views, you'll override the view, and set several class attributes. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) paginate_by = 100 @@ -26,17 +26,16 @@ Typically when using the generic views, you'll override the view, and set severa For more complex cases you might also want to override various methods on the view class. For example. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) - def get_paginate_by(self, queryset): + def get_paginate_by(self): """ Use smaller pagination for HTML representations. """ - page_size_param = self.request.QUERY_PARAMS.get('page_size') - if page_size_param: - return int(page_size_param) + if self.request.accepted_renderer.format == 'html': + return 20 return 100 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. @@ -47,134 +46,127 @@ For very simple cases you might want to pass through any class attributes using # API Reference -The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. - -## CreateAPIView - -Used for **create-only** endpoints. - -Provides `post` method handlers. - -Extends: [GenericAPIView], [CreateModelMixin] - -## ListAPIView - -Used for **read-only** endpoints to represent a **collection of model instances**. - -Provides a `get` method handler. - -Extends: [MultipleObjectAPIView], [ListModelMixin] - -## RetrieveAPIView - -Used for **read-only** endpoints to represent a **single model instance**. - -Provides a `get` method handler. - -Extends: [SingleObjectAPIView], [RetrieveModelMixin] - -## DestroyAPIView - -Used for **delete-only** endpoints for a **single model instance**. - -Provides a `delete` method handler. - -Extends: [SingleObjectAPIView], [DestroyModelMixin] - -## UpdateAPIView - -Used for **update-only** endpoints for a **single model instance**. - -Provides `put` and `patch` method handlers. - -Extends: [SingleObjectAPIView], [UpdateModelMixin] - -## ListCreateAPIView - -Used for **read-write** endpoints to represent a **collection of model instances**. - -Provides `get` and `post` method handlers. - -Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin] - -## RetrieveUpdateAPIView - -Used for **read or update** endpoints to represent a **single model instance**. - -Provides `get`, `put` and `patch` method handlers. - -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin] - -## RetrieveDestroyAPIView - -Used for **read or delete** endpoints to represent a **single model instance**. - -Provides `get` and `delete` method handlers. - -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin] - -## RetrieveUpdateDestroyAPIView - -Used for **read-write-delete** endpoints to represent a **single model instance**. - -Provides `get`, `put`, `patch` and `delete` method handlers. - -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] - ---- - -# Base views - -Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes. - ## GenericAPIView -Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets. +This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views. -**Methods**: +Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes. + +### Attributes + +**Basic settings**: + +The following attributes control the basic view behavior. + +* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. +* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. +* `lookup_field` - The field that should be used to lookup individual model instances. Defaults to `'pk'`. The URL conf should include a keyword argument corresponding to this value. More complex lookup styles can be supported by overriding the `get_object()` method. + +**Shortcuts**: + +* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. + +**Pagination**: + +The following attibutes are used to control pagination when used with list views. + +* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. +* `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 unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. +* `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting. +* `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`. + +**Filtering**: + +* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting. + +### Methods + +**Base methods**: + +#### `get_queryset(self)` + +Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute, or the default queryset for the model if the `model` shortcut is being used. + +May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request. + +For example: + + def get_queryset(self): + return self.user.accounts.all() + +#### `get_object(self)` + +Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. + +May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg. + +For example: + + def get_object(self): + queryset = self.get_queryset() + filter = {} + for field in self.multiple_lookup_fields: + filter[field] = self.kwargs[field] + return get_object_or_404(queryset, **filter) + +#### `get_serializer_class(self)` + +Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute, or dynamically generating a serializer class if the `model` shortcut is being used. + +May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of uesr. + +For example: + + def get_serializer_class(self): + if self.request.user.is_staff: + return FullAccountSerializer + return BasicAccountSerializer + +#### `get_paginate_by(self)` + +Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set. + +You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response. + +For example: + + def get_paginate_by(self): + self.request.accepted_renderer.format == 'html': + return 20 + return 100 + +**Save hooks**: + +The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes. -* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. -* `get_serializer_class(self)` - Returns the class that should be used for the serializer. -* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. * `pre_save(self, obj)` - A hook that is called before saving an object. * `post_save(self, obj, created=False)` - A hook that is called after saving an object. +The `pre_save` method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. -**Attributes**: + def pre_save(self, obj): + """ + Set the object's owner, based on the incoming request. + """ + obj.owner = self.request.user -* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required. -* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class. +Remember that the `pre_save()` method is not called by `GenericAPIView` itself, but it is called by `create()` and `update()` methods on the `CreateModelMixin` and `UpdateModelMixin` classes. -## MultipleObjectAPIView +**Other methods**: -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin]. +You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. -**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`. -* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. -* `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 unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. - -## SingleObjectAPIView - -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin]. - -**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`. -* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+] -* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+] -* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`. +* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. +* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. +* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data. +* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. --- # Mixins -The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour. +The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior. ## ListModelMixin @@ -182,9 +174,7 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. -If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. - -Should be mixed in with [MultipleObjectAPIView]. +If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. ## CreateModelMixin @@ -194,47 +184,157 @@ If an object is created this returns a `201 Created` response, with a serialized If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. -Should be mixed in with any [GenericAPIView]. - ## RetrieveModelMixin Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. -If an object can be retrieve this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`. - -Should be mixed in with [SingleObjectAPIView]. +If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`. ## UpdateModelMixin Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. +Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. + If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. -A boolean `partial` keyword argument may be supplied to the `.update()` method. If `partial` is set to `True`, all fields for the update will be optional. This allows support for HTTP `PATCH` requests. - -Should be mixed in with [SingleObjectAPIView]. - ## DestroyModelMixin Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`. -Should be mixed in with [SingleObjectAPIView]. +--- + +# Concrete View Classes + +The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. + +## CreateAPIView + +Used for **create-only** endpoints. + +Provides a `post` method handler. + +Extends: [GenericAPIView], [CreateModelMixin] + +## ListAPIView + +Used for **read-only** endpoints to represent a **collection of model instances**. + +Provides a `get` method handler. + +Extends: [GenericAPIView], [ListModelMixin] + +## RetrieveAPIView + +Used for **read-only** endpoints to represent a **single model instance**. + +Provides a `get` method handler. + +Extends: [GenericAPIView], [RetrieveModelMixin] + +## DestroyAPIView + +Used for **delete-only** endpoints for a **single model instance**. + +Provides a `delete` method handler. + +Extends: [GenericAPIView], [DestroyModelMixin] + +## UpdateAPIView + +Used for **update-only** endpoints for a **single model instance**. + +Provides `put` and `patch` method handlers. + +Extends: [GenericAPIView], [UpdateModelMixin] + +## ListCreateAPIView + +Used for **read-write** endpoints to represent a **collection of model instances**. + +Provides `get` and `post` method handlers. + +Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin] + +## RetrieveUpdateAPIView + +Used for **read or update** endpoints to represent a **single model instance**. + +Provides `get`, `put` and `patch` method handlers. + +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin] + +## RetrieveDestroyAPIView + +Used for **read or delete** endpoints to represent a **single model instance**. + +Provides `get` and `delete` method handlers. + +Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin] + +## RetrieveUpdateDestroyAPIView + +Used for **read-write-delete** endpoints to represent a **single model instance**. + +Provides `get`, `put`, `patch` and `delete` method handlers. + +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] + +--- + +# Customizing the generic views + +Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed. + +## Creating custom mixins + +For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following: + + class MultipleFieldLookupMixin(object): + """ + Apply this mixin to any view or viewset to get multiple field filtering + based on a `lookup_fields` attribute, instead of the default single field filtering. + """ + def get_object(self): + queryset = self.get_queryset() # Get the base queryset + queryset = self.filter_queryset(queryset) # Apply any filter backends + filter = {} + for field in self.lookup_fields: + filter[field] = self.kwargs[field] + return get_object_or_404(queryset, **filter) # Lookup the object + +You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior. + + class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer + lookup_fields = ('account', 'username') + +Using custom mixins is a good option if you have custom behavior that needs to be used + +## Creating custom base classes + +If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example: + + class BaseRetrieveView(MultipleFieldLookupMixin, + generics.RetrieveAPIView): + pass + + class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, + generics.RetrieveUpdateDestroyAPIView): + pass + +Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views -[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/ -[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/ -[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/ -[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/ [GenericAPIView]: #genericapiview -[SingleObjectAPIView]: #singleobjectapiview -[MultipleObjectAPIView]: #multipleobjectapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin [RetrieveModelMixin]: #retrievemodelmixin diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 13d4760a3..912ce41bd 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -93,7 +93,8 @@ The default pagination style may be set globally, using the `DEFAULT_PAGINATION_ You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. class PaginatedListView(ListAPIView): - model = ExampleModel + queryset = ExampleModel.objects.all() + serializer_class = ExampleModelSerializer paginate_by = 10 paginate_by_param = 'page_size' diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index a28304922..5bd79a317 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -34,7 +34,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE ) } -You can also set the renderers used for an individual view, using the `APIView` class based views. +You can also set the renderers used for an individual view, or viewset, +using the `APIView` class based views. class ExampleView(APIView): """ @@ -101,6 +102,33 @@ You will typically want to use both `FormParser` and `MultiPartParser` together **.media_type**: `multipart/form-data` +## FileUploadParser + +Parses raw file upload content. The `request.DATA` property will be an empty `QueryDict`, and `request.FILES` will be a dictionary with a single key `'file'` containing the uploaded file. + +If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`. + +**.media_type**: `*/*` + +##### Notes: + +* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead. +* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view. +* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details. + +##### Basic usage example: + + class FileUploadView(views.APIView): + parser_classes = (FileUploadParser,) + + def put(self, request, filename, format=None): + file_obj = request.FILES['file'] + # ... + # do some staff with uploaded file + # ... + return Response(status=204) + + --- # Custom parsers @@ -144,35 +172,6 @@ The following is an example plaintext parser that will populate the `request.DAT """ return stream.read() -## Uploading file content - -If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property. - -For example: - - class SimpleFileUploadParser(BaseParser): - """ - A naive raw file upload parser. - """ - media_type = '*/*' # Accept anything - - def parse(self, stream, media_type=None, parser_context=None): - content = stream.read() - name = 'example.dat' - content_type = 'application/octet-stream' - size = len(content) - charset = 'utf-8' - - # Write a temporary file based on the request content - temp = tempfile.NamedTemporaryFile(delete=False) - temp.write(content) - uploaded = UploadedFile(temp, name, content_type, size, charset) - - # Return the uploaded file - data = {} - files = {name: uploaded} - return DataAndFiles(data, files) - --- # Third party packages @@ -185,6 +184,7 @@ The following third party packages are also available. [jquery-ajax]: http://api.jquery.com/jQuery.ajax/ [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion +[upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza -[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack \ No newline at end of file +[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 2db6ce1e3..db0d4b26a 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -21,7 +21,12 @@ If any permission check fails an `exceptions.PermissionDenied` exception will be REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. -Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. +Object level permissions are run by REST framework's generic views when `.get_object()` is called. +As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. + +If you're writing your own views and want to enforce object level permissions, +you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. +This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions. ## Setting the permission policy @@ -39,7 +44,8 @@ If not specified, this setting defaults to allowing unrestricted access: 'rest_framework.permissions.AllowAny', ) -You can also set the authentication policy on a per-view basis, using the `APIView` class based views. +You can also set the authentication policy on a per-view, or per-viewset basis, +using the `APIView` class based views. class ExampleView(APIView): permission_classes = (IsAuthenticated,) @@ -90,16 +96,35 @@ This permission is suitable if you want to your API to allow read permissions to ## DjangoModelPermissions -This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user has the relevant model permissions assigned. +This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. * `POST` requests require the user to have the `add` permission on the model. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model. * `DELETE` requests require the user to have the `delete` permission on the model. - + The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. +## DjangoModelPermissionsOrAnonReadOnly + +Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. + +## TokenHasReadWriteScope + +This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide. + +Requests with a safe methods of `GET`, `OPTIONS` or `HEAD` will be allowed if the authenticated token has read permission. + +Requests for `POST`, `PUT`, `PATCH` and `DELETE` will be allowed if the authenticated token has write permission. + +This permission class relies on the implementations of the [django-oauth-plus][django-oauth-plus] and [django-oauth2-provider][django-oauth2-provider] libraries, which both provide limited support for controlling the scope of access tokens: + +* `django-oauth-plus`: Tokens are associated with a `Resource` class which has a `name`, `url` and `is_readonly` properties. +* `django-oauth2-provider`: Tokens are associated with a bitwise `scope` attribute, that defaults to providing bitwise values for `read` and/or `write`. + +If you require more advanced scoping for your API, such as restricting tokens to accessing a subset of functionality of your API then you will need to provide a custom permission class. See the source of the `django-oauth-plus` or `django-oauth2-provider` package for more details on scoping token access. + --- # Custom permissions @@ -168,5 +193,7 @@ Also note that the generic views will only check the object-level permissions fo [throttling]: throttling.md [contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions [guardian]: https://github.com/lukaszb/django-guardian +[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus +[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider [2.2-announcement]: ../topics/2.2-announcement.md [filtering]: filtering.md diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 623fe1a90..155c89de3 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -123,9 +123,9 @@ Would serialize to a representation like this: 'album_name': 'Graceland', 'artist': 'Paul Simon' 'tracks': [ - 'http://www.example.com/api/tracks/45', - 'http://www.example.com/api/tracks/46', - 'http://www.example.com/api/tracks/47', + 'http://www.example.com/api/tracks/45/', + 'http://www.example.com/api/tracks/46/', + 'http://www.example.com/api/tracks/47/', ... ] } @@ -138,9 +138,7 @@ By default this field is read-write, although you can change this behavior using * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. -* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. -* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ## SlugRelatedField @@ -196,17 +194,15 @@ Would serialize to a representation like this: { 'album_name': 'The Eraser', 'artist': 'Thom Yorke' - 'track_listing': 'http://www.example.com/api/track_list/12', + 'track_listing': 'http://www.example.com/api/track_list/12/', } - + This field is always read-only. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. **required**. -* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. -* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. -* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. --- @@ -291,32 +287,23 @@ This custom field would then serialize to the following representation. ## Reverse relations -Note that reverse relationships are not automatically generated by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you cannot simply add it to the fields list. - -**The following will not work:** +Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: - fields = ('tracks', ...) - -Instead, you must explicitly add it to the serializer. For example: + fields = ('tracks', ...) - class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelatedField(many=True) - ... - -By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work. - -The best way to ensure this is typically to make sure that the relationship on the model definition has it's `related_name` argument properly set. For example: +You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') ... -Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. +If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example: class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelatedField(many=True, source='track_set') + class Meta: + fields = ('track_set', ...) See the Django documentation on [reverse relationships][reverse-relationships] for more details. @@ -394,6 +381,40 @@ Note that reverse generic keys, expressed using the `GenericRelation` field, can For more information see [the Django documentation on generic relations][generic-relations]. +## Advanced Hyperlinked fields + +If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`. + +There are two methods you'll need to override. + +#### get_url(self, obj, view_name, request, format) + +This method should return the URL that corresponds to the given object. + +May raise a `NoReverseMatch` if the `view_name` and `lookup_field` +attributes are not configured to correctly match the URL conf. + +#### get_object(self, queryset, view_name, view_args, view_kwargs) + + +This method should the object that corresponds to the matched URL conf arguments. + +May raise an `ObjectDoesNotExist` exception. + +### Example + +For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this: + + class CustomHyperlinkedField(serializers.HyperlinkedRelatedField): + def get_url(self, obj, view_name, request, format): + kwargs = {'account': obj.account, 'slug': obj.slug} + return reverse(view_name, kwargs=kwargs, request=request, format=format) + + def get_object(self, queryset, view_name, view_args, view_kwargs): + account = view_kwargs['account'] + slug = view_kwargs['slug'] + return queryset.get(account=account, slug=sug) + --- ## Deprecated APIs diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 3c8396aa1..ed733c653 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -27,7 +27,8 @@ The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CL ) } -You can also set the renderers used for an individual view, using the `APIView` class based views. +You can also set the renderers used for an individual view, or viewset, +using the `APIView` class based views. class UserCountView(APIView): """ @@ -56,7 +57,7 @@ Or, if you're using the `@api_view` decorator with function based views. It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response. -For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. +For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers]. @@ -127,7 +128,7 @@ An example of a view that uses `TemplateHTMLRenderer`: """ A view that returns a templated HTML representations of a given user. """ - model = Users + queryset = User.objects.all() renderer_classes = (TemplateHTMLRenderer,) def get(self, request, *args, **kwargs) @@ -166,7 +167,7 @@ See also: `TemplateHTMLRenderer` ## BrowsableAPIRenderer -Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. +Renders data into HTML for the Browsable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. **.media_type**: `text/html` diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md new file mode 100644 index 000000000..6588d7e51 --- /dev/null +++ b/docs/api-guide/routers.md @@ -0,0 +1,111 @@ + + +# Routers + +> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. +> +> — [Ruby on Rails Documentation][cite] + +Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. + +REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. + +## Usage + +Here's an example of a simple URL conf, that uses `DefaultRouter`. + + router = routers.SimpleRouter() + router.register(r'users', UserViewSet) + router.register(r'accounts', AccountViewSet) + urlpatterns = router.urls + +There are two mandatory arguments to the `register()` method: + +* `prefix` - The URL prefix to use for this set of routes. +* `viewset` - The viewset class. + +Optionally, you may also specify an additional argument: + +* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `model` or `queryset` attribute on the viewset, if it has one. + +The example above would generate the following URL patterns: + +* URL pattern: `^users/$` Name: `'user-list'` +* URL pattern: `^users/{pk}/$` Name: `'user-detail'` +* URL pattern: `^accounts/$` Name: `'account-list'` +* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'` + +### 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: + + @action(permission_classes=[IsAdminOrIsSelf]) + def set_password(self, request, pk=None): + ... + +The following URL pattern would additionally be generated: + +* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` + +# API Guide + +## SimpleRouter + +This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@link` or `@action` decorators. + + + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/GET@link decorated method{basename}-{methodname}
POST@action decorated method
+ +## DefaultRouter + +This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes. + + + + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
{prefix}/[.format]GETlist{basename}-list
POSTcreate
{prefix}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/[.format]GET@link decorated method{basename}-{methodname}
POST@action decorated method
+ +# Custom Routers + +Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic 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. + +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. + +## Example + +The following example will only route to the `list` and `retrieve` actions, and unlike the routers included by REST framework, it does not use the trailing slash convention. + + class ReadOnlyRouter(SimpleRouter): + """ + A router for read-only APIs, which doesn't use trailing suffixes. + """ + routes = [ + (r'^{prefix}$', {'get': 'list'}, '{basename}-list'), + (r'^{prefix}/{lookup}$', {'get': 'retrieve'}, '{basename}-detail') + ] + +## 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. + +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. + +[cite]: http://guides.rubyonrails.org/routing.html diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 6f1f28832..c83a0967e 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -25,6 +25,7 @@ Let's start by creating a simple object we can use for example purposes: comment = Comment(email='leila@example.com', content='foo bar') We'll declare a serializer that we can use to serialize and deserialize `Comment` objects. + Declaring a serializer looks very similar to declaring a form: class CommentSerializer(serializers.Serializer): @@ -33,14 +34,20 @@ Declaring a serializer looks very similar to declaring a form: created = serializers.DateTimeField() def restore_object(self, attrs, instance=None): + """ + Given a dictionary of deserialized field values, either update + an existing model instance, or create a new model instance. + """ if instance is not None: - instance.title = attrs['title'] - instance.content = attrs['content'] - instance.created = attrs['created'] + instance.title = attrs.get('title', instance.title) + instance.content = attrs.get('content', instance.content) + instance.created = attrs.get('created', instance.created) return instance return Comment(**attrs) -The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. The `restore_object` method is optional, and is only required if we want our serializer to support deserialization. +The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. + +The `restore_object` method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items. ## Serializing objects @@ -52,14 +59,15 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments. At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`. - stream = JSONRenderer().render(data) - stream + json = JSONRenderer().render(serializer.data) + json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' ## Deserializing objects Deserialization is similar. First we parse a stream into python native datatypes... + stream = StringIO(json) data = JSONParser().parse(stream) ...then we restore those native datatypes into a fully populated object instance. @@ -80,20 +88,21 @@ By default, serializers must be passed values for all required fields or they wi serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data -## Serializing querysets - -To serialize a queryset instead of an object instance, you should pass the `many=True` flag when instantiating the serializer. - - queryset = Comment.objects.all() - serializer = CommentSerializer(queryset, many=True) - serializer.data - # [{'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}, {'email': u'jamie@example.com', 'content': u'baz', 'created': datetime.datetime(2013, 1, 12, 16, 12, 45, 104445)}] - ## Validation -When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages. +When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example: -### Field-level validation + serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) + serializer.is_valid() + # False + serializer.errors + # {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']} + +Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. + +When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. + +#### Field-level validation You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are analagous to `.clean_` methods on Django forms, but accept slightly different arguments. @@ -116,7 +125,7 @@ Your `validate_` methods should either just return the `attrs` dictio raise serializers.ValidationError("Blog post is not about Django") return attrs -### Object-level validation +#### Object-level validation To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example: @@ -137,26 +146,44 @@ To do any other validation that requires access to multiple fields, add a method ## Saving object state -Serializers also include a `.save()` method that you can override if you want to provide a method of persisting the state of a deserialized object. The default behavior of the method is to simply call `.save()` on the deserialized object instance. +To save the deserialized objects created by a serializer, call the `.save()` method: + + if serializer.is_valid(): + serializer.save() + +The default behavior of the method is to simply call `.save()` on the deserialized object instance. You can override the default save behaviour by overriding the `.save_object(obj)` method on the serializer class. The generic views provided by REST framework call the `.save()` method when updating or creating entities. ## Dealing with nested objects -The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, -where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. +The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): - email = serializers.Field() - username = serializers.Field() + email = serializers.EmailField() + username = serializers.CharField(max_length=100) class CommentSerializer(serializers.Serializer): user = UserSerializer() - title = serializers.Field() - content = serializers.Field() - created = serializers.Field() + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + +If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer. + + class CommentSerializer(serializers.Serializer): + user = UserSerializer(required=False) # May be an anonymous user. + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + +Similarly if a nested representation should be a list of items, you should the `many=True` flag to the nested serialized. + + class CommentSerializer(serializers.Serializer): + user = UserSerializer(required=False) + edits = EditItemSerializer(many=True) # A nested list of 'edit' items. + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() --- @@ -164,6 +191,96 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent --- +## Dealing with multiple objects + +The `Serializer` class can also handle serializing or deserializing lists of objects. + +#### Serializing multiple objects + +To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. + + queryset = Book.objects.all() + serializer = BookSerializer(queryset, many=True) + serializer.data + # [ + # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, + # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, + # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} + # ] + +#### Deserializing multiple objects for creation + +To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the `many=True` flag, and pass a list of data to be deserialized. + +This allows you to write views that create multiple items when a `POST` request is made. + +For example: + + data = [ + {'title': 'The bell jar', 'author': 'Sylvia Plath'}, + {'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'} + ] + serializer = BookSerializer(data=data, many=True) + serializer.is_valid() + # True + serializer.save() # `.save()` will be called on each deserialized instance + +#### Deserializing multiple objects for update + +You can also deserialize a list of objects as part of a bulk update of multiple existing items. +In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with. + +This allows you to write views that update or create multiple items when a `PUT` request is made. + + # Capitalizing the titles of the books + queryset = Book.objects.all() + data = [ + {'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'}, + {'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'} + ] + serializer = BookSerializer(queryset, data=data, many=True) + serializer.is_valid() + # True + serialize.save() # `.save()` will be called on each updated or newly created instance. + +By default bulk updates will be limited to updating instances that already exist in the provided queryset. + +When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass `allow_add_remove=True` to the serializer. + + serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True) + serializer.is_valid() + # True + serializer.save() # `.save()` will be called on updated or newly created instances. + # `.delete()` will be called on any other items in the `queryset`. + +Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects. + +#### How identity is determined when performing bulk updates + +Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances. + +By default the serializer class will use the `id` key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the `get_identity` method on the `Serializer` class. For example: + + class AccountSerializer(serializers.Serializer): + slug = serializers.CharField(max_length=100) + created = serializers.DateTimeField() + ... # Various other fields + + def get_identity(self, data): + """ + This hook is required for bulk update. + We need to override the default, to use the slug as the identity. + + Note that the data has not yet been validated at this point, + so we need to deal gracefully with incorrect datatypes. + """ + try: + return data.get('slug', None) + except AttributeError: + return None + +To map the incoming data items to their corresponding object instances, the `.get_identity()` method will be called both against the incoming data, and against the serialized representation of the existing objects. + ## Including extra context There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. @@ -176,50 +293,9 @@ You can provide arbitrary additional context by passing a `context` argument whe The context dictionary can be used within any serializer field logic, such as a custom `.to_native()` method, by accessing the `self.context` attribute. -## Creating custom fields - -If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects. - -The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation. - -Let's look at an example of serializing a class that represents an RGB color value: - - class Color(object): - """ - A color represented in the RGB colorspace. - """ - def __init__(self, red, green, blue): - assert(red >= 0 and green >= 0 and blue >= 0) - assert(red < 256 and green < 256 and blue < 256) - self.red, self.green, self.blue = red, green, blue - - class ColourField(serializers.WritableField): - """ - Color objects are serialized into "rgb(#, #, #)" notation. - """ - def to_native(self, obj): - return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) - - def from_native(self, data): - data = data.strip('rgb(').rstrip(')') - red, green, blue = [int(col) for col in data.split(',')] - return Color(red, green, blue) - - -By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`. - -As an example, let's create a field that can be used represent the class name of the object being serialized: - - class ClassNameField(serializers.Field): - def field_to_native(self, obj, field_name): - """ - Serialize the object's class name. - """ - return obj.__class__ - --- -# ModelSerializers +# ModelSerializer Often you'll want serializer classes that map closely to model definitions. The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields. @@ -230,7 +306,42 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit By default, all the model fields on the class will be mapped to corresponding serializer fields. -Any foreign keys on the model will be mapped to `PrimaryKeyRelatedField` if you're using a `ModelSerializer`, or `HyperlinkedRelatedField` if you're using a `HyperlinkedModelSerializer`. +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. + +## 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`. + +For example: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + +## Specifying nested serialization + +The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + depth = 1 + +The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. + +## Specifying which fields should be read-only + +You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + read_only_fields = ('account_name',) + +Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option. ## Specifying fields explicitly @@ -253,43 +364,68 @@ Alternative representations include serializing using hyperlinks, serializing co For full details see the [serializer relations][relations] documentation. -## 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`. +# HyperlinkedModelSerializer -For example: +The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys. - class AccountSerializer(serializers.ModelSerializer): +By default the serializer will include a `url` field instead of a primary key field. + +The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field. + +You can explicitly include the primary key by adding it to the `fields` option, for example: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account - exclude = ('id',) + fields = ('url', 'id', 'account_name', 'users', 'created') -## Specifiying nested serialization +## How hyperlinked views are determined -The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: +There needs to be a way of determining which views should be used for hyperlinking to model instances. - class AccountSerializer(serializers.ModelSerializer): +By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument. + +You can change the field that is used for object lookups by setting the `lookup_field` option. The value of this option should correspond both with a kwarg in the URL conf, and with an field on the model. For example: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account - exclude = ('id',) - depth = 1 + fields = ('url', 'account_name', 'users', 'created') + lookup_field = 'slug' -The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. +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: -## Specifying which fields should be read-only + class AccountSerializer(serializers.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name='account_detail', + lookup_field='account_name' + ) + users = serializers.HyperlinkedRelatedField( + view_name='user-detail', + lookup_field='username', + many=True, + read_only=True + ) -You may wish to specify multiple fields as read-only. Instead of adding each field explicitely with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: - - class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account - read_only_fields = ('created', 'modified') + fields = ('url', 'account_name', 'users', 'created') + +--- + +# Advanced serializer usage + +You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields. + +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. ## Customising the default fields -You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get__field` methods. +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. -Each of these methods may either return a field or serializer instance, or `None`. +For more advanced customization than simply changing the default serializer class you can override various `get__field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`. ### get_pk_field @@ -299,23 +435,27 @@ Returns the field instance that should be used to represent the pk field. ### get_nested_field -**Signature**: `.get_nested_field(self, model_field)` +**Signature**: `.get_nested_field(self, model_field, related_model, to_many)` Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero. +Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship. + ### get_related_field -**Signature**: `.get_related_field(self, model_field, to_many=False)` +**Signature**: `.get_related_field(self, model_field, related_model, to_many)` Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero. +Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship. + ### get_field **Signature**: `.get_field(self, model_field)` 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 e103fbab4..b00ab4c1d 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,78 @@ 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 +#### DEFAULT_FILTER_BACKENDS -The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled. +A list of filter backend classes 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 +161,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 +169,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 +177,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,16 +185,75 @@ 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 and time formatting + +*The following settings are used to control how date and time representations may be parsed and rendered.* + +#### DATETIME_FORMAT + +A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return python `datetime` objects, and the datetime encoding will be determined by the renderer. + +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None` + +#### DATETIME_INPUT_FORMATS + +A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields. + +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + +Default: `['iso-8601']` + +#### DATE_FORMAT + +A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return python `date` objects, and the date encoding will be determined by the renderer. + +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None` + +#### DATE_INPUT_FORMATS + +A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields. + +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + +Default: `['iso-8601']` + +#### TIME_FORMAT + +A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return python `time` objects, and the time encoding will be determined by the renderer. + +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None` + +#### TIME_INPUT_FORMATS + +A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields. + +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + +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. Default: `'format'` [cite]: http://www.python.org/dev/peps/pep-0020/ +[strftime]: http://docs.python.org/2/library/time.html#time.strftime diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 1abd49f47..d6de85ba8 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -40,7 +40,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. -You can also set the throttling policy on a per-view basis, using the `APIView` class based views. +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,) @@ -167,4 +168,4 @@ The following is an example of a rate throttle, that will randomly throttle 1 in [cite]: https://dev.twitter.com/docs/error-codes-responses [permissions]: permissions.md [cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches -[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache \ No newline at end of file +[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md new file mode 100644 index 000000000..cd92dc585 --- /dev/null +++ b/docs/api-guide/viewsets.md @@ -0,0 +1,219 @@ + + +# ViewSets + +> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. +> +> — [Ruby on Rails Documentation][cite] + + +Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. + +A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. + +The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. + +Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. + +## Example + +Let's define a simple viewset that can be used to list or retrieve all the users in the system. + + class UserViewSet(viewsets.ViewSet): + """ + A simple ViewSet that for listing or retrieving users. + """ + def list(self, request): + queryset = User.objects.all() + serializer = UserSerializer(queryset, many=True) + return Response(serializer.data) + + def retrieve(self, request, pk=None): + queryset = User.objects.all() + user = get_object_or_404(queryset, pk=pk) + serializer = UserSerializer(user) + return Response(serializer.data) + +If we need to, we can bind this viewset into two seperate views, like so: + + user_list = UserViewSet.as_view({'get': 'list'}) + user_detail = UserViewSet.as_view({'get': 'retrieve'}) + +Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. + + router = DefaultRouter() + router.register(r'users', UserViewSet) + urlpatterns = router.urls + +Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: + + class UserViewSet(viewsets.ModelViewSet): + """ + A viewset for viewing and editing user instances. + """ + serializer_class = UserSerializer + queryset = User.objects.all() + +There are two main advantages of using a `ViewSet` class over using a `View` class. + +* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. +* By using routers, we no longer need to deal with wiring up the URL conf ourselves. + +Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. + +## Marking extra methods for routing + +The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below: + + class UserViewSet(viewsets.VietSet): + """ + Example empty viewset demonstrating the standard + actions that will be handled by a router class. + + If you're using format suffixes, make sure to also include + the `format=None` keyword argument for each action. + """ + + def list(self, request): + pass + + def create(self, request): + pass + + def retrieve(self, request, pk=None): + pass + + def update(self, request, pk=None): + pass + + def partial_update(self, request, pk=None): + pass + + def destroy(self, request, pk=None): + pass + +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decroator will route `POST` requests. + +For example: + + from django.contrib.auth.models import User + from rest_framework import viewsets + from rest_framework.decorators import action + from myapp.serializers import UserSerializer + + class UserViewSet(viewsets.ModelViewSet): + """ + A viewset that provides the standard actions + """ + queryset = User.objects.all() + serializer_class = UserSerializer + + @action + def set_password(self, request, pk=None): + user = self.get_object() + serializer = PasswordSerializer(data=request.DATA) + if serializer.is_valid(): + user.set_password(serializer.data['password']) + user.save() + return Response({'status': 'password set'}) + else: + return Response(serializer.errors, + status=status.HTTP_400_BAD_REQUEST) + +The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example... + + @action(permission_classes=[IsAdminOrIsSelf]) + def set_password(self, request, pk=None): + ... + +--- + +# API Reference + +## ViewSet + +The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. + +The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. + +## GenericViewSet + +The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default. + +In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. + +## ModelViewSet + +The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. + +The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. + +#### Example + +Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + +Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing the accounts + associated with the user. + """ + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + + def get_queryset(self): + return 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. + +## ReadOnlyModelViewSet + +The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. + +#### Example + +As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ReadOnlyModelViewSet): + """ + A simple ViewSet for viewing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + +Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. + +# Custom ViewSet base classes + +You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way. + +## Example + +To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions: + + class CreateListRetrieveViewSet(mixins.CreateMixin, + mixins.ListMixin, + mixins.RetrieveMixin, + viewsets.GenericViewSet): + pass + + """ + A viewset that provides `retrieve`, `update`, and `list` actions. + + To use it, override the class and set the `.queryset` and + `.serializer_class` attributes. + """ + pass + +By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. + +[cite]: http://guides.rubyonrails.org/routing.html diff --git a/docs/css/default.css b/docs/css/default.css index 07c4884d1..998efa273 100644 --- a/docs/css/default.css +++ b/docs/css/default.css @@ -47,7 +47,7 @@ body.index-page #main-content iframe.twitter-share-button { body.index-page #main-content img.travis-build-image { float: right; margin-right: 8px; - margin-top: -9px; + margin-top: -11px; margin-bottom: 0px; } @@ -277,3 +277,24 @@ footer a { footer a:hover { color: gray; } + +.btn-inverse { + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important; + background-image: -webkit-linear-gradient(top, #606060, #404040) !important; +} + +.modal-open .modal,.btn:focus{outline:none;} + +@media (max-width: 650px) { + .repo-link.btn-inverse {display: none;} +} + +td, th { + padding: 0.25em; + background-color: #f7f7f9; + border-color: #e1e1e8; +} + +table { + border-color: white; +} diff --git a/docs/index.md b/docs/index.md index b2c04735a..7c38efd34 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,17 +9,21 @@ # Django REST framework -**A toolkit for building well-connected, self-describing Web APIs.** +**Awesome web-browsable Web APIs.** -Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. +Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs. -Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. +Some reasons you might want to use REST framework: -If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcement][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. +* The Web browseable API is a huge useability win for your developers. +* Authentication policies including OAuth1a and OAuth2 out of the box. +* Serialization that supports both ORM and non-ORM data sources. +* Customizable all the way down - just use regular function-based views if you don't need the more powerful features. +* Extensive documentation, and great community support. -There is also a sandbox API you can use for testing purposes, [available here][sandbox]. +There is a live example API for testing purposes, [available here][sandbox]. -**Below**: *Screenshot from the browseable API* +**Below**: *Screenshot from the browsable API* ![Screenshot][image] @@ -32,26 +36,26 @@ REST framework requires the following: The following packages are optional: -* [Markdown][markdown] (2.1.0+) - Markdown support for the browseable API. +* [Markdown][markdown] (2.1.0+) - Markdown support for the browsable API. * [PyYAML][yaml] (3.10+) - YAML content-type support. * [defusedxml][defusedxml] (0.3+) - XML content-type support. * [django-filter][django-filter] (0.5.4+) - Filtering support. +* [django-oauth-plus][django-oauth-plus] (2.0+) and [oauth2][oauth2] (1.5.211+) - OAuth 1.0a support. +* [django-oauth2-provider][django-oauth2-provider] (0.2.3+) - OAuth 2.0 support. + +**Note**: The `oauth2` python package is badly misnamed, and actually provides OAuth 1.0a support. Also note that packages required for both OAuth 1.0a, and OAuth 2.0 are not yet Python 3 compatible. ## Installation Install using `pip`, including any optional packages you want... pip install djangorestframework - pip install markdown # Markdown support for the browseable API. - pip install pyyaml # YAML content-type support. + pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ...or clone the project from github. git clone git@github.com:tomchristie/django-rest-framework.git - cd django-rest-framework - pip install -r requirements.txt - pip install -r optionals.txt Add `'rest_framework'` to your `INSTALLED_APPS` setting. @@ -60,7 +64,7 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting. 'rest_framework', ) -If you're intending to use the browseable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. +If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. urlpatterns = patterns('', ... @@ -69,9 +73,60 @@ If you're intending to use the browseable API you'll probably also want to add R Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. +## Example + +Let's take a look at a quick example of using REST framework to build a simple model-backed API. + +We'll create a read-write API for accessing users and groups. + +Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module: + + REST_FRAMEWORK = { + # Use hyperlinked styles by default. + # Only used if the `serializer_class` attribute is not set on a view. + 'DEFAULT_MODEL_SERIALIZER_CLASS': + 'rest_framework.serializers.HyperlinkedModelSerializer', + + # Use Django's standard `django.contrib.auth` permissions, + # or allow read-only access for unauthenticated users. + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' + ] + } + +Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS`. + +We're ready to create our API now. +Here's our project's root `urls.py` module: + + from django.conf.urls.defaults import url, patterns, include + from django.contrib.auth.models import User, Group + from rest_framework import viewsets, routers + + # ViewSets define the view behavior. + class UserViewSet(viewsets.ModelViewSet): + model = User + + class GroupViewSet(viewsets.ModelViewSet): + model = Group + + + # Routers provide an easy way of automatically determining the URL conf + router = routers.DefaultRouter() + router.register(r'users', UserViewSet) + router.register(r'groups', GroupViewSet) + + + # Wire up our API using automatic URL routing. + # Additionally, we include login URLs for the browseable API. + urlpatterns = patterns('', + url(r'^', include(router.urls)), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) + ) + ## Quickstart -Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running with REST framework. +Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework. ## Tutorial @@ -82,6 +137,7 @@ The tutorial will walk you through the building blocks that make up REST framewo * [3 - Class based views][tut-3] * [4 - Authentication & permissions][tut-4] * [5 - Relationships & hyperlinked APIs][tut-5] +* [6 - Viewsets & routers][tut-6] ## API Guide @@ -91,6 +147,8 @@ The API guide is your complete reference manual to all the functionality provide * [Responses][response] * [Views][views] * [Generic views][generic-views] +* [Viewsets][viewsets] +* [Routers][routers] * [Parsers][parsers] * [Renderers][renderers] * [Serializers][serializers] @@ -118,6 +176,7 @@ General guides to using REST framework. * [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas] * [2.0 Announcement][rest-framework-2-announcement] * [2.2 Announcement][2.2-announcement] +* [2.3 Announcement][2.3-announcement] * [Release Notes][release-notes] * [Credits][credits] @@ -133,6 +192,10 @@ Run the tests: ./rest_framework/runtests/runtests.py +To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`: + + tox + ## Support For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag. @@ -176,6 +239,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [yaml]: http://pypi.python.org/pypi/PyYAML [defusedxml]: https://pypi.python.org/pypi/defusedxml [django-filter]: http://pypi.python.org/pypi/django-filter +[oauth2]: https://github.com/simplegeo/python-oauth2 +[django-oauth-plus]: https://bitbucket.org/david/django-oauth-plus/wiki/Home +[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X [image]: img/quickstart.png [sandbox]: http://restframework.herokuapp.com/ @@ -186,11 +252,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [tut-3]: tutorial/3-class-based-views.md [tut-4]: tutorial/4-authentication-and-permissions.md [tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md +[tut-6]: tutorial/6-viewsets-and-routers.md [request]: api-guide/requests.md [response]: api-guide/responses.md [views]: api-guide/views.md [generic-views]: api-guide/generic-views.md +[viewsets]: api-guide/viewsets.md +[routers]: api-guide/routers.md [parsers]: api-guide/parsers.md [renderers]: api-guide/renderers.md [serializers]: api-guide/serializers.md @@ -215,9 +284,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [contributing]: topics/contributing.md [rest-framework-2-announcement]: topics/rest-framework-2-announcement.md [2.2-announcement]: topics/2.2-announcement.md +[2.3-announcement]: topics/2.3-announcement.md [release-notes]: topics/release-notes.md [credits]: topics/credits.md +[tox]: http://testrun.org/tox/latest/ + [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [stack-overflow]: http://stackoverflow.com/ [django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework diff --git a/docs/template.html b/docs/template.html index e0f88daf5..53656e7d4 100644 --- a/docs/template.html +++ b/docs/template.html @@ -2,11 +2,11 @@ - Django REST framework + {{ title }} - - + + @@ -41,6 +41,9 @@