aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api-guide')
-rw-r--r--docs/api-guide/authentication.md31
-rw-r--r--docs/api-guide/fields.md180
-rw-r--r--docs/api-guide/filtering.md7
-rw-r--r--docs/api-guide/generic-views.md60
-rw-r--r--docs/api-guide/pagination.md33
-rw-r--r--docs/api-guide/parsers.md13
-rw-r--r--docs/api-guide/permissions.md2
-rw-r--r--docs/api-guide/relations.md139
-rw-r--r--docs/api-guide/renderers.md14
-rw-r--r--docs/api-guide/serializers.md35
-rw-r--r--docs/api-guide/settings.md22
-rw-r--r--docs/api-guide/views.md4
12 files changed, 388 insertions, 152 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index b2323d62..4dfcb0f1 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -126,19 +126,36 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
+<<<<<<< HEAD
<!--## OAuth2Authentication
+=======
+If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
-This authentication scheme uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
+ @receiver(post_save, sender=User)
+ def create_auth_token(sender, instance=None, created=False, **kwargs):
+ if created:
+ Token.objects.create(user=instance)
-If successfully authenticated, `OAuth2Authentication` provides the following credentials.
+If you've already created some users, you can generate tokens for all existing users like this:
-* `request.user` will be a Django `User` instance.
-* `request.auth` will be a `rest_framework.models.OAuthToken` instance.
+ from django.contrib.auth.models import User
+ from rest_framework.authtoken.models import Token
+
+ 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:
+
+ urlpatterns += patterns('',
+ url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
+ )
+
+Note that the URL part of the pattern can be whatever you want to use.
-**TODO**: Note type of response (401 vs 403)
+The `obtain_auth_token` view will return a JSON response when valid `username` and `password` fields are POSTed to the view using form data or JSON:
-**TODO**: Implement OAuth2Authentication, using django-oauth2-provider.
--->
+ { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
## SessionAuthentication
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 0485b158..5bc8f7f7 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,11 +2,11 @@
# Serializer fields
-> Flat is better than nested.
+> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it -- normalizing it to a consistent format.
>
-> &mdash; [The Zen of Python][cite]
+> &mdash; [Django documentation][cite]
-Serializer fields handle converting between primative values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
+Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
---
@@ -28,7 +28,7 @@ Defaults to the name of the field.
### `read_only`
-Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
+Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.
Defaults to `False`
@@ -41,7 +41,7 @@ Defaults to `True`.
### `default`
-If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all.
+If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all.
### `validators`
@@ -96,9 +96,9 @@ Would produce output similar to:
'expired': True
}
-By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary.
+By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
-You can customize this behaviour by overriding the `.to_native(self, value)` method.
+You can customize this behavior by overriding the `.to_native(self, value)` method.
## WritableField
@@ -110,6 +110,24 @@ A generic field that can be tied to any arbitrary model field. The `ModelField`
**Signature:** `ModelField(model_field=<Django ModelField class>)`
+## SerializerMethodField
+
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
+ from rest_framework import serializers
+ from django.contrib.auth.models import User
+ from django.utils.timezone import now
+
+ class UserSerializer(serializers.ModelSerializer):
+
+ days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
+
---
# Typed Fields
@@ -131,6 +149,18 @@ or `django.db.models.fields.TextField`.
**Signature:** `CharField(max_length=None, min_length=None)`
+## URLField
+
+Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
+
+**Signature:** `CharField(max_length=200, min_length=None)`
+
+## SlugField
+
+Corresponds to `django.db.models.fields.SlugField`.
+
+**Signature:** `CharField(max_length=50, min_length=None)`
+
## ChoiceField
A field that can accept a value out of a limited set of choices.
@@ -141,6 +171,16 @@ A text representation, validates the text to be a valid e-mail address.
Corresponds to `django.db.models.fields.EmailField`
+## RegexField
+
+A text representation, that validates the given value matches against a certain regular expression.
+
+Uses Django's `django.core.validators.RegexValidator` for validation.
+
+Corresponds to `django.forms.fields.RegexField`
+
+**Signature:** `RegexField(regex, max_length=None, min_length=None)`
+
## DateField
A date representation.
@@ -165,124 +205,32 @@ A floating point representation.
Corresponds to `django.db.models.fields.FloatField`.
----
-
-# Relational Fields
-
-Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
+## FileField
-## RelatedField
+A file representation. Performs Django's standard FileField validation.
-This field can be applied to any of the following:
+Corresponds to `django.forms.fields.FileField`.
-* A `ForeignKey` field.
-* A `OneToOneField` field.
-* A reverse OneToOne relationship
-* Any other "to-one" relationship.
+**Signature:** `FileField(max_length=None, allow_empty_file=False)`
-By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+ - `max_length` designates the maximum length for the file name.
+
+ - `allow_empty_file` designates if empty files are allowed.
-You can customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
+## ImageField
-## ManyRelatedField
+An image representation.
-This field can be applied to any of the following:
-
-* A `ManyToManyField` field.
-* A reverse ManyToMany relationship.
-* A reverse ForeignKey relationship
-* Any other "to-many" relationship.
+Corresponds to `django.forms.fields.ImageField`.
-By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+Requires the `PIL` package.
-For example, given the following models:
+Signature and validation is the same as with `FileField`.
- class TaggedItem(models.Model):
- """
- Tags arbitrary model instances using a generic relation.
-
- See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
- """
- tag = models.SlugField()
- content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
- content_object = GenericForeignKey('content_type', 'object_id')
-
- def __unicode__(self):
- return self.tag
-
-
- class Bookmark(models.Model):
- """
- A bookmark consists of a URL, and 0 or more descriptive tags.
- """
- url = models.URLField()
- tags = GenericRelation(TaggedItem)
-
-And a model serializer defined like this:
-
- class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
-
- class Meta:
- model = Bookmark
- exclude = ('id',)
-
-Then an example output format for a Bookmark instance would be:
-
- {
- 'tags': [u'django', u'python'],
- 'url': u'https://www.djangoproject.com/'
- }
-
-## PrimaryKeyRelatedField / ManyPrimaryKeyRelatedField
-
-`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
-
-By default these fields are read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `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`.
-
-## SlugRelatedField / ManySlugRelatedField
-
-`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
-
-By default these fields read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
-* `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`.
-
-## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
-
-`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
-
-By default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `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`.
-
-## HyperLinkedIdentityField
-
-This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
-
-This field is always read-only.
-
-**Arguments**:
+---
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `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`.
+**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
+Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
-[cite]: http://www.python.org/dev/peps/pep-0020/
+[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
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 14ab9a26..53ea7cbc 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -71,7 +71,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
by filtering against a `username` query parameter in the URL.
"""
queryset = Purchase.objects.all()
- username = self.request.QUERY_PARAMS.get('username', None):
+ username = self.request.QUERY_PARAMS.get('username', None)
if username is not None:
queryset = queryset.filter(purchaser__username=username)
return queryset
@@ -84,9 +84,9 @@ As well as being able to override the default queryset, REST framework also incl
REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package.
-To use REST framework's default filtering backend, first install `django-filter`.
+To use REST framework's filtering backend, first install `django-filter`.
- pip install -e git+https://github.com/alex/django-filter.git#egg=django-filter
+ pip install django-filter
You must also set the filter backend to `DjangoFilterBackend` in your settings:
@@ -94,7 +94,6 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings:
'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend'
}
-**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
## Specifying filter fields
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 360ef1a2..693e210d 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -7,11 +7,11 @@
>
> &mdash; [Django Documentation][cite]
-One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
+One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
-If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
+If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
## Examples
@@ -29,7 +29,7 @@ For more complex cases you might also want to override various methods on the vi
model = User
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
-
+
def get_paginate_by(self, queryset):
"""
Use smaller pagination for HTML representations.
@@ -85,7 +85,7 @@ Extends: [SingleObjectAPIView], [DestroyModelMixin]
Used for **update-only** endpoints for a **single model instance**.
-Provides a `put` method handler.
+Provides `put` and `patch` method handlers.
Extends: [SingleObjectAPIView], [UpdateModelMixin]
@@ -97,6 +97,14 @@ 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**.
@@ -109,7 +117,7 @@ Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin]
Used for **read-write-delete** endpoints to represent a **single model instance**.
-Provides `get`, `put` and `delete` method handlers.
+Provides `get`, `put`, `patch` and `delete` method handlers.
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
@@ -123,52 +131,90 @@ Each of the generic views provided is built by combining one of the base views b
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
+**Attributes**:
+
+* `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.
+
## MultipleObjectAPIView
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin].
**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'`.
+
---
# 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 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.
## ListModelMixin
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
+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].
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
+If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
+
+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].
## UpdateModelMixin
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
+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].
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
@@ -184,4 +230,4 @@ Should be mixed in with [SingleObjectAPIView].
[CreateModelMixin]: #createmodelmixin
[RetrieveModelMixin]: #retrievemodelmixin
[UpdateModelMixin]: #updatemodelmixin
-[DestroyModelMixin]: #destroymodelmixin \ No newline at end of file
+[DestroyModelMixin]: #destroymodelmixin
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 597baba4..ab335e6e 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -70,33 +70,32 @@ We could now use our pagination serializer in a view like this.
# If page is not an integer, deliver first page.
users = paginator.page(1)
except EmptyPage:
- # If page is out of range (e.g. 9999), deliver last page of results.
+ # If page is out of range (e.g. 9999),
+ # deliver last page of results.
users = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
- serializer = PaginatedUserSerializer(instance=users,
+ serializer = PaginatedUserSerializer(users,
context=serializer_context)
return Response(serializer.data)
## Pagination in the generic views
-The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, or by turning pagination off completely.
+The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.
-The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example.
+The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY` and `PAGINATE_BY_PARAM` settings. For example.
REST_FRAMEWORK = {
- 'PAGINATION_SERIALIZER': (
- 'example_app.pagination.CustomPaginationSerializer',
- ),
- 'PAGINATE_BY': 10
+ 'PAGINATE_BY': 10,
+ 'PAGINATE_BY_PARAM': 'page_size'
}
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
class PaginatedListView(ListAPIView):
model = ExampleModel
- pagination_serializer_class = CustomPaginationSerializer
paginate_by = 10
+ paginate_by_param = 'page_size'
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
@@ -122,4 +121,20 @@ For example, to nest a pair of links labelled 'prev' and 'next', and set the nam
results_field = 'objects'
+## Using your custom pagination serializer
+
+To have your custom pagination serializer be used by default, use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting:
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_PAGINATION_SERIALIZER_CLASS':
+ 'example_app.pagination.CustomPaginationSerializer',
+ }
+
+Alternatively, to set your custom pagination serializer on a per-view basis, use the `pagination_serializer_class` attribute on a generic class based view:
+
+ class PaginatedListView(ListAPIView):
+ model = ExampleModel
+ pagination_serializer_class = CustomPaginationSerializer
+ paginate_by = 10
+
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 185b616c..9356b420 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -159,4 +159,17 @@ For example:
files = {name: uploaded}
return DataAndFiles(data, files)
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## MessagePack
+
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
+
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
+[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
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 1a746fb6..fce68f6d 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -53,7 +53,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
Or, if you're using the `@api_view` decorator with function based views.
@api_view('GET')
- @permission_classes(IsAuthenticated)
+ @permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
content = {
'status': 'request was permitted'
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
new file mode 100644
index 00000000..351b5e09
--- /dev/null
+++ b/docs/api-guide/relations.md
@@ -0,0 +1,139 @@
+<a class="github" href="relations.py"></a>
+
+# Serializer relations
+
+> Bad programmers worry about the code.
+> Good programmers worry about data structures and their relationships.
+>
+> &mdash; [Linus Torvalds][cite]
+
+
+Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
+
+---
+
+**Note:** The relational fields are declared in `relations.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
+
+---
+
+## RelatedField
+
+This field can be applied to any of the following:
+
+* A `ForeignKey` field.
+* A `OneToOneField` field.
+* A reverse OneToOne relationship
+* Any other "to-one" relationship.
+
+By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+
+You can customize this behavior by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
+
+## ManyRelatedField
+
+This field can be applied to any of the following:
+
+* A `ManyToManyField` field.
+* A reverse ManyToMany relationship.
+* A reverse ForeignKey relationship
+* Any other "to-many" relationship.
+
+By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+
+For example, given the following models:
+
+ class TaggedItem(models.Model):
+ """
+ Tags arbitrary model instances using a generic relation.
+
+ See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
+ """
+ tag = models.SlugField()
+ content_type = models.ForeignKey(ContentType)
+ object_id = models.PositiveIntegerField()
+ content_object = GenericForeignKey('content_type', 'object_id')
+
+ def __unicode__(self):
+ return self.tag
+
+
+ class Bookmark(models.Model):
+ """
+ A bookmark consists of a URL, and 0 or more descriptive tags.
+ """
+ url = models.URLField()
+ tags = GenericRelation(TaggedItem)
+
+And a model serializer defined like this:
+
+ class BookmarkSerializer(serializers.ModelSerializer):
+ tags = serializers.ManyRelatedField(source='tags')
+
+ class Meta:
+ model = Bookmark
+ exclude = ('id',)
+
+Then an example output format for a Bookmark instance would be:
+
+ {
+ 'tags': [u'django', u'python'],
+ 'url': u'https://www.djangoproject.com/'
+ }
+
+## PrimaryKeyRelatedField
+## ManyPrimaryKeyRelatedField
+
+`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
+
+By default these fields are read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `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`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## SlugRelatedField
+## ManySlugRelatedField
+
+`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
+
+By default these fields read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
+* `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`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## HyperlinkedRelatedField
+## ManyHyperlinkedRelatedField
+
+`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
+
+By default, `HyperlinkedRelatedField` is read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `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`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## HyperLinkedIdentityField
+
+This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
+
+This field is always read-only.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `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`.
+
+[cite]: http://lwn.net/Articles/193245/
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 374ff0ab..389dec1f 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -271,6 +271,15 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## MessagePack
+
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md
@@ -280,4 +289,7 @@ Templates will render with a `RequestContext` which includes the `status_code` a
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
-[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views \ No newline at end of file
+[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
+[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
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 0cdae1ce..d98a602f 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -4,8 +4,7 @@
> Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
-will take some serious design work. Any offers to help out in this
-area would be gratefully accepted.
+will take some serious design work.
>
> &mdash; Russell Keith-Magee, [Django users group][cite]
@@ -34,7 +33,7 @@ Declaring a serializer looks very similar to declaring a form:
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
- if instance:
+ if instance is not None:
instance.title = attrs['title']
instance.content = attrs['content']
instance.created = attrs['created']
@@ -77,6 +76,10 @@ When deserializing data, we can either create a new instance, or update an exist
serializer = CommentSerializer(data=data) # Create new instance
serializer = CommentSerializer(comment, data=data) # Update `instance`
+By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the `partial` argument in order to allow partial updates.
+
+ serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data
+
## 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.
@@ -106,7 +109,22 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio
### 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`.
+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:
+
+ from rest_framework import serializers
+
+ class EventSerializer(serializers.Serializer):
+ description = serializers.CahrField(max_length=100)
+ start = serializers.DateTimeField()
+ finish = serializers.DateTimeField()
+
+ def validate(self, attrs):
+ """
+ Check that the start is before the stop.
+ """
+ if attrs['start'] < attrs['finish']:
+ raise serializers.ValidationError("finish must occur after start")
+ return attrs
## Saving object state
@@ -248,6 +266,15 @@ The default `ModelSerializer` uses primary keys for relationships, but you can a
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 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')
+
## 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_type>_field` methods.
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 4f87b30d..8c87f2ca 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -96,11 +96,21 @@ Default: `rest_framework.serializers.ModelSerializer`
Default: `rest_framework.pagination.PaginationSerializer`
-## FORMAT_SUFFIX_KWARG
+## FILTER_BACKEND
-**TODO**
+The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled.
-Default: `'format'`
+## PAGINATE_BY
+
+The default page size to use for pagination. If set to `None`, pagination is disabled by default.
+
+Default: `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 set to `None`, clients may not override the default page size.
+
+Default: `None`
## UNAUTHENTICATED_USER
@@ -150,4 +160,10 @@ Default: `'accept'`
Default: `'format'`
+## FORMAT_SUFFIX_KWARG
+
+**TODO**
+
+Default: `'format'`
+
[cite]: http://www.python.org/dev/peps/pep-0020/
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 5b072827..d1e42ec1 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -19,6 +19,10 @@ Using the `APIView` class is pretty much the same as using a regular `View` clas
For example:
+ from rest_framework.views import APIView
+ from rest_framework.response import Response
+ from rest_framework import authentication, permissions
+
class ListUsers(APIView):
"""
View to list all users in the system.